content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def clean_data(df): """ Takes a dataframe and cleans the data. :param df: pandas dataframe containing the data to clean :return: pandas dataframe with cleaned data """ # drop duplicates df = df[df.duplicated() == False] # force related category to be bi-variate df.loc[df['related']==...
74acb3a5d9c5d36c3c301f79d50c7c8d60f60067
569,144
def create_url(keyword): """Create API call URL string""" url = (f'http://api.dataatwork.org/v1/jobs/' + f'autocomplete?ends_with="{keyword}"') return url
7347ea980eb4c8e82e68d01c3df03d0d320a98b5
569,148
def timezone_from_offset(offset): """Given an offset (integer), returns a timezone in the format UTC(+/-)<offset> (or simply 'UTC' if the offset is zero. ex: timezone_from_offset(-3) -> "UTC-3" """ if offset==0: return "UTC" elif offset>0: return "UTC+"+str(offset) else: ...
b631742f56d4ff415a3ba8a086f73c69f1947f8f
569,150
def parse_line(line): """ Parse a line from the ignore config :param line: line :return: None if line is not in a valid ignore format, or a tuple of (file path, block name, rank) """ if not line or line.strip().startswith('#'): return None line_parts = [l.strip() for l in line.split...
5c2808924c23aa7c504bc1499c7a6a016f8839c0
569,154
def unescape_ass_tag(text: str) -> str: """Do the reverse operation to escape_ass_tag(). :param text: text to unescape :return: unescaped text """ return text.replace(r"\\", "\\").replace(r"\[", "{").replace(r"\]", "}")
edc3f2fe9c6b5364d61d881cf77818e751dbda23
569,155
import collections def backward_step(activations, targets, layers): """ Perform the backpropagation step over all the layers and return the parameter gradients. Input: activations: A list of forward step activations where the activation at each index i+1 corresponds to the activation ...
fc369fac0291c6ded6bd6f73c67a801c160449d2
569,156
def chunk_list(items, size): """ Return a list of chunks :param items: List :param size: int The number of items per chunk :return: List """ size = max(1, size) return [items[i:i + size] for i in range(0, len(items), size)]
5c932be571fc1caf828d19a8d050f4a04a0e2800
569,157
def credit_fe_columns_subset(data_frame, columns): """ Subset of the dataset with as selected subset of fields. :param data_frame: Spark DataFrame :return: Spark DataFrame with only the subset of columns """ data_frame = data_frame.select(columns) return data_frame
644b8a032f113955f81a97ce93bf19df1cbba9ca
569,158
def gzipped_extension(filename): """ Return true if file seems to be gzipped based on extension """ return filename[-3:] == '.gz'
90095d2ce22fe289db4acba93a69fc1af0c76a36
569,160
def checksum(data): """ Compute a checksum for DATA. """ # Remove this later after development assert isinstance(data, bytearray), "data must be a bytearray" chk = data[0] for i in range(1, len(data)): chk ^= data[i] return chk
88ada906a772745d8a203e0a65f0356001ebbcb6
569,165
import pytz import calendar def dt2epoch (dt): """ get an epoch time corresponding to a datetime object :param dt: datetime object to convert :rtype: int (epoch time) """ # convert to UTC if hasattr(dt, 'tzinfo') and dt.tzinfo: UTC = pytz.timezone('UTC') utcdt = ...
c9de34003573c68fa237a67ca7e4906e036c7615
569,167
def lookup_schema_target_namespace(e): """ For the given BaseSchema element find the target namespace. The targetNamespace is that of this element or if not defined it is that of the first parent element which has targetNamespace attribute defined. """ if 'targetNamespace' in e.attrib: ...
3d69253de5f7623f3ed0b5b6f037dc3a367c1f84
569,169
def parse_cigar(cigar): """ Parse a cigar string into a list of operations :param cigar: a cigar string :returns: A list of tuples of the form (length, operation) """ cigar = cigar ops = [] while len(cigar) > 0: for i, c in enumerate(cigar): if c in ("=", "X"...
a4754972ff11dafa522eed70ad779073ec35fd39
569,170
def evaluation(xnodes,weights,fvalues,value): """ Evaluating the barycentric interpolant p(x) p(x) = \sum_{j=0}^{n} ((w_j f(x_j))/(x-x_j))/ (\sum_{j=0}^{n} w_j/(x-x_j)) where w_j = 1/(pi*(x_j - x_i) { j \= i}) Inputs: nodes x_j, weights w_j, f(x_j) and the location of where teh interpolant should be...
ecaa450297b372783bcde84f42c92aaf095a4d3b
569,171
def get_features_json_file_path(input_image_path): """Get the appropriate features JSON output path for a given image input. Effectively appends "--features" to the original image file and places it within the same directory. Parameters ----------- input_file_path: str Path to input i...
62aafb24ba47045a49e50b8ee989ffc9161913f0
569,177
def get_photo_ids(g, aid): """Retrieve all the photo IDs in a specified album.""" photo_list = [] conn_name = 'photos' while True: # Retrieve and parse the album IDs. photos = g.get_connections(id=aid, connection_name=conn_name) for photo in photos['data']: photo_list.append(photo['id']) # Continue the...
98108372db10d090c8739d51673815424a0bbd17
569,182
def make_descriptor_string(attribute, value): """ Create a key-value string to form part of a GTF entry. Example: gene_id and ENSG00000117676.13 becomes gene_id "ENSG00000117676.13"; """ return str(attribute) + ' "' + str(value) + '";'
8c685543149032a74839257667804985cdaee046
569,184
def bmr(sex, weight, height, age): """ return the Basal Metabolic Rate (BMR) based on Miffin-St Jeor Equation :param sex: person sex, m or w :param weight: person weight in kg :param height: person height in cm :param age: person age in years :return: bmr """ base_bmr = 1...
1b63a28bcc49572055b9a0863375e8578d393458
569,187
def x_edges_interval(df_agg): """Set the x-axis edges to be the edges of the bucket interval""" res = df_agg.assign( x_left=lambda df: df.index.left, x_right=lambda df: df.index.right, ) return(res)
3ca1420f2505a7a5d06fecb7856d6b2952595541
569,189
def rcBase(base): """Return the reverse complement of the base.""" base = base.upper() if base == 'A': return 'T' if base == 'C': return 'G' if base == 'G': return 'C' if base == 'T': return 'A' return 'N'
368f337adc24a16b324e9323b5a249cfa0971733
569,192
def _get_counter_by_name(agent, name): """ Get a counter by its name A counter name is expected to be in the following form: - <group>.<name>.<unit>.<rollup> Args: agent (VConnector): A VConnector instance name (str): A counter name Returns: A vim.Performa...
ce612fabd76e2bdf08cee9ca7c3f9bc4f578c93f
569,194
def term_frequency(text, term, per=1000): """ :type text: Text :param text: The text to be analysed :param term: A term/word :type term: str :param per: An Int determining per how many terms the frequency should be evaluated :type per: int :return: The frequency of the term appearing in ...
0e8241981e54dec7526ccaa04b0a82133fbd7fbe
569,195
def get_aperture_pos(sequence): """ Calculate positions of apertures. Returns ------- List of tuples with index and position of OPE in sequence. """ d = 0.0 d_ = [] for idx, ope in enumerate(sequence): if ope.has_aperture(): d_.append((idx, d)) else: ...
27cbba5c4fc5a49dc9523333dd2dfda98ebbb8aa
569,196
def fake_traj(traj_template, ID, seed): """Return a new trajectory that has the same data as `traj_template`, but a different `ID` and `seed`. Assumes that `traj_template` only has a single record (i.e., it was created from QSD data)""" assert len(traj_template.record) == 1 orig_id = traj_template.I...
2b8dff8c6d02a8f54e0d71fca6d9c3a55d3c1c5a
569,199
def extract_substring(string, left, right, right_to_left=False): """Return a substring from a string. Parameters ---------- string : |str| A string to be parsed. left : |str| A character representing the left bound of a target substring. right : |str| A character represe...
63d9f48fdc2f32bd600d32bdb15a435981e569bc
569,201
def prod(sequence, inplace=False): """Perform the product of a sequence of elements. Parameters ---------- sequence : any object that implements `__iter__` Sequence of elements for which the `__mul__` operator is defined. inplace : bool, default=False Perform the product inplace (us...
036e0b6f3deb190b36dd6ea4e2ba605fa84e9705
569,203
def column(lexdata, lexpos): """ Calculate the (1-indexed) column number given the input data and the current position. """ last_cr = lexdata.rfind('\n', 0, lexpos) if last_cr < 0: return lexpos + 1 else: return lexpos - last_cr
3fc081d7fe984eb577f13d9457d96c65f784722d
569,207
def mat_approx_equal(x, y, tol=1e-5): """Returns True if each cell in 2D iterable matrix ``x`` differs by less than ``tol`` from the corresponding element in ``y`` """ if len(x) != len(y): return False for row_x, row_y in zip(x, y): if len(row_x) != len(row_y): return Fal...
da35edbaa67b8f4cea342e0538f6b700c65d703d
569,212
from typing import Counter def init_counters(tags, not_count_tags): """ Given a list of tags, such as ["word", "char", "ner", ...], return a dictionary of counters: tag -> Counter instance. """ counters = {} for tag in tags: counters[tag] = Counter() for tag in not_count_tags: ...
e93f4774da2b96a619873ee3847645627e7efc66
569,213
def tlv_file_mapping(tlv_data_mapping, tmp_path): """Return the path to an XML file containing the mapping.""" path = tmp_path / "mapping.xml" path.write_bytes(tlv_data_mapping) return path
ba24e3711c2e90f76b34cb719c2110cc59f91c3e
569,217
from sympy import Symbol, symbols def get_coordinates(function): """ Given a function evaluated from finite difference: return the coordinate system and its differential forms Example ------- >>> t, x, y = symbols('t x y') >>> dt, dx, dy = symbols('dt dx dy') >>> U = Function('U'...
862cc69b495d249c8fc9ba564fec25e11ac6b240
569,219
def is_rotation(s, t): """ Returns True iff s is a rotated version of t. """ return len(s) == len(t) and s in t + t
91dca15ce4f94723609d6a6b081425130cd0c3e7
569,224
def get_all_narrative_points(switches, enduse): """Get all narrative points of an enduse Arguments --------- switches : list All switches enduse : str Enduse Returns ------- switch_yrs : list All sorted defined timesteps from narrative """ switch_yrs = s...
aa0f9057c97ca04924d1bb23a627ea9e0ed8a258
569,226
def resource_delete(client, path, id_, params): """Delete an instance of a resource.""" return client.request(f"{path}/{id_}", method="delete", params=params)
baed27c66ebe595875359a20fc0cb4a9d78ae567
569,228
import struct def _parsepackmeta(metabuf): """parse datapack meta, bytes (<metadata-list>) -> dict The dict contains raw content - both keys and values are strings. Upper-level business may want to convert some of them to other types like integers, on their own. raise ValueError if the data is c...
e68061df7ca53d276b8ec6de5f641ea03ce06486
569,232
def yes_no_from_user(msg: str): """ Utility to get a yes/no answer from user and return boolean """ msg = msg + ' [y/n]: ' while True: user_input = input(msg) if user_input == 'n': return False elif user_input == 'y': return True print('enter [y]es or ...
0b906b34951ebd59ab6e5c2b59efdbf9858848d1
569,234
import torch def init_schedulers(args, optimizer, optimizer_alpha, optimizer_beta): """ Initialize LR schedulers. Args: args: The args object obtained with argparse. The following requirements should be met: args.qw is a boolean value indicating whether the model weights s...
1cae42f7e16d169051f4e3a86495eafa830b78b4
569,240
def clamp(val, minVal, maxVal): """ Clamp a value between minVal and maxVal :param val: Incoming value :param minVal: bottom of range :param maxVal: top of range :return: clamped value """ return max(minVal, min(val, maxVal))
d6cc80b790558f75bf15c9cc67b11dc9edc9d145
569,244
from typing import Union import base64 def b64_encode( data: Union[bytes, str], encoding: str = "utf-8", padded: bool = True ) -> str: """ Encodes the string or bytes `data` using Base64. If `data` is a string, encode it to bytes using `encoding` before converting it to Base64. If `padded` is `Tru...
3e26d2187d7d52c1166aadab404e9993b183f908
569,245
def _get_description(var, parameters): """ Get the description for the variable from the parameters. This was manually added in the driver to the viewer_descr parameter. """ if hasattr(parameters, "viewer_descr") and var in parameters.viewer_descr: return parameters.viewer_descr[var] ret...
1c6674cdebead53463ed91bbebf2899a526ffb02
569,248
def find_card_from_header(header, value=None, keyword=None, comment_contens=None): """ Find card from header specified be several possible ways. :param header: Instance of ``astropy.io.fits.Header`` class. :param value: Value of header's card that specifies car...
5db6aae35dbef49106253cbcc0cbc9f98edae95b
569,251
import platform def check_py_version(major: int, minor: int) -> bool: """ Checks the version of Python that was used to run the program to see if it is greater than or equal to the values passed in Args: major (int): the major release version minor (int): the minor release version...
75754f09d4047fb3c38f3c35fa356a1a0566e6e7
569,252
def field_model(key): """ Model to replace each row with the value of single field in the row, with the specified key. """ def model_fn(row): return row[key] return model_fn
a3d39e227b8b6288ed63a96733ba81432a25dbbd
569,253
def simple_addition(first_number, second_number): """ This function adds the first_number to the second_number and returns the sum """ return first_number + second_number
c5e24024e6dd52711357aaea7ac4ef61a32946b1
569,255
def removeListInds(edit_list, pop_inds): """ remove more than one index from a list at once Parameters ---------- edit_list : list pop_inds : list of int Returns ------- edit_list : list """ subtract = 0 if edit_list and pop_inds: for ind in pop_inds: ...
d22466474864a6253fd82a593d413692b88c807f
569,258
def _remove_witespace(raw_string: str) -> str: """Return a new string without any whitespace""" return "".join(raw_string.split())
dc992143530a5a7c08aacab9c061e5470b9a345b
569,266
def check_expr(vdict, expr): """ >>> check_expr({"CSQ": "asdfHIGHasdf"}, to_exprs("CSQ contains 'HIGH'")) True >>> check_expr({"CSQ": "asdfHIGHasdf", "DHFC": 1.1}, to_exprs("CSQ contains 'HIGH' & DHFC < 0.5")) False >>> check_expr({"CSQ": "asdfHIGHasdf", "DHFC": 1.1}, to_exprs("CSQ contains 'H...
24e0902b7064e1ef69a03dad5428de2fe96dc687
569,267
def _Refractive(rho, T, l=0.5893): """Equation for the refractive index Parameters ---------- rho : float Density [kg/m³] T : float Temperature [K] l : float, optional Light Wavelength [μm] Returns ------- n : float Refractive index [-] Raises ...
cfc96a03842a19d3144ac86bfb0637eacd800bff
569,272
import torch from typing import Union def _jitter(values: torch.Tensor, scale: Union[float, torch.Tensor]) -> torch.Tensor: """ Jitters values by the transform: .. math:: \\hat{\\theta} = \\theta + \\epsilon, \\: \\epsilon \\sim \\mathcal{N}(0, \\sigma). Args: values: The valu...
d1920b8694d53fd567caff6e3cd901b308e1fd8d
569,280
def complex_math(x: int, y: int) -> int: """Very complex math calculation. This function will add two numbers and return the result of the calculation. Args: x (int): first number to be calculated. y (int): second number to be calculated. Returns: int: the answer to the calculation...
b7ad970b65eb1d8208df4ba86a1e363a537dcc4b
569,282
def match_closest_time(reftime, searchtimes): """Get time closest to reftime in list of times (searchtimes)""" return str("{}".format(min([float(x) for x in searchtimes], key=lambda x: abs(x - reftime))))
46d09757fba24744e0abe72a92809d8c6bd7cc31
569,283
def num_matches(df): """Total number matches.""" return df.noraw.Type.isin(['MATCH']).sum()
510cddfdd42b49944a2129e5dea090af08b36786
569,284
def schema_url(server, app): """URL of the schema of the running application.""" return f"http://127.0.0.1:{server['port']}/schema.yaml"
e98b4d5e4df383bba812f53d324885ea2b0f1743
569,286
def maketmp(name): """Make a tmp variable name""" return "tmp" + str(name)
d67547523b8a8724b439f0c949edee51eb21db8a
569,287
def mrna_chrom(gff): """ Takes a gff3 object and returns a dictionary of chromosomes with mRNA names as keys. """ res = {} mrna_lines = [line for line in gff.lines if line['line_type'] == 'feature' and line['type'] == 'mRNA'] for mrna_line in mrna_lines: gene_name = mrna_line['attrib...
cccbe665527515b048c2b8f62183a244208e4f92
569,290
def remove_trailing_delimiter(url, trailing_delimiters): """Removes trailing delimiters. Args: url: A url that could potentially have some trailing characters that need to be removed. trailing_delimiters: A string of characters that should not be seen at the end of a URL. Returns: The input url with th...
4ba6f63801b9b69b32fe78616ec1177033275edb
569,291
import itertools def _set_product(set_1, set_2): """Returns the cartesian product of two sets.""" return set(itertools.product(set_1, set_2))
5c70c5424cdea1ae5b1cad7b22b6e5c021c01f0c
569,292
def find_maximum(res): """ Trouver le couple (nombre de poulets achetés, profit) lorsque le profit est maximum. @param res résultat de la fonction :func:`maximum <mlstatpy.garden.poulet.maximum>` @return ``(X, profit)`` maximum """ m = (0, 0) for r in res: ...
ec45e8908479a999aabbe2af7c7a0f3e7ae61f5e
569,294
def cut_deck(deck_size, cards, cut): """Cut deck operation.""" return [(card + change) % deck_size for card, change in zip(cards, (0, -cut))]
49372fc4aba6b2f4f677f2a01682f1f4ba2198b8
569,297
def merge_settings(settings_from_env, settings_from_cli): """ Returns dictionary containing variables needed for trainrunner after merging values from the CLI and environemnt. CLI will take precidence as it is more direct :return: dictionary containing merged variables needed for trainrunner to ...
9582d664350b5c7d97526e8b32327ff4489aac1d
569,298
def float_sum(iterable): """ Sum the elements of the iterable, and return the result as a float. """ return float(sum(iterable))
3bec19ab174a325c5deb57a722f3f89bfd65751a
569,303
def text_sort_key(ex): """Sort using the number of tokens in the sequence.""" if hasattr(ex, "tgt"): return len(ex.src[0]), len(ex.tgt[0]) return len(ex.src[0])
86aae7772542edc5761bf0b153fcb2006f00b33c
569,305
def _make_clean_col_info(col_info, col_id=None): """ Fills in missing fields in a col_info object of AddColumn or AddTable user actions. """ is_formula = col_info.get('isFormula', True) ret = { 'isFormula': is_formula, # A formula column should default to type 'Any'. 'type': col_info.get('type', '...
a87c7e4055979cb9d4b5eb26eece29a796f11263
569,307
import textwrap def dedent(text): """ Removes indentation of text. Useful in text emails that otherwise can't be indented. Example usage:: {% filter dedent %} My text {% if something %} another text {% endif %} {% endfilter %} ...
1d2b40ecdda96429fa1d54633c033072757a3b5d
569,309
from typing import List def get_source_langs(lang_pairs: List[str]) -> List[str]: """ Return list of source languages from args.lang_pairs lang_pairs: List[str] where each element is a str with comma separated list of language pairs """ return [lang_pair.split("-")[0] for lang_pair in lang_pai...
c8f62b4ae578bc040f3f911f9bbaac80ead094d4
569,311
def get_num_dims(inputs): """ Get number of dimensions in one tensor, minus the batch and channel dimension. """ dim = len(inputs.shape) return max(1, dim - 2)
4dd13a3a09f86c453e7b6062f0b1e26ce0a0d565
569,312
from typing import List def to_lines(s: str) -> List[str]: """ Like `str.splitlines()`, except that an empty string results in a one-element list and a trailing newline results in a trailing empty string (and all without re-implementing Python's changing line-splitting algorithm). """ line...
90fac21f535537a731a4e3a3573a2f2cf548f161
569,316
def fill_with_tabs(text, tab_col): """Adds tabs to a string until a certain column is reached. :Parameters: - `text`: the string that should be expanded to a certain column - `tab_col`: the tabulator column to which should be filled up. It is *not* a character column, so a value of, say, "...
cae9c1d17c1e17a962fbd1592a401929aad4a5fe
569,317
def pass_method(*args): """ Method which takes any number of arguments and returns and empty string. Like 'pass' reserved word, but as a func. @param args: Any number of arguments. @return: An empty string. """ return ""
1ee3532a6e4894d87dcc211a41db07fc1b461b02
569,318
def format_dictionary(adict, sep=', ', sort_first=True): """\ Formats a dictionary into a string of key=value pairs. :param adict: dictionary to format :param sep: separator. Default ',' :param sort_first: whether to sort the key-value pairs first before formatting :return: a string with the fo...
4f90a44596dec0a1201671893b7b73f8185ce378
569,319
def is_in_path(id, path): """Determines whether id is in the path as returned from /entity/{id}/path :param id: synapse id string :param path: object as returned from '/entity/{id}/path' :returns: True or False """ return id in [item['id'] for item in path['path']]
31763703069bc3458af2827dc87ad4b90efd4e30
569,322
def build_connections(movies, participants, role, threshold): """ Build connections between movies and participants (cast and directors). The `role` filed in the `attributes` will be constructed with corresponding pointers, and the nodes that are not connected to any movie will be removed. Parameters -----...
601606f4c45a404c0bcbc6fcb56a7be9e7d2f495
569,325
def polignac(num,p): """ input: num can be any positive integer and p and prime number. output: Gives the total number of factors of p in num! (num factorial). Stated another way, this function returns the total number of factors of p of all numbers between 1 and num; de Polignac's formula is prett...
faf5b0e7ffc16451bf74a74433d7dcbec2037895
569,327
import json def get_user_params(job_data): """Decodes the JSON user parameters and validates the required properties. Args: job_data: The job data structure containing the UserParameters string which should be a valid JSON structure Returns: The JSON parameters decoded as a d...
a94a71914ac089182b66fc174d1fffe004683fd3
569,328
def atbash_slow(sequence: str) -> str: """ >>> atbash_slow("ABCDEFG") 'ZYXWVUT' >>> atbash_slow("aW;;123BX") 'zD;;123YC' """ output = "" for i in sequence: extract = ord(i) if 65 <= extract <= 90: output += chr(155 - extract) elif 97 <= extract <= 122...
1f38ab498cd808df9c313608d694363dba439d19
569,333
def explode_hyperedge(hyperedge, hyperedge_id): """ Takes a hyperedge set, and generates all the dyadic connections for a similar regular edge. :param hyperedge: (list) List of participating terms. :param hyperedge_id: (int) Identifier for the hyperedge, used for postgres. :return: (list) List of co...
f584c1d3b86582787651825f58211b0237949cf0
569,335
def texture( mat, texture, location, # Upper-right corner of the TexImage node label, # Label for the TexImg node color_socket=None, alpha_socket=None, is_data=False, ): """Creates nodes for a TextureInfo and hooks up the color/alpha outputs.""" x, y = location # Image Texture...
f1a115284f12417827f54e13908311738908f6dc
569,337
def _prediction_function(model_object, predictor_matrix_in_list): """Prediction function. This function satisfies the requirements for the input `prediction_function` to `permutation.run_permutation_test`. :param model_object: Trained instance of `keras.models.Model` or `keras.models.Sequentia...
f265556f0380ba406d438be1dda27ea3e7f13a7b
569,338
def keying(restype, keying): """Decorator to configure resource type and keying for model classes. restype: the string name for the resource type, used to name auxilliary storage keying: dictionary of column names mapped to (psql_type, function) pairs which define the Postgres storage type ...
ee47262227acfb0ce92272d13c74039173fe4771
569,340
def is_comparison_pass(avg_historical_throughput, test_throughput, tolerance, ref_type='none'): """ Determine whether or not to consider the benchmark test as passed. This is based on whether the throughput of the microbenchmark has decreased more than the allowed tolerance %. Parameters -...
a84788908bde2d8e9caae27bb9d892188d31e53c
569,341
def _PrepareDevicePath(vm, link): """Find device path and grant full permission. Args: vm: VirtualMachine object. link: string. Represents device path. Returns: String represents the actual path to the device. """ path = vm.RemoteCommand('readlink -f %s' % link)[0][:-1] vm.RemoteCommand('sudo ...
4b34f3338ce0b328ff52d27f418674ad5c8a44da
569,342
import logging def add_same_offset_images(parameters,parameters_slave,rd_dem,rd_dem_slave,t0_dem): """Get offsets of the dem for master and slave Parameters ---------- parameters : dict Dictionary with parameters of the master image. Output of function get_params_from_xml() parame...
cce4aacf389dd025897ba1e6d0859b7fe4093b17
569,344
def make_test_output(test_name=None, score=0, max_score=0, output="", visibility=None): """ Return a dictionary representing results of a test. Fields are valid Gradescope autograder JSON. """ result = { "score": score, "max_score": max_score, "output": output } if vi...
5dd4408c8fd102b90998d6fd879bf9c2fe3e5c1f
569,349
def create_container_headers( slug='', link='<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"'): """ Create a header dictionary to be used when creating a cointainer resource. The slug is a string used to identify the container, which may be modified to be a valid URL path segment ""...
02005fabfbfd8acbcbda45e937e015bf0339cf3b
569,354
def get_assignment_similarities(context_documents, ending_documents, similarity_measure): """ Given two dicts of the form (key -> embedding) where both dicts share the same set of keys, returns the similarities between documents of the same key as a list. :param context_documents: :param ending_docu...
c11cc7cc8da874b2cd9e55429e0b0b08e67adf28
569,355
def trim_left(value, max_length): """ Trim the left side of the string so that the length is at most max_length. """ str_value = str(value) return str_value[-max_length:len(str_value)]
53b5b6e90b09613655a819b07d93c20a656bc6a0
569,356
def split_n(seq, num): """Split |seq| in twain with the first part having length |num|.""" if len(seq) < num: raise ValueError('sequence too short: seq={}, num={}'.format(seq, num)) return seq[:num], seq[num:]
c46aca5d869abdb25666a2097ddee5b7bdaef0b6
569,363
def get_bgp_leaf_spine(cfmclient, uuid): """ Get VPC BGP leaf and spine configuration. :param cfmclient: Connected CFM API client :param uuid: VPC UUID from which to retrieve BGP info :return: BGP dictionary object :rtype: list """ path = 'v1/vpcs/{}/bgp/leaf_spine'.format(uuid) re...
17816e3cd8e78a7424f5423b685e22b85dd337e6
569,365
import logging def setLogger(logFilePath): """ Set logger Args: logFilePath ([str]): path to log file Returns: [obj]: logger object """ logHandler = [logging.FileHandler(logFilePath), logging.StreamHandler()] logging.basicConfig(level=logging.INFO, format="%(asctime)s...
659d6c099f2f239020f31d085f52cb5c65ff368d
569,370
def _get_username(user): """ Return user's username. ``user`` can be standard Django User instance, a custom user model or just an username (as string). """ value = None # custom user, django 1.5+ get_username = getattr(user, 'get_username', None) if get_username is not None: val...
e0f80aee5b8f8be2c5c11ca3cbe556f9c80637e9
569,371
def filter_data(data, **kwargs): """ Filter a list of data rows Keyword arguments Filter these keys, only keeping matches. If value is a list perform an in() check, otherwise check for equal values. """ rv = [] for row in data: for key, value in kwargs.items(): if type(value) != list: ...
15bcd9f0477f1632267a92359408ca0323e0e1ed
569,374
def ensure_valid_kernel_type(specified_kernel, kernel_type_list): """ Checks to make sure that `specified_kernel` is in `kernel_type_list` and raises a helpful error if this is not the case. Parameters ---------- specified_kernel : str. Denotes the user-specified kernel class that is to...
f45f60887ffda3899efc771e1ecd1aa636d40abd
569,379
def get_presentation_attributes(filename): """ Parses the given video-filename and determines the type of presentation (real or attack), the quality (laptop or mobile), and in case of attack, the instrument used (video_hd, video_mobile, or print) Returns: presentation: a string either 'real' or...
be97079bf20292074a54ee40e7a8fdbe8bc26694
569,382
def issues_to_corpus(issues): """Convert from list of issues to a corpus. An issue will be extracted as its title, description and attachments. [title, descriptions, attachments] Note: Attachments is also a list of attachments' descriptions Parameters ---------- issues: List of Issue ob...
df27e02193258681ff0e5f15501b74cc49879b35
569,385
def _clean_label(label, lr, dat_type): """Clean the ROI label. Parameters ---------- label : str ROI label. lr : {'L', 'R'} Whether current ROI is left/right. dat_type : {'anat', 'elec'} Whether ROI label comes from anat or elec data. """ # For elec, drop the L/...
5bb6c82d5a981526e1bb09ce5f4e0f91032fa961
569,386
def init_blocks(x, y): """Create a x*y 2D array with all None""" return [[None for _ in range(y)] for _ in range(x)]
2c50d35fe0e5ed73d2684809143f17546e8a0b7b
569,388
def get_dict_from_list(list_of_dicts, key_value, key='id'): """ Returns dictionary with key: @prm{key} equal to @prm{key_value} from a list of dictionaries: @prm{list_of_dicts}. """ for dictionary in list_of_dicts: if dictionary.get(key) == None: raise Exception("No key: " + key ...
906381a7220d7c41d5151984e3c10d2514997643
569,390
import math def get_delta(temp): """ Reference page number: 28-29 Parameters ------------------------------ temp: (``float``) The air temperature in degrees Celcius Returns ------------------------------ delta: (``float``) The slope of the saturation vapor pressure-temp...
a6c1b9e2e774e347f2bc4dc01c1a9445e95b3f87
569,396
import math def pmi(prob_x: float, prob_y: float, prob_xy: float) -> float: """calculate pmi using probabilities, return 0.0 if p_xy is 0""" if prob_xy > 0.0: return math.log(prob_xy / prob_x / prob_y) else: return 0.0
af4cc09230fb2e4a1ea601bf40430f75debe64f3
569,397
def sanitize_journal_name(journal_name: str) -> str: """Sanitize journal name to make it an appropriate directory name""" return journal_name.lower().replace(" ", "_")
88b5af082e8691f224e593377b756e50ef8db75f
569,400