content
stringlengths
22
815k
id
int64
0
4.91M
def plot_elite(d: dict, f, ylabel: str, title: str, save_path: str): """Create a plot of the given dictionary. Each value of d consists of a list of length 3 (min, avg, max).""" # Parse the values keys = sorted(d.keys()) elite_data = [f(d[k]) for k in keys] # Create the plot plt.figure(figs...
14,600
def new_oauth2ProviderLimited(pyramid_request): """this is used to build a new auth""" validatorHooks = CustomValidator_Hooks(pyramid_request) provider = oauth2_provider.OAuth2Provider( pyramid_request, validator_api_hooks=validatorHooks, validator_class=CustomValidator, serv...
14,601
def rand_color(red=(92, 220), green=(92, 220), blue=(92, 220)): """ Random red, green, blue with the option to limit the ranges. The ranges are tuples 0..255. """ r = rand_byte(red) g = rand_byte(green) b = rand_byte(blue) return f"#{r:02x}{g:02x}{b:02x}"
14,602
def tile_to_html(tile, fig_size=None): """ Provide HTML string representation of Tile image.""" import base64 b64_img_html = '<img src="data:image/png;base64,{}" />' png_bits = tile_to_png(tile, fig_size=fig_size) b64_png = base64.b64encode(png_bits).decode('utf-8').replace('\n', '') return b64_...
14,603
def generate_buchwald_hartwig_rxns(df): """ Converts the entries in the excel files from Sandfort et al. to reaction SMILES. """ df = df.copy() fwd_template = '[F,Cl,Br,I]-[c;H0;D3;+0:1](:[c,n:2]):[c,n:3].[NH2;D1;+0:4]-[c:5]>>[c,n:2]:[c;H0;D3;+0:1](:[c,n:3])-[NH;D2;+0:4]-[c:5]' methylaniline = '...
14,604
def init_bold_std_trans_wf( mem_gb, omp_nthreads, spaces, name="bold_std_trans_wf", use_compression=True, use_fieldwarp=False, ): """ Sample fMRI into standard space with a single-step resampling of the original BOLD series. .. important:: This workflow provides two outputno...
14,605
def print_lambda_cost(args): """ Main function. :param args: script arguments. :return: None. """ regions = list_available_lambda_regions() progress_bar = progressbar.ProgressBar(max_value=len(regions)) lambdas_data = [] total_monthly_cost = 0 for region in progress_bar(regions):...
14,606
def log_model_info(model): """Logs model info""" logger.info("Model:\n{}".format(model)) logger.info("Params: {:,}".format(mu.params_count(model))) logger.info("Acts: {:,}".format(mu.acts_count(model))) logger.info("Flops: {:,}".format(mu.flops_count(model)))
14,607
def orbit_text(ax,radius,long_asc_node,inclination,longitude,text): """ Position text using orbital coordinates. @param radius : radial distance of text @type radius : float (degrees) @param long_asc_node : longitude (deg) where vector crosses the orbit @type long_asc_node : float @param inclinatio...
14,608
def _get_indent(node): """Determine the indentation level of ``node``.""" indent = None while node: indent = find_first(node, TOKEN.INDENT) if indent is not None: indent = indent.value break node = node.parent return indent
14,609
def distancesarr(image_centroid, object_centroids): """gets the distances between image and objects""" distances = [] j = 0 for row in object_centroids: distance = centroid_distance(image_centroid, object_centroids, j) distances.append(distance) j +=1 return distances
14,610
def obs_agent_has_neighbour(agent_id: int, factory: Factory) -> np.ndarray: """Does this agent have a neighbouring node?""" agent: Table = factory.tables[agent_id] return np.asarray( [ agent.node.has_neighbour(Direction.up), agent.node.has_neighbour(Direction.right), ...
14,611
def P_split_prob(b): """Returns the probability of b according to the P_split() distribution. """ """n = b.length if n <= 2: p = 1.0 else: k = 1 # si el arbol es binario y n > 2 seguro que tiene que ser splittable. #while k < n and not b.splittable(k): while n...
14,612
def t(): """Or time(). Returns the number of seconds elapsed since the cartridge was run.""" global begin return py_time.time() - begin
14,613
def data_provider(data_provider_function, verbose=True): """PHPUnit style data provider decorator""" def test_decorator(test_function): def new_test_function(self, *args): i = 0 if verbose: print("\nTest class : " + get_class_that_defined_method(test_function))...
14,614
def intersect_generators(genlist): """ Intersect generators listed in genlist. Yield items only if they are yielded by all generators in genlist. Threads (via ThreadedGenerator) are used in order to run generators in parallel, so that items can be yielded before generators are exhausted. T...
14,615
def main(): """Console script for ceda_intake.""" parser = argparse.ArgumentParser() parser.add_argument('--test', dest='test_mode', action='store_true', help='Create small catalog in test mode') parser.add_argument('-p', '--project', type=str, required=True, ...
14,616
def check_combinations2_task(infiles, outfile, prefices, subpath, subdir): """ Test combinations with k-tuple = 2 """ with open(outfile, "w") as outf: outf.write(prefices + ",")
14,617
def convert_none( key: str, attr_type: bool, attr: dict[str, Any] = {}, cdata: bool = False ) -> str: """Converts a null value into an XML element""" key, attr = make_valid_xml_name(key, attr) if attr_type: attr["type"] = get_xml_type(None) attrstring = make_attrstring(attr) return f"<{...
14,618
def main(): """To try the server.""" try: server = HTTPServer(('', 10300), RequestHandler) print('Server started...') server.serve_forever() except KeyboardInterrupt: print('^C received, shutting down server.') server.socket.close()
14,619
def maybe_download_and_extract(): """Download and extract model tar file. If the pretrained model we're using doesn't already exist, this function downloads it from the TensorFlow.org website and unpacks it into a directory. """ dest_directory = FLAGS.model_dir if not os.path.exists(dest_directory): os...
14,620
def is_title(ngram, factor = 2.0): """ Define the probability of a ngram to be a title. Factor is for the confidence coex max. """ confidence = 1 to_test = [n for n in ngram if n not in stop_words] for item in to_test: if item.istitle(): confidence += factor / len(to_test) # p...
14,621
def img_to_b64(img_path): """显示一副图片""" assert os.path.isfile(img_path) with open(img_path, 'rb') as f: img = f.read() b64 = base64.b64encode(img) return b64
14,622
def ul(microliters): """Unicode function name for creating microliter volumes""" if isinstance(microliters,str) and ':' in microliters: return Unit(microliters).to('microliter') return Unit(microliters,"microliter")
14,623
def edit_bbox(obj_to_edit, action): """action = `delete` `change_class:new_class_index` `resize_bbox:new_x_left:new_y_top:new_x_right:new_y_bottom` """ global tracker_dir, img_index, image_paths_list, current_img_path, width, height if "change_class" in action: new_class_index = int(acti...
14,624
def read_glh(filename): """ Read glitch parameters. Parameters ---------- filename : str Name of file to read Returns ------- glhParams : array Array of median glitch parameters glhCov : array Covariance matrix """ # Extract glitch parameters glh...
14,625
def update_user_group(user_group_id, name, **options): """ Update a user group :param user_group_id: The id of the user group to update :type user_group_id: str :param name: Name of the user group :type name: str, optional :param options: ...
14,626
def longitudinal_kmeans(X, n_clusters=5, var_reg=1e-3, fixed_clusters=True, random_state=None): """Longitudinal K-Means Algorithm (Genolini and Falissard, 2010)""" n_time_steps, n_nodes, n_features = X.shape # vectorize latent positions across time X_vec = np.moveaxis(X, 0, -1)....
14,627
def terminate(mgr, qname='input'): """DEPRECATED: Use TFNode class instead""" logging.info("terminate() invoked") mgr.set('state','terminating') # drop remaining items in the queue queue = mgr.get_queue(qname) count = 0 done = False while not done: try: queue.get(blo...
14,628
def do_payment( checkout_data, # Dict[str, str] parsed_checkout, # Dict[str, str] enable_itn, # type: bool ): # type: (...) -> Dict[str, str] """ Common test helper: do a payment, and assert results. This takes a checkout's data and page parse (for session info and assertions). ...
14,629
def nifti_to_numpy(input_folder: str, output_folder: str): """Converts all nifti files in a input folder to numpy and saves the data and affine matrix into the output folder Args: input_folder (str): Folder to read the nifti files from output_folder (str): Folder to write the numpy arrays to ...
14,630
def test_gocc_other_relationship_for_expression_exists(): """Test GOCC Other Relationship For Expression Exists""" query = """MATCH (n:ExpressionBioEntity)-[r:CELLULAR_COMPONENT_RIBBON_TERM]-(o:GOTerm:Ontology) WHERE o.primaryKey = 'GO:otherLocations' RETURN count(r) AS counter"""...
14,631
def ensure_sphinx_astropy_installed(): """ Make sure that sphinx-astropy is available. This returns the available version of sphinx-astropy as well as any paths that should be added to sys.path for sphinx-astropy to be available. """ # We've split out the Sphinx part of astropy-helpers into sph...
14,632
def SPEED_OF_LIGHT(): """ The `SPEED_OF_LIGHT` function returns the speed of light in vacuum (unit is ms-1) according to the IERS numerical standards (2010). """ return 299792458.0
14,633
def odd_factory(NATIVE_TYPE): # pylint: disable=invalid-name """ Produces a Factory for OddTensors with underlying tf.dtype NATIVE_TYPE. """ assert NATIVE_TYPE in (tf.int32, tf.int64) class Factory: """ Represents a native integer data type. It is currently not considered for general use, but o...
14,634
def filter_by_is_awesome(resources): """The resources being that is_awesome Arguments: resources {[type]} -- A list of resources """ return [resource for resource in resources if resource.is_awesome]
14,635
def topograph_image(image, step): """ Takes in NxMxC numpy matrix and a step size and a delta returns NxMxC numpy matrix with contours in each C cell """ step_gen = _step_range_gen(step) new_img = np.array(image, copy=True) """step_gen ~ (255, 245, 235, 225,...) """ def myfunc(color):...
14,636
def _etag(cur): """Get current history ETag during request processing.""" h_from, h_until = web.ctx.ermrest_history_snaprange cur.execute(("SELECT _ermrest.tstzencode( GREATEST( %(h_until)s::timestamptz, (" + _RANGE_AMENDVER_SQL + ")) );") % { 'h_from': sql_literal(h_from), 'h_until': sql_li...
14,637
def send_request(url, method='GET', headers=None, param_get=None, data=None): """实际发送请求到目标服务器, 对于重定向, 原样返回给用户 被request_remote_site_and_parse()调用""" final_hostname = urlsplit(url).netloc dbgprint('FinalRequestUrl', url, 'FinalHostname', final_hostname) # Only external in-zone domains are allowed (SSR...
14,638
def MakeListOfPoints(charts, bot, test_name, buildername, buildnumber, supplemental_columns): """Constructs a list of point dictionaries to send. The format output by this function is the original format for sending data to the perf dashboard. Args: charts: A dictionary of chart names...
14,639
def set_standard_part(elements: List[int]) -> None: """Sets covers (wall, opening or floor) to standard part Args: elements (List[int]): element IDs """
14,640
def parse_csv(string): """ Rough port of wq/pandas.js to Python. Useful for validating CSV output generated by Django REST Pandas. """ if not string.startswith(','): data = [] for row in csv.DictReader(StringIO(string)): for key, val in row.items(): try: ...
14,641
def list_system_configurations(): """ List all the system configuration parameters Returns: .. code-block:: python [ { "ParameterName": "ParameterValue" }, ... ] Raises: 500 - ChaliceViewError...
14,642
def main(): """Run bot.""" # Create the Updater and pass it your bot's token. # Make sure to set use_context=True to use the new context based callbacks # Post version 12 this will no longer be necessary defaults = Defaults(timeout = 60) updater = Updater(os.environ['BOT_TOKEN'], use_context=Tru...
14,643
def add_dbnsfp_to_vds(hail_context, vds, genome_version, root="va.dbnsfp", subset=None, verbose=True): """Add dbNSFP fields to the VDS""" if genome_version == "37": dbnsfp_schema = DBNSFP_SCHEMA_37 elif genome_version == "38": dbnsfp_schema = DBNSFP_SCHEMA_38 else: raise ValueEr...
14,644
def look_for_time_position(target, source, begin_pos=0): """ Given a time stamp, find its position in time series. If target does NOT exist in source, then return the value of the smallest time point that is larger than the given target. Parameters ------------- target : DateTime obj ...
14,645
def get_wav2vec_preds_for_wav( path_to_wav: str, model, processor, device: torch.device, bs: int = 8, loading_step: float = 10, extra_step: float = 1, ) -> str: """ Gets binary predictions for wav file with a wav2vec 2.0 model Args: path_to_wav (str): absolute path to wa...
14,646
def get_template(parsed_args): """Initialize jinja2 and return the right template""" env = jinja2.Environment( loader=jinja2.PackageLoader(__name__, TEMPLATES_PATH), trim_blocks=True, lstrip_blocks=True, ) # Make the missingvalue() function available in the template so that the # tem...
14,647
def get_node_cmd(config): """ Get the node CLI call for Least Cost Xmission Parameters ---------- config : reVX.config.least_cost_xmission.LeastCostXmissionConfig Least Cost Xmission config object. Returns ------- cmd : str CLI call to submit to SLURM execution. """...
14,648
def header_lines(filename): """Read the first five lines of a file and return them as a list of strings.""" with open(filename, mode='rb') as f: return [f.readline().decode().rstrip() for _ in range(5)]
14,649
def deactivate_venv( venv: str = 'mrsm', color : bool = True, debug: bool = False ) -> bool: """ Remove a virtual environment from sys.path (if it's been activated). """ import sys global active_venvs if venv is None: return True if debug: from m...
14,650
async def load_last_cotd(chat_id: int): """Load the time when the user has last received his card of the day. Args: chat_id (int): user chat_id """ QUERY = "SELECT last_cotd FROM users WHERE id = %(id)s" async with aconn.cursor() as cur: await cur.execute(QUERY, {"id": chat_id}) ...
14,651
def load_model(targets, model_name='umxhq', device='cpu'): """ target model path can be either <target>.pth, or <target>-sha256.pth (as used on torchub) """ model_path = Path(model_name).expanduser() if not model_path.exists(): raise NotImplementedError else: # load model fro...
14,652
def model_gradient_descent( f: Callable[..., float], x0: np.ndarray, *, args=(), rate: float = 1e-1, sample_radius: float = 1e-1, n_sample_points: int = 100, n_sample_points_ratio: Optional[float] = None, rate_decay_exponent: float = 0.0, s...
14,653
def index(): """Show the index.""" return render_template( "invenio_archivematica/index.html", module_name=_('Invenio-Archivematica'))
14,654
def on_pod_event(event, body: Body, logger: Logger, **kwargs): """ Handle low-level MySQL server pod events. The events we're interested in are: - when a container restarts in a Pod (e.g. because of mysqld crash) """ # TODO ensure that the pod is owned by us while True: try: ...
14,655
def get_functions_and_macros_from_doc(pmdk_path): """ Returns names of functions and macros in a list based on names of files from the doc directory. """ path_to_functions_and_macros = path.join(pmdk_path, 'doc') functions_and_macros_from_doc = [] for _, _, files in walk(path_to_functions_an...
14,656
def kmv_tet_polyset(m, mf, mi): """Create the polynomial set for a KMV space on a tetrahedron.""" poly = polynomial_set(3, 1, m) # TODO: check this for axes in [(x[0], x[1]), (x[0], x[2]), (x[1], x[2]), (x[1] - x[0], x[2] - x[0])]: b = axes[0] * axes[1] * (1 - axes[0] - axes[1]) for i i...
14,657
def list_faqs(IndexId=None, NextToken=None, MaxResults=None): """ Gets a list of FAQ lists associated with an index. See also: AWS API Documentation Exceptions :example: response = client.list_faqs( IndexId='string', NextToken='string', MaxResults=123 ) ...
14,658
def word_detokenize(tokens): """ A heuristic attempt to undo the Penn Treebank tokenization above. Pass the --pristine-output flag if no attempt at detokenizing is desired. """ regexes = [ # Newlines (re.compile(r'[ ]?\\n[ ]?'), r'\n'), # Contractions (re.compile(r"\b...
14,659
def googlenet_paper(pretrained=False, **kwargs): """ GoogLeNet Model as given in the official Paper. """ kwargs['aux'] = True if 'aux' not in kwargs else kwargs['aux'] kwargs['replace5x5with3x3'] = False if 'replace5x5with3x3' not in kwargs \ else kwargs['replace5x5with3x3'] ...
14,660
def get_parser(): """ Parses the command line arguments .. todo:: Adapter services related to alerts/messaging, and local device/Edge management :returns: An object with attributes based on the arguments :rtype: argparse.ArgumentParser """ parser = argparse.ArgumentParser(descriptio...
14,661
def get_prefix(path): """Generate a prefix for qresource in function of the passed path. Args: path (str): Relative path of a folder of resources from project dir. Returns; str: Prefix corresponding to `path` """ # Remove finishing separator from path if exist if path[-1] == o...
14,662
def getInfoLabel(infotag): """ Returns an InfoLabel as a string. infotag : string - infoTag for value you want returned. List of InfoTags - http://xbmc.org/wiki/?title=InfoLabels example: - label = xbmc.getInfoLabel('Weather.Conditions') """ pass
14,663
def is_regex(obj): """Cannot do type check against SRE_Pattern, so we use duck typing.""" return hasattr(obj, 'match') and hasattr(obj, 'pattern')
14,664
def GetDefaultScopeLister(compute_client, project=None): """Constructs default zone/region lister.""" scope_func = { compute_scope.ScopeEnum.ZONE: functools.partial(zones_service.List, compute_client), compute_scope.ScopeEnum.REGION: functools.partial(regions_service.List, compute_cl...
14,665
def find_user(username): """ Function that will find a user by their username and return the user """ return User.find_by_username(username)
14,666
def filter_by_author(resources: List[Resource], author: Author) -> List[Resource]: """The resources by the specified author Arguments: resources {List[Resource]} -- A list of resources """ return [resource for resource in resources if resource.author == author]
14,667
def cpu_bound_op(exec_time, *data): """ Simulation of a long-running CPU-bound operation :param exec_time: how long this operation will take :param data: data to "process" (sum it up) :return: the processed result """ logger.info("Running cpu-bound op on {} for {} seconds".format(data, exec_...
14,668
def elastic_transform_approx( img, alpha, sigma, alpha_affine, interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_REFLECT_101, value=None, random_state=None, ): """Elastic deformation of images as described in [Simard2003]_ (with modifications for speed). Based on https://gis...
14,669
def uncompleted_task(request): """ Make the completed task incomplete if use uncheck the task.""" task_list = TaskList.objects.all() context = {'task_list': task_list} if request.POST: task_is_unchecked = request.POST['task_is_unchecked'] task_unchecked_id = request.POST['task_unch...
14,670
def load_settings_from_file(filepath="settings.ini", in_omelib=True): """Reload settings from a different settings file. Arguments --------- filepath: The path to the settings file to use. in_omelib: Whether or not the path given is a relative path from the omelib directory. """ if i...
14,671
def jitter(t, X, amountS): """Return a random number (intended as a time offset, i.e. jitter) within the range +/-amountS The jitter is different (but constant) for any given day in t (epoch secs) and for any value X (which might be e.g. deviceID)""" dt = ISO8601.epoch_seconds_to_datetime(t) d...
14,672
def check_DNA(DNA_sequence): """Check that we have a DNA sequence without junk""" # import string # Remove all spaces DNA_sequence=string.replace(DNA_sequence,' ','') # Upper case DNA_sequence=string.upper(DNA_sequence) # Check that we only have DNA bases in the seq ok=1 garbage=...
14,673
def draw(): """Clears and draws objects to the screen""" screen.fill(WHITE) object_pos = current_object.get_pos() # Draw the Tetris object for i in range(len(object_pos)): pygame.draw.rect(screen, current_object.color, [object_pos[i][0]...
14,674
def read(): """ read() : Fetches documents from Firestore collection as JSON warehouse : Return document that matches query ID all_warehouses : Return all documents """ try: warehouse_id = request.args.get('id') if warehouse_id: warehouse = warehouse_ref.d...
14,675
def transposeC(array, axes=None): """ Returns the (conjugate) transpose of the input `array`. Parameters ---------- array : array_like Input array that needs to be transposed. Optional -------- axes : 1D array_like of int or None. Default: None If *None*, reverse the di...
14,676
def _partition_files(files: List[str], num_partitions: int) -> List[List[str]]: """Split files into num_partitions partitions of close to equal size""" id_to_file = defaultdict(list) for f in files: id_to_file[_sample_id_from_path(f)[0]].append(f) sample_ids = np.array(list(id_to_file)) np.r...
14,677
def test_tti(shape, space_order, kernel): """ This first test compare the solution of the acoustic wave-equation and the TTI wave-eqatuon with all anisotropy parametrs to 0. The two solutions should be the same. """ if kernel == 'shifted': space_order *= 2 to = 2 so = space_order...
14,678
def run_vscode_command( command: str, *args: str, wait_for_finish: bool = False, expect_response: bool = False, decode_json_arguments: bool = False, ): """Execute command via vscode command server.""" # NB: This is a hack to work around the fact that talon doesn't support # variable argu...
14,679
def flush_cache(roles=['webapp_servers', 'celery_servers']): """ Flushes the cache. """ if _current_host_has_role(roles): print("=== FLUSHING CACHE ===") with cd(env.REMOTE_CODEBASE_PATH): run("workon %s && ./manage.py ft_clear_cache" % env.REMOTE_VIRTUALENV_NAME)
14,680
def run_with_timeout(proc, timeout, input=None): """ Run Popen process with given timeout. Kills the process if it does not finish in time. You need to set stdout and/or stderr to subprocess.PIPE in Popen, otherwise the output will be None. The returncode is 999 if the process was killed. ...
14,681
def set_is_significant_to_zero(rfam_acc, rfamseq_acc): """ Fetch the correct db entry from full_region table according to rfam_acc and rfamseq_acc and set is_significant field to zero (0) rfam_acc: RNA family accession rfamseq_acc: Family specific sequence accession """ # maybe have this w...
14,682
def dot(x, y, alpha=0): """ Compute alpha = xy + alpha, storing the incremental sum in alpha x and y can be row and/or column vectors. If necessary, an implicit transposition happens. """ assert type(x) is matrix and len(x.shape) is 2, \ "laff.dot: vector x must be a 2D num...
14,683
def main(argv=None): """Run ExperimentRunner locally on ray. To run this example on cloud (e.g. gce/ec2), use the setup scripts: 'softlearning launch_example_{gce,ec2} examples.development <options>'. Run 'softlearning launch_example_{gce,ec2} --help' for further instructions. """ run_exam...
14,684
def create_buildpack(buildpack_name, buildpack_path, position=1): """Creates a buildpack. Always enables it afterwards (--enable flag). Args: buildpack_name (str): Name for the buildpack. buildpack_path (str): Path to the buildpack's artifact. position (int): Priority of the new buildpa...
14,685
def load_train_test_data( train_data_path, label_binarizer, test_data_path=None, test_size=None, data_format="list"): """ train_data_path: path. path to JSONL data that contains text and tags fields label_binarizer: MultiLabelBinarizer. multilabel binarizer instance used to transform tags ...
14,686
def delete_courrier_affaire_view(request): """ Supprimer le fichier une fois téléchargé """ settings = request.registry.settings filename = request.params['filename'] temporary_directory = settings["temporary_directory"] file_path = os.path.join(temporary_directory, filename) if os.path...
14,687
def get_token() -> str: """Obtains the Access Token from the Authorization Header""" # Get the authorization header authorization_header = request.headers.get("Authorization", None) # Raise an error if no Authorization error is found if not authorization_header: payload = { "co...
14,688
def load_image(path, grayscale=False): """Summary Args: path (str): Path to image grayscale (bool): True loads image as grayscale, False loads image as color Returns: numpy.ndarray: Image loaded from path """ # TODO: Loa...
14,689
def _get_matching_s3_keys(bucket, prefix='', suffix=''): """Generate all the matching keys in an S3 bucket. Parameters ---------- bucket : str Name of the S3 bucket prefix : str, optional Only fetch keys that start with this prefix suffix : str, optional Only fetch key...
14,690
def frames_player(frames, n_snapshots=None): """ Shows each frame from the data with 15fps speed. If n_snapshots is defined it will take and save snapshots from the video with interval = len(frames) // n_snapshots :param frames: :param n_snapshots: :return: """ # For taking snapshots at ...
14,691
def test_days(): """ Ensure d suffix is converted to days """ assert_equal(datetime.timedelta(days=1), convert_delta("1d"))
14,692
def convert_op_str(qubit_op_str, op_coeff): """ Convert qubit operator into openfermion format """ converted_Op=[f'{qOp_str}{qNo_index}' for qNo_index, qOp_str in enumerate(qubit_op_str) if qOp_str !='I'] seperator = ' ' #space Openfermion_qubit_op = QubitOperator(seperator.join(conver...
14,693
def __state_resolving_additional_facts(conversation, message, just_acknowledged): """ Bot is asking the user questions to resolve additional facts :param conversation: The current conversation :param message: The user's message :param just_acknowledged: Whether or not an acknowledgement just happene...
14,694
def load_dataset(path): """Load json file and store fields separately.""" with open(path) as f: data = json.load(f)['data'] output = {'qids': [], 'questions': [], 'answers': [], 'contexts': [], 'qid2cid': []} for article in data: for paragraph in article['paragraphs']: ...
14,695
def generate_rand_enex_by_prob_nb(shape: tp.Shape, entry_prob: tp.MaybeArray[float], exit_prob: tp.MaybeArray[float], entry_wait: int, exit_wait: int, ...
14,696
def bresenham_3d_line_of_sight(observers, targets, raster, obs_height_field, tar_height_field, radius, raster_crs, fresnel=False): """Naive bresenham line of sight algorithm""" writePoints = [] lines_for_shp = [] start, end = 0, 0 raster_transform = raster.GetGeoTrans...
14,697
def delete(): """ Receives requests for deleting certain files at the back-end """ path = request.form['path'] files = glob.glob(path) for f in files: os.remove(f) return 'Successfull'
14,698
def retrieve(last_updated=datetime.now()): """ Crawls news and returns a list of tweets to publish. """ print('Retrieving {} alzheimer news since {}.'.format(SITE, last_updated)) to_ret = list() # Get all the content from the last page of the site's news tree = html.fromstring(requests.get(URL).co...
14,699