content
stringlengths
22
815k
id
int64
0
4.91M
def post_search(netid: str, client: ShrunkClient, req: Any) -> Any: """``POST /api/search`` Execute a search query. Request format: .. code-block:: json { "query?": "string", "set": { "set": "'user' | 'shared' | 'all' | 'org'", "org?": "string" }, ...
80,200
def os_error(): """Operating system error. AKA EnvironmentError / IOError.""" try: smtplib.SMTP('localhost:a_port') except OSError: return "bad port number"
80,201
def test_bert_all(inf, model_keyouts): """ Test nearest neighbour BERT classifier for all layers. """ from wsdeval.tools.ctx_embedder import bert_embedder inst_it = bert_embedder.iter_inst_vecs_grouped(inf) test_sesame_all(inst_it, model_keyouts)
80,202
def select_random_hashtag(): """ Returns a random hashtag from the latest posts or travel if none was found """ r = requests.get('https://api.instagram.com/v1/users/self/media/recent?access_token={}'.format(os.environ['ACCESS_TOKEN'])) if r.status_code == 200: data = r.json() tags = ...
80,203
def learn_oldfashion( env, agent, timesteps=1e5): """ Old-fashion runner for RL agent: Expriment environment, memorize experiences and execute RL updates. Parameters ---------- env: gym.Env OpenAI Gym environment agent: sweet.agents.agent.Agent ...
80,204
def test_delete_param_exception(sqlalchemy_engine, caplog): """ Test the delete function of the param persist sqlalchemy agent using a bad id. """ agent = SqlAlchemyAgent(sqlalchemy_engine) with caplog.at_level(logging.WARNING): agent.delete('not-a-valid-uuid') assert 'unable to query da...
80,205
def multivariate_potential(ptset2, meanvec, covmat): """ Vectorised evaluation of multivariate Gaussian pdf. Args: ptset: shape (N, d) mean: shape (d,) covar: shape (d,) Raises: AssertionError: if ptset, mean and covar have not consistent shape Returns: resul...
80,206
def test_apigateway_invoke_localhost_with_path( cfn_client, deploy_cfn_template, stepfunctions_client ): """tests the same as above but with the "generic" localhost version of invoking the apigateway""" deploy_result = deploy_cfn_template( template_path=os.path.join( os.path.dirname(__fi...
80,207
def restart(backend): """Restart the running server from an async test function. This fixture deals with possible differences between the environment of the test function and that of the server. """ async def restart(server): await backend.run_in_threadpool(AsyncioBackend().run, server.res...
80,208
def colinterp(a,x) : """Interpolates colors""" l = len(a)-1 i = min(l, max(0, int (x * l))) (u,v) = a[i:i+2,:] return u - (u-v) * ((x * l) % 1.0)
80,209
def test_temperature_successfully_retrieved(requests_mock_get): """ Check that the request to Accuweather service is properly build and the current temperature is successfully retrieved """ get, response = requests_mock_get response.status_code = 200 response.json = lambda: { 'simple...
80,210
def setFocus(*args, **kwargs): """ Give keyboard focus to a specific control or panel, passed as an argument. Returns: None """ pass
80,211
def accepted_content_type(f): """ Check if the requested content type is application/json. """ def decorator(*args, **kwargs): if request.content_type != 'application/json': raise ServiceException('Content type must be application/json', 400) return f(*args, **kwargs) r...
80,212
def test_esd_lbaas_fallback_persist_lbaas_persist(track_bigip_cfg, ESD_Pairs_Experiment): """Validate application of a pair of tags.""" apply_validate_remove_validate(ESD_Pairs_Experiment)
80,213
def get_articles_html(url_articles: str) -> str: """Wraps HTTP requests.get for testibility Parameters ---------- url_articles : str Articles URL Returns ------- str HTML page of articles """ articles_html = requests.get( url_articles, headers={"User-Agent":...
80,214
def ei_merit(X, surrogate, fX, XX=None, dtol=0): """Compute the expected improvement merit function. :param X: Points where to compute EI, of size n x dim :type X: numpy.array :param surrogate: Surrogate model object, must implement predict_std :type surrogate: object :param fX: Values at previ...
80,215
def load_audio( path: Path, channel: Optional[int] = None, mmap: bool = False, channel_names: List[str] = ["left", "right"], ) -> MultiTrack: """load waveform from file""" multiTrack = MultiTrack() assert 0 < len(channel_names) <= 2 try: fs, value = wav_read(path, mmap=mmap) ...
80,216
def test_ppo_strategy(df): """Checks PPO strategy calculates correctly.""" series_name = "close" df_with_allocations = allocations.PPO_strategy(df, 26, 12, 9, max_investment) df_with_signals = percentage_series_oscillator(df, 26, 12, 9, series_name) above_zero = df_with_signals["signal"] > 0 be...
80,217
def alarm(bot, job): """Send the alarm message.""" reply_text = 'Beep!' logging.info('>> %s' % reply_text) bot.send_message(job.context, text=reply_text)
80,218
def render_robots_meta_tag(context): """ Returns the robots meta tag. """ request = context['request'] robots_indexing = None robots_following = None # Prevent indexing any unwanted domains (e.g. staging). if context.request.get_host() in settings.META_TAGGER_ROBOTS_DOMAIN_WHITELIST: ...
80,219
def search(search_string)->Dict: """ API to search "search_string" in the stored documents :param search_string: search string provided by the user :type search_string: str :return: returns results i.e. return list of documents that are closest match to the search string :rtype: dict """ ...
80,220
def convert_lang_code(code): """ Map a language code to the canonical one that ConceptNet 5 uses, using the 'langcodes' library. """ return str(langcodes.get(code))
80,221
def solution_math( A: np.array, B: np.array, threshold: int = 1_000_000_000, scale: int = 1_000_000 ) -> int: """Math based method. See tutorial/examples in docs for more details.add() Parameters ---------- A : np.array integer part of the decimal numbers B : np.array decimal pa...
80,222
def tag_list(context, addon, tags=[]): """Display list of tags, with delete buttons.""" c = dict(context.items()) c.update({'addon': addon, 'tags': tags}) return c
80,223
def make_range_partition(min_val, max_val): """ Returns a new partitioning function that partitions keys in the range *[min_val:max_val]* into equal sized partitions. The number of partitions is defined by the *partitions* parameter """ r = max_val - min_val f = ("lambda k_n_p: int(round(fl...
80,224
def sparse_mx_to_torch_sparse_tensor(sparse_mx): """Convert a scipy sparse matrix to a torch sparse tensor.""" sparse_mx = sparse_mx.tocoo().astype(np.float32) indices = torch.from_numpy(np.vstack((sparse_mx.row,sparse_mx.col)).astype(np.int64)) values = torch.from_numpy(sparse_mx.data) shape = torc...
80,225
def split_outside(a, sep, start="([{", end=")]}"): """Split string a at occurences of separator sep, except when it occurs inside matching groups of start and end characters.""" segments = split_by_group(a, start, end) res = [""] for seg in segments: if len(seg) == 0: continue if seg[0] in start: res[-1] +=...
80,226
def gen_unique_image_path(standard_image_path, image_num): """ Generates a unique image path based on the standard_image_path by adding the IMAGE_IDENTIFIER_SEQUENCE followed by a number """ # Index where extension sequence starts (.jpg, .jpeg, or .png) extension_start = standard_image_path.lowe...
80,227
def try_wrapper( func: callable, *args, ret_: Optional[Any] = None, msg_: str = "", verbose_: bool = True, **kwargs, ) -> Any: """Wrap ``func(*args, **kwargs)`` with ``try`` and ``except`` blocks. Args: func (callable) : functions. ret_ (Optional[Any], opt...
80,228
def _CreateSamples(results: Dict[str, Any], number_of_messages: int, message_size: int, cloud: str) -> List[sample.Sample]: """Handles sample creation from benchmark_scenario results.""" samples = [] common_metadata = { 'number_of_messages': number_of_messages, 'message_size': messa...
80,229
def merge(df_list,merge_param_list): """ method to merge the list of data frames based on list of column identifiers. This returns intersection of values :param df_list: :param merge_param_list: :return merged data frame: """ merged = funs.reduce(lambda left, right: pd.merge(left, right,how...
80,230
def yices_check_context(ctx, params): """Checks whether all the assertions stored in the context ctx are satisfiable. - params is an optional structure that stores heuristic parameters. - if params is NULL, default parameter settings are used. It's better to keep params=NULL unless you encounter perfo...
80,231
def collate_fn_v2_(data_batch): """ used for trained on the original complex dataset and tested on the ligand-only and protein-only datasets :param data_batch: :return: """ graphs, graphs3, Ys, Nodes = map(list, zip(*data_batch)) bg = dgl.batch(graphs) bg3 = dgl.batch(graphs3...
80,232
def standardvariables_get(username=None, label=None, page=None, per_page=None): # noqa: E501 """List all instances of StandardVariable Gets a list of all instances of StandardVariable (more information in https://w3id.org/okn/o/sd#StandardVariable) # noqa: E501 :param username: Name of the user graph to ...
80,233
def construct_scale(root_note, scale_signature, scale_length=None): """Construct a musical scale from a root note Arguments: root_note -- A root note object from class Note scale_signature -- array of frequency ratios between consecutive notes on the scale scale_length -- Defaults to standard scale...
80,234
def get_env_logname(name): """ get_env_logname """ modname = name.split('.')[0].upper() envname = f"{modname}_LOGLEVEL" # print(envname) return envname
80,235
def filter_cases_modified_since(domain, case_ids, reference_date): """ Given a domain, case_ids, and a reference date, filter the case ids to only those that have been modified since that reference date. """ last_modified_date_dict = get_last_modified_dates(domain, case_ids) for case_id in case_...
80,236
def horizontal_flip(image_array: ndarray): """ horizontal flip doesn't need skimage, it's easy as flipping the image array of pixels ! """ return image_array[:, ::-1]
80,237
def lookup(a, idx, dim=0): """ Lookup the values of input array based on index. Parameters ---------- a : af.Array. Multi dimensional array. idx : is lookup indices dim : optional: int. default: 0. Specifies the dimension for indexing Returns ------- out : af....
80,238
def main(args, loglevel): """ Main method""" logging.basicConfig(format="%(levelname)s: %(message)s", level=loglevel) group_name = args.group app_type = args.type if app_type == 'search': crawler = TwitterSearch(group_name) crawler.execute() elif app_type == 'stream': c...
80,239
def test_upgrade_non_empty_upgrading_group(): # pylint: disable=invalid-name """Test that an upgrade that starts with a non-empty 'upgrading' node group runs correctly to completion. """ # Start the watcher if it is not already started... queue, pending = start_watching() # Get the xnames and...
80,240
def patch_internal_presign(f: FieldFile): """Create an environment where Minio-based `FieldFile`s construct a locally accessible presigned URL. Sometimes the external host differs from the internal host for Minio files (e.g. in development). Getting the URL in this context ensures that the presigned URL re...
80,241
def match_connected_hboxes(g: BaseGraph[VT,ET], edgef: Optional[Callable[[ET],bool]] = None ) -> List[ET]: """Matches Hadamard-edges that are connected to H-boxes, as these can be fused, see the rule (HS1) of https://arxiv.org/pdf/1805.02175.pdf.""" if edgef is not None: candidates = set([e ...
80,242
def _exist_(url): """ 判断所给的路径是否存在,如果所给的是相对路径(在判断文件夹不存在后)转换为绝对路径 :param url: 用户给定文件夹的路径 :return: """ s = url; if not os.path.exists(url): s = os.path.abspath(url) if os.path.exists(s) and os.path.isdir(s): return True else: print(url + " don't exist...
80,243
def make_user(d): """Get or create a user. Arguments: d A Dict with keys: name A human readable full name, required. The unique username will be inferred through lowersnake(name). email A valid email, optional. phone A phone number, optional. role A role description, optional. ...
80,244
def test_generate_s3_events_legacy(): """CLI - Terraform - S3 Events - Legacy""" cluster_dict = common.infinitedict() CONFIG['clusters']['test']['modules']['s3_events'] = { 's3_bucket_id': 'unit-test-bucket.legacy.data' } result = s3_events.generate_s3_events('test', cluster_dict, CONFIG) ...
80,245
def add_track_with_lines(g, ic, segment, lines, connections, hlc_name_f): """Add tracks to the rr_graph from straight lines and connections.""" logging.debug( "Created track %s from sections: %s", segment.name, len(lines)) logging.debug( "Created track %s from sections: %s", segment.name, li...
80,246
def n2N(n): """ Calculate the square matrix rank N for a packed storage size n Parameters ---------- n : int The packed length. Returns ------- N : np.uint64 The matrix rank. """ N = np.uint64((np.sqrt(8*n+1)-1)/2) return N
80,247
def catalan(n): """calculates the first n catalan numbers (except 0th) extremely inefficiently""" for i in range(1,n): s=a_sent(i) chart,backpoints = ckypy.parse(s,grammar_ambig) print(ckypy.n_parses("S",chart,backpoints,grammar_ambig,s))
80,248
def insert_tables(cur, conn): """ Performs SQL to SQL ETL from staging tables into fact and dimension tables. """ for query in insert_table_queries: cur.execute(query) conn.commit()
80,249
def change_directory(path, create=True): """A context manager to temporaily change the working directory to a specified path, optionally creating the directory if it does not exist. """ if create: os.makedirs(path, exist_ok=True) current_directory = os.getcwd() os.chdir(path) ...
80,250
def run(cmd): """ Run a given process. Returns the PID and returned code from execution. param cmd: str The command to be executed """ logger.info("Running process %s", cmd) command = shlex.split(cmd) proc = subprocess.Popen(command) proc.wait() return proc.pid, proc.returncod...
80,251
def test_duration_min_inclusive003_1116_duration_min_inclusive003_1116_v(mode, save_output, output_format): """ TEST :Facet Schemas for string : facet=minInclusive and value=P1Y1MT1H and document value=P1Y2MT2H """ assert_bindings( schema="msData/datatypes/Facets/duration/duration_minInclusi...
80,252
def scrape_url(url: str, python_objects: Union[bool, List, Tuple] = False, nonstandard_attrs: bool = False, migrate_old_schema: bool = True, user_agent_str: str = None) -> List[Dict]: """scrape from a URL Parameters ---------- url : string A...
80,253
def timeit(text: str = "Time used {:.3f}s", print_fun=LOG.debug): """Timing context with logging/printing output. Args: text (str): Text to print. If it contains an unnamed format key, this is filled with the time. Otherwise `text` is assumed to be description of...
80,254
def ecs_container_instance(request, ecs_cluster, ec2_client, ecs_client, ecs_instance_type, ecs_ami): """ Fixture to handle spin up and tear down of ECS container instance :param request: pytest request object :param ecs_cluster: ecs cluster fixture :param ec2_client: boto3 ec2 client :param ec...
80,255
def sound_mode_rev_map_factory(instance: DenonAVRFoundation) -> Dict[str, str]: """ Construct the sound_mode_rev_map. Reverse the key value structure. The sound_mode_rev_map is bigger, but allows for direct matching using a dictionary key access. The sound_mode_map is uses externally to set this di...
80,256
def get_objhash_from_object_desc(gitobjcontent): """returns object hash without control characters""" return gitobjcontent.split(" ")[1][:40]
80,257
def wgs84_to_lv03(latitude, longitude, altitude=None): """Convert WGS84 to LV03. :param float latitude: latitude in degrees :param float longitude: longitude in degrees :param float altitude: altitude :rtype: (float, float, float) """ lat_sex = dms_to_sex(*dd_to_dms(dd=latitude)) lon_se...
80,258
def decrypt(signature: str, js: str): """ Main function for decrypting the signature cipher. :param signature: original signature, encrypted :param js: base.js contents :return: the decrypted signature """ functions = get_dict_functions(js) signature = [char for char in signature] ...
80,259
def ffactory(type, data=None): """Devuelve el valor filtrado por la función indicada en type Metodo factory, llama a la función type de filtrado. Parameters ---------- type: str data: any Returns ------- any Depende de la función llamada Raises ------ Convert...
80,260
def report(desc, distance_km, duration_hour): """ reports the description, distance, time and average one a line to stdout """ average = distance_km / duration_hour print(f"{desc:20}: {distance_km:>8.1f} km, {duration_hour:>6.1f} h, {average:>5.1f} km/h")
80,261
def get_id_codeList(): """ replace every key word in key_word_dict as a code """ word2code = cPickle.load(open("./data/word_to_code.pickle")) key_word_dict = cPickle.load(open("./data/key_word_dict.pickle")) id2code_dict = cPickle.load(open("./data/id2code_dict.pickle")) f = open("./data/id_codeList.txt", "w") ...
80,262
def get_path(origin, dest): """ MapBox APIを用いてルート探索を行う Arguments: origin {list} -- 出発地の緯度経度 dest {list} -- 到着地の緯度経度 Returns: list -- ルート探索結果 """ api = mapbox.Directions() res = api.directions([{ 'type': 'Feature', 'geometry': { 'type': 'P...
80,263
def update_dict(to_update, updates): """ Recursively updates a nested dict `to_update` from a nested dict `updates` """ for key, val in updates.items(): if isinstance(val, collections.Mapping): to_update[key] = update_dict(to_update.get(key, {}), val) else: to_update[...
80,264
def sin(duration: int, amp: complex, freq: float = None, phase: float = 0, name: Optional[str] = None) -> SamplePulse: """Generates sine wave `SamplePulse`. Args: duration: Duration of pulse. Must be greater than zero. amp: Pulse amplitude. freq: Pulse frequency, units of 1/dt. ...
80,265
def list_resources() -> List[str]: """ Lists all available resources by name. :returns: A list of resources by name. """ return _get_resources(_get_resources_json()["resources"]).keys()
80,266
def get_impulse(f, tf, dt, T): """ Calculates the impulse response, given a single-sided transfer function. f should be non-negative and increasing. See https://www.overleaf.com/read/mxxtgdvkmkvt """ # calculate number of time points in impulse response n_req = round(T/dt) logging.debug('Numbe...
80,267
def url_add(url, ssl_ignore = False, aka = None, ca_path = None): """ Add a TTBD server :param str url: server's URL (``http://SERVER:PORT``); it can be *https*; port is most commonly *5000*. :param bool ssl_ignore: if True, skips verifying SSL certificates :param str aka: Short form for this...
80,268
def contourf_latpres(data, lat=None, plev=None, clev=None, init=True, cmap='RdBu_r', symmetric=True, topo=None, topo_clr='black', p_units='hPa', axlims=(-90, 90, 0, 1000), lattick_width=None, ptick_width=None): """Plot filled contours of data in latitude-p...
80,269
def extract_all_content( content: str, author: str, created_at: str, attachments: List[Dict[str, str]], ) -> List[dict]: """ Extract all information for content, allowing for multiple week submissions in one post. Parameters ---------- content : `str` The content text. ...
80,270
def computeMaskIntersection(gt, gtMask, pred, predMask): """ Compute intersection between GT instance and prediction. Increase efficiency by computing elementwise product between masks only inside the tight bounding box of the union of the prediction and target masks. """ if gtMask is None o...
80,271
def handle_merge_duplicate_facilities( facilities: DataFrame, ) -> Tuple[DataFrame, Union[Dict[str, str], None]]: """Drops duplicate facilities by name and some other logic. Returns facility DataFrame without duplicate facilities and merged facilityIds as a dictionary ({from_id: to_id},...). """ ...
80,272
def test_low_invcdf_value(): """ Bounds from New Cambridge Statistical Tables, 2nd Ed. (4dp of precision given in Table 5) """ assert -2.05375 < invcdf(0.02) < -2.05365
80,273
def write_mothers_spreadsheet(outfile): """ """ with open(outfile, "w") as fp: wtr = csv.writer(fp) header = ["Guardian", "Children"] wtr.writerow(header) for family in sorted(families.values(), key=Family.sortkey): family.children.sort(key=Student.sortkey, revers...
80,274
def load_csv_file(csv_file): """ load csv file and check file content format Args: csv_file (str): csv file path, csv file content is like below: Returns: list: list of parameters, each parameter is in dict format Examples: >>> cat csv_file username,password te...
80,275
def get_applicant(form): """ Gets applicant info, or adds if necessary """ applicant_result = Applicant.query.filter_by(email=form.get("email")).first() if applicant_result: applicant_id = applicant_result.applicant_id else: applicant_id = add_applicant(form) return applicant_i...
80,276
def run_ansible(ansible_vars, playbook, args, local=False): """ Executes ansible playbook and checks for errors :param ansible_vars: dictionary of variables to inject into ansible run :param playbook: playbook to execute :param args: CLI args :return: None """ logging.info("Executing ans...
80,277
def vis_detection(im_orig, detections, class_names, thresh=0.7): """visualize [cls, conf, x1, y1, x2, y2]""" import matplotlib.pyplot as plt import random plt.imshow(im_orig) colors = [(random.random(), random.random(), random.random()) for _ in class_names] for [cls, conf, x1, y1, x2, y2] in de...
80,278
def check_function_task(self, file_path, user_id, q_id, function_name, args, answers, timeout): """task that will check a submission""" # this needs refactoring ! results = [] total = len(args) status = 'Unsucessful' sub_result = False try: for i, arg in enumerate(args): ...
80,279
def main(): """ """ example_usage = """ ------------------------------------------------------------------------------------------ view jira: jira-cli BE-193 view multiple jiras: jira-cli XYZ-123 ZZZ-123 ABC-123 add a comment: jira-cli -j BE-193 -c "i am sam" create a new issue: jira-cli -n bug -p BE -t "i ...
80,280
def graphing(dataframe_after_LDA, title, color_list, labels): """ Function that given a dataframe after the LDA, returns a graph where each point corresponds to a frame, and each cluster correspond to a different location of the mouse during the experiment (HOME, CORRIDOR, FARCHAMBER) :param dat...
80,281
def make_sentences(diff): """Create human-readable sentences out of the diff dict.""" info = [] for t in sorted(diff.keys()): if "old" in diff[t]: old_range = make_range(diff[t]["old"]["min"], diff[t]["old"]["max"]) new_range = make_range(diff[t]["new"]["min"], diff[t]["new"]...
80,282
def acquire_lock(lock_file, sock_file, block, heartbeat): """ Acquire a lock on the passed file, block if needed :param lock_file: :param sock_file: :param block: :return: """ # get dir lock first to check lock file existence with open(os.path.dirname(lock_file) + DIR_LOCK_FILE, 'w'...
80,283
def swsl_resnext101_32x16d(pretrained=True, **kwargs): """Constructs a semi-weakly supervised ResNeXt-101 32x16 model pre-trained on 1B weakly supervised image dataset and finetuned on ImageNet. `"Billion-scale Semi-Supervised Learning for Image Classification" <https://arxiv.org/abs/1905.00546>`_ ...
80,284
def test_listdomain_unif_rand_samp(): """Test uniform random sampling of domain points.""" dom_params = Namespace(set_domain_list=True, domain_list=[1.0, 'cat', (5, 5)]) listdom = ListDomain(params=dom_params) nsamp = 10 samp_list = listdom.unif_rand_sample(n=nsamp) assert isinstance(samp_list, ...
80,285
def completeTreeNames(tree, useBS = False ) : """ Takes: - tree (ete3.Tree) - useBS (bool) [default = False] : uses bootstrap to name nodes Returns: (ete3.Tree) : the tree, but where the nodes without a name now have one that correspond to their post-order OR the...
80,286
def password(characters: Sequence[chr] = string.printable, length: int = 8, unique: bool = False) -> str: """ :param characters: The character pool that will be used when generating the password :param length: The total length of the password to be generated :param unique: Whet...
80,287
def ValidateUpdatePolicyAgainstStateful(update_policy, group_ref, stateful_policy, client): """Validates and fixed update policy for stateful MIG. Sets default values in update_policy for stateful IGMs or throws exception if the wrong value is set explicitly. Args: ...
80,288
def build(kernel_desc, attrs=None, poly=True, use_repo=True): """ build kernel with compute description in json format Args: kernel_desc : str or dict of compute description attrs : dict of build attributes Returns: Module. """ if isinstance(kernel_desc, str): des...
80,289
def bitsize(a): """ Compute the bitsize of an element of Z (not counting the sign). """ val = abs(a) res = 0 while val: res += 1 val >>= 1 return res
80,290
def test_multi_keyword__Search__4(search_data, browser): """`Search` result is displayed as a table with links to the edit form.""" browser.login('visitor') browser.keyword_search('church') assert (['Koch', 'Liebig', 'Velleuer'] == browser.etree.xpath('//table/tbody/tr/td/a/text()')) ass...
80,291
def InjectDll(proc, name, entry = None): """Inject a dll with CreateRemoteThread in the remote process""" kernel32 = _GetModuleHandleA(b'kernel32') if not kernel32: raise Win32Exception() LoadLibraryEx = _GetProcAddress(kernel32, b'LoadLibraryA') if not LoadLibraryEx: raise Win32Exce...
80,292
def find_module_corner2(mask, mode=0): """ mode == 0: detect corners of the convex of module mode == 1: detect corners of the approximated convex of module mode == 2: detect corners of the approximated contour of the module mode == 3: detect corners of the blurred mask of the module """ blur...
80,293
def gen_rand_lists(): """ Generate two lists with random numbers in [0,5], output them and compare their mean and tell who is greater """ def gen_list(): ll = [] for i in range(5): ll.append(random.randint(0, 5)) return ll def calc_average(x): s...
80,294
def get_image_zip(project_id, project_name, json_data, filters=None): """ Create a zip file in memory containing the project's images and a descriptive JSON file. """ all_data = ProjectImageData.query.filter_by(project_id=project_id).all() date_time = time.localtime(time.time())[:6] memory_f...
80,295
def degre(poly): """Renvoie le degré du polynôme _poly_""" poly = clear_poly(poly) return len(poly)-1
80,296
def test_fold_from_right_with_terminal_measurements_min_stretch(): """Tests folding from left with terminal measurements.""" # Test circuit # 0: ───H───@───@───M─── # │ │ # 1: ───H───X───@───M─── # │ # 2: ───H───T───X───M─── qreg = LineQubit.range(3) circ = ...
80,297
def store_forecast_values(forecast_id, forecast_df): """Store Forecast data Parameters ---------- forecast_id: string UUID of the associated forecast. forecast_df: DataFrame Dataframe with DatetimeIndex and value column. Returns ------- string The UUID of the as...
80,298
def gather_link_defn_lines(file_lines): """Returns all link def lines occuring after main content. Should be called with set of lines starting with first non-main-content line.""" ld_lines = [] for mdfl in file_lines: if is_ld_block_begin_line(mdfl): continue # ignore the b...
80,299