content
stringlengths
22
815k
id
int64
0
4.91M
def create_token_swap_augmenter( level: float, respect_ents: bool = True, respect_eos: bool = True ) -> Callable[[Language, Example], Iterator[Example]]: """Creates an augmenter that randomly swaps two neighbouring tokens. Args: level (float): The probability to swap two tokens. respect_ent...
43,100
def getUnigram(str1): """ Input: a list of words, e.g., ['I', 'am', 'Denny'] Output: a list of unigram """ words = str1.split() assert type(words) == list return words
43,101
def expval_and_stddev(items, exp_ops=''): """Compute expectation values from distributions. .. versionadded:: 0.16.0 Parameters: items (list or dict or Counts or ProbDistribution or QuasiDistribution): Input distributions. exp_ops (str or dict or list): String or...
43,102
def posixinstall(): """ Install the Qt reactor. """ p = QtReactor() from twisted.internet.main import installReactor installReactor(p)
43,103
def newton_polish(polys,root,niter=100,tol=1e-8): """ Perform Newton's method on a system of N polynomials in M variables. Parameters ---------- polys : list A list of polynomial objects of the same type (MultiPower or MultiCheb). root : ndarray An initial guess for Newton's met...
43,104
def COUNT(logic, n=2): """ 统计满足条件的周期数 :param logic: :param n: :return: """ return pd.Series(np.where(logic, 1, 0), index=logic.index).rolling(n).sum()
43,105
def get_model(name): """ Get the warpped model given the name. Current support name: "COCO-Detection/retinanet_R_50_FPN"; "COCO-Detection/retinanet_R_101_FPN"; "COCO-Detection/faster_rcnn_R_50_FPN"; "COCO-Detection/faster_rcnn_R_101_FPN"; "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN"; ...
43,106
def load_model_params(model, model_name, model_uri, ignore_cache=False, device=None): """Load model parameters from disk or from the web. Parameters ---------- model : torch.nn.modules.container.Sequential The model instance to load the parameters for. model_name : str The name of t...
43,107
def energy_sensor( gateway_nodes: dict[int, Sensor], energy_sensor_state: dict ) -> Sensor: """Load the energy sensor.""" nodes = update_gateway_nodes(gateway_nodes, energy_sensor_state) node = nodes[1] return node
43,108
def compute_one_decoding_video_metrics(iterator, feed_dict, num_videos): """Computes the average of all the metric for one decoding. Args: iterator: dataset iterator. feed_dict: feed dict to initialize iterator. num_videos: number of videos. Returns: all_psnr: 2-D Numpy array, shape=(num_samples...
43,109
def supplier_rif_file_path(instance, filename): """Generate file path for new suppliers rif image""" ext = filename.split('.')[-1] filename = f'{uuid.uuid4()}.{ext}' return os.path.join('uploads/supplier/rif/', filename)
43,110
def get_hash(name): """ This hash function receives the name of the file and returns the hash code """ readsize = 64 * 1024 with open(name, 'rb') as f: size = os.path.getsize(name) data = f.read(readsize) f.seek(-readsize, os.SEEK_END) data += f.read(readsize) ret...
43,111
def test_list_events_filter_by_time(api_client, hobby_with_events, hobby_with_events2): """ HobbyEvents should be filterable by start time """ # initialize fixture data to expected values set_event_times(hobby_with_events.events.all(), datetime.time(hour=19)) set_event_times(hobby_with_events2.events.al...
43,112
def geocode_locations(df: gpd.GeoDataFrame, loc_col: str): """ Geocode location names into polygon coordinates Parameters ---------- df: Geopandas DataFrame loc_col:str name of column in df which contains locations Returns ------- """ locations = geocode(df.loc[:, loc_col]) ...
43,113
def get_data(): """Get dummy data returned from the server.""" jwt_data = get_jwt() data = {'Heroes': ['Hero1', 'Hero2', 'Hero3']} json_response = json.dumps(data) return Response(json_response, status=Status.HTTP_OK_BASIC, mimetype='application/json')
43,114
def convert_pdf_to_tif(source_file, output_dir): """ Create a TIF for every Page in the PDF and saves them to the output_dir. :param str source_file: path to the PDF :param str output_dir: path to the output Directory """ log.debug(f"Creating tif files from {source_file} to {output_dir}") ...
43,115
def coerce_integer(df): """ Loop through the columns of a df, if it is numeric, convert it to integer and fill nans with zeros. This is somewhat heavy-handed in an attempt to force Esri to recognize sparse columns as integers. """ # Numeric columns to not coerce to integer EXCEPT = ["lat...
43,116
def read_cfg(floc, cfg_proc=process_cfg): """ Reads the given configuration file, returning a dict with the converted values supplemented by default values. :param floc: The location of the file to read. :param cfg_proc: The processor to use for the raw configuration values. Uses default values when t...
43,117
def delete_conference(job: Job, db_session: SessionLocal): """Deletes the conference.""" conference = conference_service.get_by_job_id(db_session=db_session, job_id=job.id) p = plugins.get(INCIDENT_PLUGIN_CONFERENCE_SLUG) p.delete(conference.conference_id) event_service.log( db_session=db_s...
43,118
def get_jsmol_input(request, pk): """Return a statement to be executed by JSmol. Go through the atomic structure data subsets of the representative data set of the given system. Pick the first one that comes with a geometry file and construct the "load data ..." statement for JSmol. If there are no...
43,119
def test_version_parsing(): """VersionNumber can only parse a sequence of integers, separated by periods""" with pytest.raises(ValueError): VersionNumber("1.2.x") with pytest.raises(ValueError): VersionNumber("string")
43,120
def convert_date(raw_date: str, dataserver=True): """ Convert raw date field into a value interpretable by the dataserver. The date is listed in mddyy format, """ date = datetime.strptime(raw_date, "%Y%m%d") if not dataserver: return date.strftime("%m/%d/%Y") return date.strftime("%m...
43,121
def getComputerMove(board): """ Given a board and the computer's letter, determine where to move and return that move. \n Here is our algorithm for our Tic Tac Toe AI: """ copy = getBoardCopy(board) for i in range(1, NUMBER_SPACES): if isSpaceFree(copy, i): # Play out the ne...
43,122
def add(topcell, subcell, center=(0,0)): """ First creates a CellReference to subcell, then adds this to topcell at location center Args: * **topcell** (gdspy.Cell): Cell to be added to * **subcell** (gdspy.Cell): Cell being added Keyword Args: * **center** (tupl...
43,123
def triangular_prism(p1, p2, p3, height, ret_unique_vertices_and_faces=False): """ Tesselate a triangular prism whose base is the triangle `p1`, `p2`, `p3`. If the vertices are oriented in a counterclockwise direction, the prism extends from behind them. Args: p1 (np.ndarray): A 3D point on...
43,124
def realfft(eventfile,segment_length): """ Performing PRESTO's realfft on the binned data (.dat) eventfile - path to the event file. Will extract ObsID from this for the NICER files. segment_length - length of the individual segments """ parent_folder = str(pathlib.Path(eventfile).parent) d...
43,125
def chain_species_base(base, basesite, subunit, site1, site2, size, comp=1): """ Return a MonomerPattern representing a chained species, chained to a base complex. Parameters ---------- base : Monomer or MonomerPattern The base complex to which the growing chain will be attached. basesi...
43,126
def find_one_item(itemname): """ GET the one item in the shop whose title matches itemname. :param itemname: The title to look for in the shop. :type itemname: str :return: dict(str, Decimal, int). A dict representing the requested item. :raise: werkzeug.exceptions.NotFound """ try: ...
43,127
def PromGraph(data_source, title, expressions, **kwargs): """Create a graph that renders Prometheus data. :param str data_source: The name of the data source that provides Prometheus data. :param title: The title of the graph. :param expressions: List of tuples of (legend, expr), where 'expr' i...
43,128
def json_to_csv(json_data, csv_filename, is_header=False): """ Converting JSON data to CSV and saving locally :param json_file: JSON file to convert :param csv_filename: Filename to save csv :param is_header: Whether header should be written or not """ data_file = open(csv_filename, 'a') ...
43,129
def test_d4_3_15v18_d4_3_15v18i(mode, save_output, output_format): """ assertions on a complex type definition, having complexContent, assertions from anySimpleType type. """ assert_bindings( schema="ibmData/valid/D4_3_15/d4_3_15v18.xsd", instance="ibmData/valid/D4_3_15/d4_3_15v18.xm...
43,130
def create_output_subdirectory(subdirectory: str) -> str: """ Creates a subdirectory in the output directory. """ path = os.path.join(GLOBAL_CONFIG['output_directory_path'], subdirectory) path = os.path.abspath(path) os.makedirs(path, exist_ok=True) return path
43,131
def get_maxlevel(divs, maxlevel): """ Returns the maximum div level. """ for info in divs: if info['level'] > maxlevel: maxlevel = info['level'] if info.get('subdivs', None): maxlevel = get_maxlevel(info['subdivs'], maxlevel) return m...
43,132
def prenut(ra, dec, mjd, degrees=True): """ Precess coordinate system to FK5 J2000. args: ra - arraylike, right ascension dec- arraylike, declination mjd- arraylike """ if degrees: c = np.pi/180. else: c = 1. raout = ra.astype(np.float)*c decout = dec.as...
43,133
def make_model_and_optimizer(conf): """Function to define the model and optimizer for a config dictionary. Args: conf: Dictionary containing the output of hierachical argparse. Returns: model, optimizer. The main goal of this function is to make reloading for resuming and evaluation ...
43,134
def trange(start: int, end: int, step: int=1, dtype: T.Dtype = None) -> T.Tensor: """ Generate a tensor like a python range. Args: start: The start of the range. end: The end of the range. step: The step of the range. Returns: tensor: A vector ranging from start to end ...
43,135
def get_molecules(topology): """Group atoms into molecules.""" if 'atoms' not in topology: return None molecules = {} for atom in topology['atoms']: idx, mol_id, atom_type, charge = atom[0], atom[1], atom[2], atom[3] if mol_id not in molecules: molecules[mol_id] = {'a...
43,136
def disk_partitions(all): """Return disk partitions.""" rawlist = _psutil_mswindows.get_disk_partitions(all) return [nt_partition(*x) for x in rawlist]
43,137
def simple_dataset() -> Dataset: """ This is a simple dataset with no BNodes that can be used in tests. Assumptions/assertions should not be made about the quads in it, other than that it contains no blank nodes. """ graph = Dataset() graph.default_context.add((EGSCHEMA.subject, EGSCHEMA.pre...
43,138
def slugify(value, allow_unicode=False): """ Taken from https://github.com/django/django/blob/master/django/utils/text.py Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to...
43,139
def is_between(start, stop, p): """Given three point check if the query point p is between the other two points Arguments: ---------- start: array(shape=(D, 1)) stop: array(shape=(D, 1)) p: array(shape=(D, 1)) """ # Make sure that the inputs are vectors assert_col_ve...
43,140
def test_no_parse_when_parse_args_false(mock_pipe): """Never run parse when parse args explicitly true.""" out = run('arb pipe', args_in=['one', 'two'], parse_args=False) assert type(out) is Context assert out == {} assert not out.is_in_pipeline_scope mock_pipe.assert_called_once_with( ...
43,141
def get_elasticsearch_type(): """ Getting the name of the main type used """ return settings.ELASTICSEARCH_TYPE
43,142
def run_cmd_code(cmd, directory='/'): """Same as run_cmd but it returns also the return code. Parameters ---------- cmd : string command to run in a shell directory : string, default to '/' directory where to run the command Returns ------- std_out, std_err, return_code ...
43,143
def unpack_le32(data): """ Unpacks a little-endian 32-bit value from a bytearray :param data: 32-bit little endian bytearray representation of an integer :return: integer value """ _check_input_array(data, 4) return data[0] + (data[1] << 8) + (data[2] << 16) + (data[3] << 24)
43,144
def InductionsFromPrescribedCtCq_ST(vr_bar,Ct,Cq,Lambda,bSwirl): """ Returns the stream tube theory inductions based on a given Ct and Cq. Based on script fGetInductions_Prescribed_CT_CQ_ST """ lambda_r=Lambda*vr_bar # --- Stream Tube theory a_ST = 1/2*(1-np.sqrt(1-Ct)) if bSwirl:...
43,145
def run_numpy(in_file, out_file): """ Load data from in_file and save new data into out_file, using numpy. :param in_file: input file with comma-separated values :type in_file: str or unicode :param out_file: output file with comma-separated values :type out_file: str or unicode """ ...
43,146
def _run(): """Makes schema for dense layers. This is effectively the main method. """ figure_object, axes_object = pyplot.subplots( 1, 1, figsize=(FIGURE_WIDTH_INCHES, FIGURE_HEIGHT_INCHES) ) axes_object.axis('off') axes_object.set_aspect('equal') num_layers = len(NUM_NEURON...
43,147
def set_map_layout_old(axes, cbar_space=2.5, cbar_vertical=True, width=17.0): """ set figure height, given width and colorbar setting Needs to be called after all plotting is done. Parameters ---------- axes : ndarray of (Geo)Axes Array with all axes of the figure. cbar_spac...
43,148
def unwrap_Optional_type(t: type) -> type: """ Given an Optional[...], return the wrapped type """ if get_origin(t) is Union: # Optional[...] = Union[..., NoneType] args = tuple(a for a in get_args(t) if a is not type(None)) if len(args) == 1: ...
43,149
def curations(clustering, pipeline): """Insert keys from ephys.ClusteringTask into ephys.Curation""" ephys = pipeline['ephys'] for key in (ephys.ClusteringTask - ephys.Curation).fetch('KEY'): ephys.Curation().create1_from_clustering_task(key) yield if _tear_down: if verbose: ...
43,150
def _read_dictionary(): """Read the british-american dictionary into an internal representation. """ global br_am_dict br_am_dict = dict() with open(FLAGS.br_am_dict, 'r') as f: for line in f: if line.startswith('//'): # ignore comment lines continue line = line.strip(...
43,151
def tox_get_python_executable(envconfig): """Return a python executable for the given python base name. The first plugin/hook which returns an executable path will determine it. ``envconfig`` is the testenv configuration which contains per-testenv configuration, notably the ``.envname`` and ``.basepyt...
43,152
def _normalize_angle(x, zero_centered=True): """Normalize angles. Take angles in radians and normalize them to [-pi, pi) or [0, 2 * pi) depending on `zero_centered`. """ if zero_centered: return (x + np.pi) % (2 * np.pi) - np.pi else: return x % (2 * np.pi)
43,153
def insert_many_from_dataframe(conn, df, table): """ Insert many into table from Dataframe Args: conn df (DataFrame) table (string): table name Returns: None """ params_insert = ["%s" for i in range(len(df.columns))] params_insert = ','.join(params_insert) ...
43,154
def g_fam(arr): """ Returns the next array """ aux = 0 hol = [] while(aux +1 < arr.__len__()): if arr[aux] or arr[aux + 1]: hol.append(True) else: hol.append(False) aux += 1 return hol
43,155
def main_archive(args, cfg: Configuration): """Start running archival""" jobs = Job.get_running_jobs(cfg.log) print('...starting archive loop') firstit = True while True: if not firstit: print('Sleeping 60s until next iteration...') time.sleep(60) jobs = J...
43,156
def k2j(k, E, nu, plane_stress=False): """ Convert fracture Parameters ---------- k: float E: float Young's modulus in GPa. nu: float Poisson's ratio plane_stress: bool True for plane stress (default) or False for plane strain condition. Returns ...
43,157
def exportGeneIdProbeIdMapping(): """Use this function to export a file which is has geneId,probeId columns. """ conn = psycopg2.connect(postgres_uri) cursor = conn.cursor() cursor.execute("select distinct from_id,to_id from stemformatics.feature_mappings where db_id=59") result = cursor.fetchal...
43,158
def get_worker_bonus(job_id, worker_id, con=None): """ :param job_id: :param worker_id: :param con: """ bonus_row = _get_worker_bonus_row(job_id, worker_id, con) if bonus_row is None: return 0 return bonus_row["bonus_cents"]
43,159
def validate_dq_info(dqroot=None, dqtag=None, dqpath=None): """Validate location information for the dreq. This returns no useful value but will throw an informative exception if things are detectably bogus. Not all bogus cases are found, but if if it does blow up then something is certainly wrong...
43,160
def sgd_update(trainables, learning_rate=1e-2): """ Updates the value of each trainable with SGD. Arguments: `trainables`: A list of `Input` Nodes representing weights/biases. `learning_rate`: The learning rate. """ # TODO: update all the `trainables` with SGD # You can access ...
43,161
def get_attribute_distribution(): """ Attribute weights based on position and prototype, in this order: [potential, confidence, iq, speed, strength, agility, awareness, stamina, injury, run_off, pass_off, special_off, run_def, pass_def, special_def] """ attr_dist = { 'QB': { ...
43,162
def big_bodda_boom(): """This function calls on big_big_bodda_boom function.""" big_big_bodda_boom()
43,163
def infer(test_reader, use_cuda, model_path): """ inference function """ place = fluid.CUDAPlace(0) if use_cuda else fluid.CPUPlace() exe = fluid.Executor(place) with fluid.scope_guard(fluid.core.Scope()): infer_program, feed_target_names, fetch_vars = fluid.io.load_inference_model( ...
43,164
def test_k_from_end_empty(): """ Will return 'empty' if linked list has no nodes. """ courses = LinkedList() assert courses.k_from_end(6) == 'Empty Linked List'
43,165
def predict(product: Product): """Return ML predictions, see /docs for more information. Args: product: (Product) the parsed data from user request Returns: A dictionnary with the predicted nutrigrade and the related probability """ sample = { "energy": round(float(...
43,166
def get_stock_historicals(symbol, interval="5minute", span="week"): """Returns the historical data for a SYMBOL with data at every time INTERVAL over a given SPAN.""" assert span in ['day', 'week', 'month', '3month', 'year', '5year'] assert interval in ['5minute', '10minute', 'hour', 'day', 'week'] historicals = r...
43,167
def re_match_both2( item, args ): """Matches a regex with a group (argument 2) against the column (number in argument 1)""" import re # setup (re_col1, re_expr1, re_col2, re_expr2 ) = args if re_expr1 not in compiled_res: compiled_res[re_expr1] = re.compile(re_expr1) if re_expr2 not in ...
43,168
def at_least(actual_value, expected_value): """Assert that actual_value is at least expected_value.""" result = actual_value >= expected_value if result: return result else: raise AssertionError( "{!r} is LESS than {!r}".format(actual_value, expected_value) )
43,169
def test_git_readRepository_without_repo(): """Test the read repository without argument, provide the current git info back. :return: """ owner, repo = djWasabi.git.readRepository() assert owner == "dj-wasabi" assert repo == "dj-wasabi-release"
43,170
def clean_text(text): """ Clean text : lower text + Remove '\n', '\r', URL, '’', numbers and double space + remove Punctuation Args: text (str) Return: text (str) """ text = str(text).lower() text = re.sub('\n', ' ', text) text = re.sub('\r', ' ', text) text = re.sub('\...
43,171
def add_organization_to_user(organization, user): """ Add a non-empty organization to the user. """ if organization: user.qset_set.add(organization)
43,172
def fnmatch_list(filename, pattern_list): """ Check filename against a list of patterns using fnmatch """ if type(pattern_list) != list: pattern_list = [pattern_list] for pattern in pattern_list: if fnmatch(filename, pattern): return True return False
43,173
def math_div_str(numerator, denominator, accuracy=0, no_div=False): """ 除法 :param numerator: 分子 :param denominator: 分母 :param accuracy: 小数点精度 :param no_div: 是否需要除。如3/5,True为3/5,False为1/1.6 :return: """ if denominator == 0 or numerator == 0: return 0 if abs(numerator) < ab...
43,174
def create_comments(post): """ Helper to create remote comments. :param post: :return: """ comment_list = list() post = post.get('posts')[0] for c in post.get('comments'): comment = Comment() comment.author = create_author(c.get('author')) comment.comment = c.get...
43,175
def zero_fuel(distance_to_pump, mpg, fuel_left): """ You were camping with your friends far away from home, but when it's time to go back, you realize that you fuel is running out and the nearest pump is 50 miles away! You know that on average, your car runs on about 25 miles per gallon. There are 2 gal...
43,176
def get_routing_matrix( lambda_2, lambda_1_1, lambda_1_2, mu_1, mu_2, num_of_servers_1, num_of_servers_2, system_capacity_1, system_capacity_2, buffer_capacity_1, buffer_capacity_2, routing_function=get_weighted_mean_blocking_difference_between_two_systems, alpha=0, )...
43,177
def merge_sort(S): """Sort the elements of Python list S using merge-sort algorithm""" n = len(S) if n < 2: return # list is already sorted # divide mid = n // 2 S1 = S[0:mid] # copy of first half S2 = S[mid:n] # copy of second half # conquer (wit...
43,178
def astrange_to_symrange(astrange, arrays, arrname=None): """ Converts an AST range (array, [(start, end, skip)]) to a symbolic math range, using the obtained array sizes and resolved symbols. """ if arrname is not None: arrdesc = arrays[arrname] # If the array is a scalar, return None...
43,179
def WriteSamplesToFile(file_path, results, test_env): """Write samples to file.""" print '==== Write %d samples to %s' % (len(results), file_path) spec = { 'test': test_env['test'] if 'test' in test_env else 'unknown-test', 'product_name': test_env['product_name'] if 'product_name' in test_e...
43,180
def get_union(*args): """Return unioin of multiple input lists. """ return list(set().union(*args))
43,181
def retrieve(func): """ Decorator for Zotero read API methods; calls _retrieve_data() and passes the result to the correct processor, based on a lookup """ @wraps(func) def wrapped_f(self, *args, **kwargs): """ Returns result of _retrieve_data() func's return value is p...
43,182
def specificity(y, z): """True negative rate `tn / (tn + fp)` """ tp, tn, fp, fn = contingency_table(y, z) return tn / (tn + fp+pseudocount)
43,183
def supress_unobserved_task_logging(): """Suppresses logs about faulted unobserved tasks. This is similar to Python Pulumi user programs. See rationale in `sdk/python/cmd/pulumi-language-python-exec`. This scope of this setting necessarily bleeds beyond this test; it has to do so because the undesi...
43,184
def untag_file(fname, tag, comment=False): """Removes all of a given tag from a given TeX file or list of files. Positional arguments: fname -- file path of file to be edited, or list of file paths tag -- tag to be removed Keyword arguments: comment -- True to process comment lines, False othe...
43,185
def deploy_template(template): """ :type template: WavycloudStack :return: cloudformation waiter object """ stack_name = template.stack_name logger.debug(pformat(get_stacks_by())) logger.debug(pformat(json.loads(template.to_json()))) policy = template.get_template_policy() cloudform...
43,186
def get_model_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn): """ :param subscenarios: SubScenarios object with all subscenario info :param subproblem: :param stage: :param conn: database connection :return: """ c1 = conn.cursor() new_stor_costs = c1.execut...
43,187
def pad_image(image, padding): """ Pad an image's canvas by the amount of padding while filling the padded area with a reflection of the data. :param image: Image to pad in either [H,W] or [H,W,3] :param padding: Amount of padding to add to the image :return: Padded image, padding uses reflection al...
43,188
def delta_obj_size(object_image_size, model_image_size): """To compute the delta (scale b/w -inf and inf) value of object (width, height) from the image (width, height) using sigmoid (range [0, 1]). Since sigmoid transform the real input value between 0 and 1 thus allowing model to learn unconstrained. Paramet...
43,189
def get_relname_info(name): """ locates the name (row) in the release map defined above and returns that objects properties (columns) """ return RELEASES_BY_NAME[name]
43,190
def swap(bee_permutation, n_bees): """Foraging stage using the swap mutation method. This function simulates the foraging stage of the algorithm. It takes the current bee permutation of a single bee and mutates the order using a swap mutation step. `n_bees` forager bees are created by swapping two uni...
43,191
def update_boundaries(x=None): """ This is the main processing code. Every time a slider on a trackbar moves this procedure is called as the callback """ # get current positions of four trackbars maxHSV[0] = cv2.getTrackbarPos('Hmax', 'image') maxHSV[1] = cv2.getTrackbarPos('Smax', 'image') ...
43,192
def info(from_github=False, from_pypi=False, update_cache=False, as_json=False): """Show information about MSL packages. The information about the packages can be either those that are installed or those that are available as repositories_ on GitHub or as packages_ on PyPI. The default action is to sh...
43,193
def get_stream(stream_id, return_fields=None, ignore_exceptions=False): """This function retrieves the information on a single publication when supplied its ID. .. versionchanged:: 3.1.0 Changed the default ``return_fields`` value to ``None`` and adjusted the function accordingly. :param stream_id:...
43,194
def get_grade_mdata(): """Return default mdata map for Grade""" return { 'output_score': { 'element_label': { 'text': 'output score', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'forma...
43,195
def flatten_dict_join_keys(dct, join_symbol=" ", simplify_iterables=False): """ Flatten dict with defined key join symbol. :param dct: dict to flatten :param join_symbol: default value is " " :param simplify_iterables: each element of lists and ndarrays is represented as one key :return: """ ...
43,196
def prev_factor(target, current): """Given a target to factorise, find the next highest factor above current""" assert(current<=target) candidates = factors(target) if len(candidates) == 1: return 1 logging.info("Selecting previous factor %d of %d given %d" % (candidates[candidates.index(current)-1], target, cur...
43,197
def compute_weight_BTEL1010(true_energy, simtel_spectral_slope=-2.0): """Compute the weight from requirement B-TEL-1010-Intensity-Resolution. Parameters ---------- true_energy: array_like simtel_spectral_slope: float Spectral slope from the simulation. """ target_slope = -2.62 # sp...
43,198
def blog_post(post_url): """Render post of given url.""" post = Post.query.filter_by(url=post_url).first() if post is None: abort(404) timezone_diff = timedelta(hours=post.timezone) return render_template('blog_post.html', post=post, tz_diff=timezone_diff)
43,199