content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def symmetric_closure_function(rel): """ Function to determine the symmetric closure of a relation :param rel: A list that represents a relation :return: The symmetric closure of relation rel """ return rel + [(y, x) for (x, y) in rel if (y, x) not in rel]
c43b123de13931d1caa4088f23b896c1f56f2c1f
660,277
import numpy def _treat_missing(out, x, max_pct_missing=100.): """ # Max_pct_missing to missing data specified, calculate new mask # If fraction of data that is missing is more than the max_pct_missing allows mask point out """ xmask = numpy.ma.less_equal((max_pct_missing / 100.), (numpy.ma.size(x...
ad6bea9936131593be01f9b169564e79dc49cfb5
660,278
import torch def get_pyg_edge_index(graph, both_dir=True): """ Get edge_index for an instance of torch_geometric.data.Data. Args: graph: networkx Graph both_dir: boolean; whether to include reverse edge from graph Return: torch.LongTensor of edge_index with size [2, num_e...
d0300a93a6e4a68302d04dfa8b646b92c7ac256b
660,279
def ctypes_shape(x): """Infer shape of a ctypes array.""" try: dim = x._length_ return (dim,) + ctypes_shape(x[0]) except AttributeError: return ()
13c81a6028a49c41a74f2623cb7936323602795e
660,280
def _loaded_dice_roll(chance_num, cur_state): """Generate a loaded dice roll based on the state and a random number """ if cur_state == 'F': if chance_num <= (float(1) / float(6)): return '1' elif chance_num <= (float(2) / float(6)): return '2' elif chance_num...
df565f1826cd1d10102d188cae1e8f7953244cde
660,281
def get_magicc6_to_magicc7_variable_mapping(inverse=False): """Get the mappings from MAGICC6 to MAGICC7 variables. Note that this mapping is not one to one. For example, "HFC4310", "HFC43-10" and "HFC-43-10" in MAGICC6 both map to "HFC4310" in MAGICC7 but "HFC4310" in MAGICC7 maps back to "HFC4310". ...
822cff3dac5b8aa18ce5f0e6c4bd13b9762a41e6
660,282
def prepare_param_order(request_value): """ request.GETからorder_byのparamを取得する Parameters ---------- request_value : request.GET URLのParam Returns ------- order_param : order_by param order_byを行うparam """ if 'sort' in request_value: order_param = request_v...
995ce765e1e1f77aaf1ac3ba514d25a04dd1e5c8
660,283
def get_environment_variables(std_out_str, marker): """Gets the environment variables from a process :param std_out_str: The std_out pipe :type std_out_str: String :param marker: A begining and end mark of environment variables printed to std_out :type marker: String ...
b00117e732b643d2cfdc12067b5f7d380cd8812d
660,284
import os def expand_input_path(input_path): """Expand the relative input path to absolute path, and add layers model file name to the end if input format is `tfjs_layers_model`. Args: input_path: input path of the model. Returns: string: return expanded input path. """ input_path = os.path.expand...
a052fd906c5111f62b519b8b771f9f8a93101632
660,285
def assert_train_test_temporal_consistency(t_train, t_test): """Helper function to assert train-test temporal constraint (C1). All objects in the training set need to be temporally anterior to all objects in the testing set. Violating this constraint will positively bias the results by integrating "fut...
92842014832ddb2d8e9b3a97172f92f5d9f82bed
660,286
def _get_thermostat(api, serial_number): """Authenticate and create the thermostat object.""" api.authenticate() return api.get_thermostat(serial_number)
443b16cf5bfda160593d848143d4189f71d27e92
660,287
import torch def construct_triplets(dist_mat, labels, hard_type='tri_hard'): """Construct triplets inside a batch. Args: dist_mat: pytorch tensor, pair wise distance between samples, shape [N, N] labels: pytorch LongTensor, with shape [N] Returns: dist_ap: pytorch tensor, distance(...
2afdbd6dec17ea9fd53dcc7141c619d2c54d4491
660,288
def _layout_column_width(col): """ Returns the logical column width of a column """ column_equivs = [pi.column_equiv for pi in col.presinfo if pi.column_equiv is not None] if len(column_equivs) > 0: # assume user has not done something silly like put # *2* column_equiv classes on a c...
f3df6c0863e2f04c4808b4817ccabb4a304bb951
660,289
import argparse def parse_arguments(): """Parses the arguments passed on the command line """ parser = argparse.ArgumentParser() required = parser.add_argument_group('required arguments') required.add_argument('-p', '--path', help='Path to files to ingest', required=True) required.add_argumen...
152a66d2d6cc9c0492e6e07d80b047b372c8ef1e
660,291
def _replace_param_fixed_length(param): """Generate a fixed length data element if param matches the expression [<type>_WITH_LENGTH_<length>] where <type> can be: STRING, INTEGER, STRING_ARRAY, INTEGER_ARRAY, JSON. E.g. [STRING_WITH_LENGTH_15] :param param: parameter value :return: tuple with repla...
bd1e6b3434aa82060c5e4ea65e78f953e873a70b
660,292
def generate_node_index_dict(node_list): """Returns a dict of node -> position in node_list Can be used for creation of links between nodes in d3 force layout """ node_index_dict = {} for node in node_list: node_index_dict[node["course_id"]] = node_list.index(node) return node_index_di...
82faa564ae348c950b7e8f88d886fda14576f4bc
660,293
def get_one_col_str(i_col, line): """ extract the column index in line i_col: index of column line: string """ col_split = '\t' return line.split(col_split)[i_col]
ce8a63e0522f2038452ef33d751c2a3feb69b974
660,294
def format_ogr_connection(connection): """a method to format a connection string for ogr usage """ return ( f"PG:host={connection['host']} " f"port=5432 user='{connection['user']}' " f"password='{connection['password']}' " f"dbname='{connection['database']}'" )
71032d88f84b7588fc2b60d07e139d6cf8280510
660,295
import sqlite3 def sqlite_conn_get(dbpath: str): """ devuelve la conexión a una db ms access """ return sqlite3.connect(dbpath)
979a150dfe9bac4a1c129977f85f887a68474da0
660,296
def PdeZ(Z): """ PdeZ : Atmospheric pressure (in hpa) as a function of altitude (in meters) """ p = 1013.25 * pow(1 - 0.0065 * Z / 288.15, 5.31) return (p)
dd89439d2a629e0ce49e4c8f3d8045790a5b57b8
660,297
import spwd def unix_crypted_shadow_password(username): """ Requests the crypted shadow password on unix systems for a specific user and returns it. """ crypted_password = spwd.getspnam(username)[1] return crypted_password
2fd5f59176ebc1256c5dff70e0f4e6d773af2aa2
660,298
from typing import Tuple import re def _lex_whitespace(header: str) -> Tuple[str, str]: """ >>> _lex_whitespace(" \\n a") ('', 'a') >>> _lex_whitespace(" abc") ('', 'abc') >>> _lex_whitespace("a ") ('', 'a ') """ whitespace_match = re.match(r"\s+", header) if not whitespace_ma...
7e8a0d856d9c3726850f93bbbfb6bebd73271d7f
660,299
import numpy as np import logging import sys def calc_accuracy(targets, predictions): """ determine classification accuracy :param targets: numpy vector of m true targets :param predictions: numpy vector of m predicted targets :return: classification accuracy """ try: accuracy = ...
d6c65c5432bc69655eeea1e0ed0beaf855c221f7
660,301
def cultivate(ctx, package, files, **tend_args): """ Add weed(s) to a package. The files are moved to the package specified by a package name, and are symlinked back into the garden. """ return ctx.obj["garden"].cultivate(package, files, **tend_args)
f8c2f7250d5d122a3f1b6a6b9c8ddc9edc4f55ae
660,302
def compute_cchalf(mean, var): """ Compute the CC 1/2 using the formular from Assmann, Brehm and Diederichs 2016 :param mean: The list of mean intensities :param var: The list of variances on the half set of mean intensities :returns: The CC 1/2 """ assert len(mean) == len(var) n = len(...
f8cb9de5a4b4367be4be3b4125316ae56210a78b
660,303
def attrFinder(attrib, attribString): """Easy function to pull attributes from column 8 of gtf files""" for entry in attribString.split(";"): if entry.lstrip().startswith(attrib): return entry.lstrip().split(" ")[1][1:-1] return None
2838ebea0caada50d527b57c8c5008989e6c88a3
660,304
import warnings def _method_cache_key_generator(*args, **kwargs) -> int: """A cache key generator implementation for methods. This generator does not implement any hashing for keyword arguments. Additionally, it skips the first argument provided to the function, which is assumed to be a class instanc...
00e8b26beb63a1c44fad35fce0cea2d132e79f38
660,305
def _mst_path(csgraph, predecessors, start, end): """Construct a path along the minimum spanning tree""" preds = predecessors[start] path = [end] while end != start: end = preds[start, end] path.append(end) return path[::-1]
7ce30eb6c155dab1fe8dad886b1adf2a4f71b408
660,308
def kewley_sf_nii(log_nii_ha): """Star forming classification line for log([NII]/Ha).""" return 0.61 / (log_nii_ha - 0.05) + 1.3
e44dade36ffc5879c3206dbf9aaaa30b9dfbcf3f
660,310
def _root_getitem_ ( self , key ) : """Get the item from ROOT-file >>> obj = db['A/B/C/histo'] """ try: value = self.cache[key] except KeyError: value = self.dict[key] if self.writeback: self.cache[key] = value return value
c581894a272add0dbcc09c8148ce10b7e56ca69b
660,311
def str_to_utf8(x): """ #Before writing/output to printer put in utf-8 """ try: return x.encode("utf-8") except: return x
3b5bc86a180dd51237cac414ddb3c8249f972462
660,312
def create_metadata_container(tooling): """ (Re)creates metadata container """ container = {'Name': 'MetamateMetadataContainer'} res = tooling.anon_query( "SELECT Id,Name FROM MetadataContainer WHERE Name='%s'" % container['Name']) if res['size'] == 1: tooling.delete('/sobjects/Metadata...
70194974226761aa62bb9ede9312aa218331553e
660,313
import math def calc_distance(ij_start, ij_end, R): """" Calculate distance from start to end point Args: ij_start: The coordinate of origin point with (0,0) in the upper-left corner ij_end: The coordinate of destination point with (0,0) in the upper-left corner R: Map resolution ...
4242d8fe01f3d286f69aac2a9432726280271530
660,314
def acronym_match(mark, candidate, lex): """ Check whether a Markable's text is an acronym of a candidate Markable's text :param mark: The Markable object to test :param candidate: The candidate Markable with potentially acronym-matching text :param lex: the LexData object with gazetteer information and model set...
2ddd5ee179354f34d40c3743a2c76b56a8117b31
660,315
from datetime import datetime, timedelta def ldap_to_datetime(timestamp: float): """ Takes an LDAP timestamp and converts it to a datetime object """ return datetime(1601, 1, 1) + timedelta(timestamp/10000000)
c4d42c606a220ba67b6ac2860cb3df87775b38bd
660,316
def parse_dss_bus_name(dss_bus_name: str, sep='.') -> str: """ Given a bus name string that may include phase from opendss, returns just the busname. Assumes that dss appends bus names with phases, separated by '.' Ex: 'sourcebus.1.2.3' -> 'sourcebus' """ return dss_bus_name.split(sep)[0]
7bec2a59724381f99a95df45e60b1bcbffbb05e9
660,318
import re def get_version(filename='canaveral/__init__.py'): """ Extract version information stored as a tuple in source code """ version = '' with open(filename, 'r') as fp: for line in fp: m = re.search("__version__ = '(.*)'", line) if m is not None: versi...
80c2e54b2b9b435162ac9f2879d6122055140f04
660,319
import pandas import logging def _makeIndex(df): """ Synapse entity-view rows unique-id or index is defined based on three values: ROW_ID, ROW_VERSION, and etag. This function concatenates ROW_ID, ROW_VERSION, and etag column values by '_' and assigns it as the data frame input index. Hint: the input ...
1a2efa54fcd96fda27e4f9e0a1683e4a93bcf808
660,321
import math def permutation_number(s: str, num: int) -> str: """ Find Nth permutation of the string letters.""" def nth(s, n): if n: n0, n1 = divmod(n, math.factorial(len(s)-1)) s = s[n0] + nth(s[:n0]+s[n0+1:], n1) return s # Assume initial string is in lexicograph...
15fd8e9c40be913419b1744ecb0db8325435f32d
660,322
def rk4(x,t,tau,derivsRK,**kwargs): """ Runge-Kutta integrator (4th order). Calling format derivsRK(x,t,**kwargs). Inputs: x current value of dependent variable t independent variable (usually time) tau step size (usually timestep) derivsRK ri...
5010992dcecb39943750e5043fc6b489c3fa0a37
660,325
import sys def check_setting_option_value(option, value): """ checks that an option has a legal value :param option: name of the option to verify from settings file :param value: value of the option to verify :return: True if the option has the correct type, exits if the value ha...
a6da0e1759f3f0c49a285f684eba0d1a50623896
660,326
import math def cos(X, max_order=30): """ A taylor series expansion for cos The parameter `max_order` is the maximum order of the taylor series to use """ op = 1 + 0*X X2 = X * X X2n = 1 + 0*X for n in range(1, max_order): X2n = X2n*X2 op = op + ((-1) ** (n) / math.gamm...
151987cac39f3cf71276cc34fbdf4c5af5be673a
660,327
def fib(n): """ Assumes n an int >= 0 Returns Fibonacci of n""" if n == 0 or n == 1: return 1 else: return fib(n-1) + fib(n-2)
477816f8aa60c444528f99124f85b7e87ad6272d
660,328
def color_based_on_operation(data, matching_criteria, matching_color, not_matching_color): """ :param data: :param matching_criteria: :param matching_color: :param not_matching_color: :return: """ color_associated = list(map(lambda x: matching_color if matching_criteria(x) else not_matc...
a295846234b05f64eccf6768f879ff78d4163ebf
660,329
def _unsplit_name(name): """ Convert "this_name" into "This Name". """ return " ".join(s.capitalize() for s in name.split('_'))
9dd79695af74bb1755a09169870b7c2de472353c
660,331
def listminus(L1, L2): """In : L1 : list or set L2 : list or set Out: List of items in L1 that are not in L2. Helper for min_dfa and bash_1. Implements subtraction (L1 - L2). """ return [x for x in L1 if x not in L2]
d5b39b530fd41493b53975c7ed34eab9bf55425d
660,333
def generate_title(stem: str) -> str: """Generate title in rst format using ``file_name``.""" return f"{stem}\n{'*' * len(stem)}\n"
f0f90bd4b2b2522ca161caa4fb38d4afddcac140
660,335
from typing import List from typing import Optional def str_replace(s: str, old: List[str], new: Optional[List[str]] = None) -> str: """Replaces occurences of all strings in *old* by the corresponding ones in *new*. If None is passed in new, *old* are simply removed fromm *s*""" if new is None: new = ['']...
9c070a2f6d3d3e63a32498fc5e5cdb3b3c55292b
660,336
def shift(l, k): """ Parameters ---------- l : list k : int Returns ------- The list l with k zeros appended . """ for _ in range(k): l.append(0) return l # Complexity: Θ(k)
6fc124dec290c94164e9adf22f53f57da259d32e
660,337
def dist(a, b): """Use pythagorean theorem to find the distance""" return (a ** 2 + b ** 2) ** (1 / 2)
e8a6d8b4f11352ae4732942c6b7f605f4b9d55f9
660,338
def precision(cm): """ Return precision. :param cm: Confusion matrix. :return: Value of precision. """ return float(cm[1, 1]) / (cm[1, 1] + cm[0, 1])
5f919854b4b329daea17e1d798c2e848c5bc847f
660,339
import struct def read_signed_long(buf): """ Reads an unsigned long from `buf`. """ return struct.unpack("i", buf.read(4))[0]
e0703773b67a7890048dec857c39435074e0a78d
660,340
def get_window_g_value(window): """For windows based on SimpleGlazingSystems, returns the g-value. Otherwise, an exception is thrown. """ assert hasattr(window.Type.Layers[0].Material, 'GValue'), \ "SimpleGlazingSystem required" assert len(window.Type.Layers) == 1, "SimpleGlazingSystem requi...
2d6c0b2c0d11ac693ce8a0c99ed57583f52dc8d0
660,341
def crop(image, startX, startY, endX, endY): """ Crop an image :param image: Image to be cropped :param startX: Starting X coord :param startY: Starting Y coord :param endX: Ending X coord :param endY: Ending Y coord :return: Cropped image """ cropped = image[startY:endY, startX...
361d9f799aef03f3ce9d621550801c4d2a293b3b
660,342
from typing import List from typing import Dict def csv_to_list(data: List[List], fields: List[str]) -> List[Dict[str, str]]: """ Converts the raw csv column to a list of dicts with the specified field names """ return list(dict(zip(fields, f)) for f in data if f)
137fd6c051e7e7af7b9430ce082871c6097a30ca
660,343
def map_substring(s, dict_map): """Map dictionary values to keys if a column contains the dictionary keys""" for key in dict_map.keys(): if key in s.lower(): return dict_map[key] return 'other'
080fe70db5e0d10da704e8b8b2328b3ccc9722f1
660,344
import argparse def parse_arguments(): """ Parse the command line arguement. :return: """ parser = argparse.ArgumentParser(description='Week summary') parser.add_argument('-start', dest='startdate', metavar='startdate', type=str, help='start date of the commodity') parser.add_argument('-en...
7325b586cead1ceb926de3e53e893eb83cc553db
660,345
def tokenise_text_col(df, text_col="text", suffix="_tokens", return_col_name = False): """ wrapper function for a list comprehenshion that tokenises a text column in df, returning df with a new column containing tokenised text Args: df: dataframe with text data text_col: column with tex...
4d9ce6c6b30e399dce6fd191bc337bfae4e5fc4a
660,346
def generate_summary_files(options, results_filenames, contig_lengths, output_dir): """ Generate the summary files from the individual error files. Args: options: Command line options. results_filenames: Filename of the flagged BED files. contig_lengths: Lengths of contigs. outp...
f43bdd254c118652cd472c8267aed18ade088573
660,347
import requests def download_file(url: str, prefix=""): """Download file by streaming and writing to file. Args: url: download url. prefix: prefix for output file. """ local_filename = url.split("/")[-1] with requests.get(url, stream=True) as r: r.raise_for_status() ...
7485b6d94415f986c63635bf8de0d71eb4577567
660,348
import numpy def is_orthogonal_nifti(nifti_image): """ Validate that volume is orthonormal :param dicoms: check that we have a volume without skewing """ affine = nifti_image.affine transformed_x = numpy.transpose(numpy.dot(affine, [[1], [0], [0], [0]]))[0][:3] transformed_y = numpy.tran...
da7d6250dd5416b43448defe97b6d29be95dc073
660,351
import fnmatch def getLabels(source, path): """Get all labels for given path :param source: Labels definition :type path: dict :param path: File full path :type path: string :return: Labels :rtype: list[string] """ result = [] for label, patterns in source.items(): ...
0310e38b185016f781ff2a958f4e6bbd82d86d39
660,352
def pack_stringlist(stringlist): """formats a stringlist to pass on command-line""" if stringlist is None or stringlist == '': return None if isinstance(stringlist,list): stringlist = '__delim__'.join(stringlist) return "'" + stringlist.replace("'","__squote__") + "'"
dbd3e1986d49417b373d045c343e2abced8ff6d8
660,353
def S(i): """Probably the ceilling of log_2 of i, but allways >= 2.""" j = 2 while j * j < i: j += 1 return j
2d30288d6782d75cac48a6f9a2f0d1ab4791a4c6
660,354
def stream_element_handler(element_name, usage_restriction = None): """Method decorator generator for decorating stream element handler methods in `StreamFeatureHandler` subclasses. :Parameters: - `element_name`: stream element QName - `usage_restriction`: optional usage restriction: "initi...
3e424c67c0839a1b3d4beccbf546b8b6d4b6ba33
660,355
def get_stacking_index(display, window): """ :type display: Display :type window: Window :rtype: int """ try: index = display.screen().root.query_tree().children.index(window) except ValueError or RuntimeError: index = None return index
f882e09f8777718b01793d592766d19cce4f86cb
660,356
def radius_to_replicas(atoms, min_nb_atoms, radius): """Calculate the replication that gives a supercell 'naively' as cubic as possible to the required `radius`. It approaches `radius` from below. The algorithm calculates how many cells can be fit within the specified radius for each dimension. For i...
49bb1875bcc86cbe54832997174d4414e6f1412f
660,357
def get_device_state(module, resp, device_id): """Get the current state and device type from response.""" current_state, device_type, invalid_device = None, None, True for device in resp['report_list']: if device['Id'] == int(device_id): current_state = device.get('PowerState', None) ...
2aa94ac5ac2e76162a0c6e0147f69b8e6a99480c
660,358
def normalize_host(host): """Normalize a host string.""" return host.lower()
f533fae1c740c9ce54e53d10a82f24ddd2f2da2f
660,359
import json from pathlib import Path def load_test_data(filename: str) -> list: """Utility function to load JSON files from 'test_data'""" json_file_path = ( Path(__file__).parent.joinpath("test_data").joinpath(filename).resolve() ) if not json_file_path.exists(): raise RuntimeError(f...
2e2cf2c43212136007132311087f9e5bfdbc0679
660,360
import torch def stack_pad_tensors(tensors, lens=None, ns=None, pad=0): """N x [B_i, T, ...]""" if ns is None: ns = [t.size(0) for t in tensors] if lens is None: lens = [t.size(1) for t in tensors] max_len = max(lens) bs = sum(ns) hid_dims = tensors[0].size()[2:] dtype = te...
82eed85b6bb54e62a9bb8b6921b53891e2bb6ce3
660,361
import os def ui_to_py(ui_file: str) -> str: """ Use pyuic6 to convert ui template into py file :param str ui_file: input ui template file :return str: converted python template """ return os.popen(f"pyuic6 {ui_file}").read()
b45a3dcf2c0c7778733e7b39a6f50cdb5a42bafc
660,362
def get_selec(tab, selec_tab, name_selec='name', thresh_selec='thresh', op_selec='op', type_selec='type', sel_tag_col='sel'): """ fonction to set a select flag (column) to tab data Parameters --------------- tab: astropy table data to process selec_tab: astropy table tab of selecti...
169db78e0d32b549573cc8642fa22dbecb8c1322
660,364
def get_pairs(word): """ Return set of symbol pairs in a word. Word is represented as tuple of symbols (symbols being variable-length strings). """ pairs = set() prev_char = word[0] for char in word[1:]: pairs.add((prev_char, char)) prev_char = char pairs = set(pairs) ...
a2e88c2c9a74bb6715a99e99813cfde7cea8789d
660,365
def topological_sort(items, partial_order): """Perform topological sort. items is a list of items to be sorted. partial_order is a list of pairs. If pair (a,b) is in it, it means that item a should appear before item b. Returns a list of the items in one of the possible orders, or None ...
37ce78cff728c37bc27ee42e2b8f12156ba5e951
660,366
def disable(actor, cmd, user, alertkey=None, severity='info'): """disable an alert""" # if isinstance(alertkey, unicode): # alertkey = str(alertkey) keyword = actor.monitoring[alertkey] keyword.disable(user) actor.broadcastActive() actor.broadcastDisabled() actor.broadcastAll() ...
012a71a7263299f1881fbbf5155acc242da72d0a
660,367
def max_profit_rohit(arr: list) -> int: """ Time Complexity: O(n*n) Space Complexity: O(1) """ def transaction(start: int, end: int) -> int: """ Max profit given atmost 1 transaction. Time Complexity: O(n) """ if start >= end: return 0 bu...
778508990a40b6b1d5a531a2cebb5c15d6685cc9
660,368
import copy def truncate(obj, allowedkeys): """ Removes all keys not in the allowed list in the tree. """ if isinstance(obj, list): return [truncate(val, allowedkeys) for val in obj] elif isinstance(obj, dict): new_obj = copy.copy(obj) for key in obj: if not (key in all...
a6f4535900d4466fab9a4e800691b3e1d4854c24
660,369
import os def load_typos_belinkov_bisk(file_name): """ Loads and returns a typos dictionary from a given file Credit: https://github.com/ybisk/charNMT-noise/blob/master/scrambler.py """ file_path = os.path.join(f"resources/typos/", f"{file_name}") typos = {} for line in open(file_pat...
5e3122ffb6c0bebc3e628ba86e7ca03221fa8f8f
660,370
def make_pure_python(obj): """ Take dict object which can include either dict or numpy scalars or Python scalars, and convert to pure Python. """ if isinstance(obj, dict): for key, val in obj.items(): obj[key] = make_pure_python(val) return obj elif hasattr(obj, 'item...
740c4d8c3bbc9a5f9a460079dd07b1d1581e8010
660,371
def normalize_reference_dict(ref_id, fld): """Normalize Reference for dict.""" return fld.to_python(ref_id.get("id") or ref_id["_id"])
b28fcfc1869292aa66e6f6cfbafeb272a2a0205e
660,372
def app_config(app_config): """Customize application configuration.""" app_config[ 'FILES_REST_STORAGE_FACTORY'] = 'invenio_s3.s3fs_storage_factory' app_config['S3_ENDPOINT_URL'] = None app_config['S3_ACCESS_KEY_ID'] = 'test' app_config['S3_SECRECT_ACCESS_KEY'] = 'test' return app_config
af0054a6242b6ff065e726fa59813a657f5c6552
660,373
def filter_images(piclists): """ Filter the image lists to remove the "False" and "path=None" items :param piclists: A list of list of Picture_infos namedtuple :return: The same lists, but filtered """ for i, piclist in enumerate(piclists): piclist = [j for j in piclist if type(j) != boo...
2701ff1122878e7db50a47fc54de7b8fba816e92
660,374
from pathlib import Path def get_path_as_str(path: Path) -> str: """ Get the given path as a string. :param path: a Path :return: a str """ return str(path)
632188289c8f3bd679ea7d18feb69edc9f24d5cd
660,376
from typing import Dict def unchanged(dico: Dict) -> bool: """If no sentences (longer than the cutoff of 5 tokens) were added or removed, consider the article unchanged.""" return True if len(dico['add']) == len(dico['rem']) == 0 else False
63de92aabcc443cda12189acaa88b16d523ff427
660,377
def _build_name_index_tuples(name, index_max): """return list of tuples [(N, 'nameN')] of the size indexMax""" def build_name(tup): return tup[1] + str(tup[0]) names = index_max * [name] names = map(build_name, enumerate(names)) return list(enumerate(names))
4d8b5b9b8ca49d0c4bc2a51abc07da0fc4b1cc16
660,378
def downsample(screen, subsample): """Factors a :func:`render`'d screen tensor along its final width dimension, returning something with shape (..., width/subsample, subsample). Typically you chase this call by aggregating over the trailing dimension in some way; either mean or min or max or ``[.....
9fb7aef25a60416193d226bd77ca52ca27ecb795
660,379
import time def slow_event(case_name, s): """ Take care of things that are slow! :param case_name: case name :param s: Some of the parameters :return: """ print(f"{case_name} running sleep {s}s") time.sleep(s) return s + 1
7eabf0b04bb68541cb655cbf7c41ef1fb74d007b
660,381
import codecs import random def create_questions(src, index1=0, index2=1, combinate=5): """ Creates single questions from given source. :param src: source file to load words from :param index1: index of first word in a line to focus on :param index2: index of second word in a line to focus on ...
dd80a247454aecc9ee5a4b65d8317bd060555a18
660,382
from string import punctuation from unicodedata import category, normalize def standardize(ds): """Remove interpunctuation and whitespaces from a string.""" ss = ''.join(s for s in normalize('NFD', ''.join(ds.split())) if category(s) != 'Mn') manually = (('“', '"'), ('”', '"'), ("(TM)", "...
3eca58c98a8755985c9d39edba631c62654c86d6
660,383
import os import re def crawl(directory): """ Parse a directory of HTML pages and check for links to other pages. Return a dictionary where each key is a page, and values are a list of all other pages in the corpus that are linked to by the page. """ pages = dict() # Extract all links fro...
acfb204874275f25501630a52d2273324a2434b7
660,384
import re def transform_kernel_string(k): """This function transforms a kernel string to make it compatible with Python's .format() syntax. Kernels are C code. The syntax to replace strings using Python's .format() is the same as the C syntax to declare scope. To write proper C code and avoid {{ // sc...
d774e4ab668967eaf0565cdeafecd8398f9c4fc9
660,385
from pathlib import Path def ed_append(filename, string): """ appends string to the end of the file. If the file does not exist, a new file is created with the given file name. The function returns the number of characters written to the file. :param filename: file to be manipulated :param str...
da9f9964794c55483ee0a549e810d9df9bef6567
660,387
import os import subprocess import re def get_repository() -> str: """ Get the current GitHub repository like `organization/project`. """ if "GITHUB_REPOSITORY" in os.environ: return os.environ["GITHUB_REPOSITORY"] remote_lines = subprocess.check_output(["git", "remote", "--verbose"]).de...
59e0fdd290f89571574dd1a33931de815729e9da
660,388
def sqlite3_call(database, query): """ Differentiate between SELECT and INSERT, UPDATE, DELETE (hack -> wont work with sub-selects in e.g. update) """ if query == "" or query is None: return "Warning: Empty query string!" elif query and query.lower().find("select") >= 0: return d...
0ff33e1e2cb9807be8326b1792d71149bca51664
660,389
def dotget(obj, expr, optional=False): """`.`으로 연결된 객체접근 표현식을 parsing, 반복하여 반환하는 유틸리티 함수입니다. Args: expr (str): 문자열 형태의 연속된 객체접근 표현식입니다. optional (bool, optional): 자바스크립트의 `optional chaining`과 같이, 해당 속성이 객체에 존재하지 않을 경우에도 에러를 발생시키지 않습니다. Returns: `eval(expr)`을 실행한 것과 같은 결...
5006f2647e4c822b182d1dbaeadb5632799d4fcd
660,390
def get_string_vector(tixi, xpath): """ Get a vector (of string) at given CPACS xpath Function 'get_string_vector' will get a vector (composed by string) at the given XPath, if the node does not exist, an error will be raised. Args: tixi (handle): Tixi handle xpath (str): XPath of the ...
4da8b017a24f12b4f2017911ceee3bc9764946c3
660,391
import os import time def get_save_image_name(org_im, org_im_path, output_dir): """ Get save image name from source image path. """ # name prefix of original image org_im_name = os.path.split(org_im_path)[-1] im_prefix = os.path.splitext(org_im_name)[0] # extension ext = '.jpg' # s...
12ac5915f56e7169bcb603c0063b47bd83586d13
660,392
import re def filter_data_genes(counts, filter_genes): """ Filter the input matrix of counts to keep only the genes given as input. :param counts: matrix of counts (genes as columns) :param filter_genes: list of genes to keep :return: the filtered matrix of counts """ genes_to_keep = l...
2d30aacb40e12d9dd7d3f7d1bcf7b078c9a8d6fb
660,393
def mark_counter(marks, min, max): """ mark_counter (marks, min, max) - takes in a list of marks and returns a list with the number of marks in between the range(inclusive) represented by a '*' """ counter = 0 for mark in marks: if min <= mark <= max: counter += 1 return ...
ce4fd64c9f3871390dc531d3d37a5f08fa5ebd6c
660,394