content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import torch def AverageProportion( delays, src_lens, tgt_lens, ref_len=None, target_padding_mask=None): """ Function to calculate Average Proportion from Can neural machine translation do simultaneous translation? (https://arxiv.org/abs/1606.02012) Delays are monotonic steps, range from 1 to ...
8653f84c4c3e5bd53a06bc1c85a05af9139b69cf
647,213
def parse_max_speed(xmldoc): """parses the vehicle speed distribution from the VISSIM data""" speed_d = dict() for max_speed in xmldoc.getElementsByTagName('desSpeedDistribution'): # get mean speed num = 0. sum_val = 0. data_points = max_speed.getElementsByTagName( ...
8c512751088bc8a87fe5e9ae92cd6b5ab31aaf0d
647,215
def convert_edif_orientation_to_hv(prop_orientation, shape_orientation): """ Determine the text orientation, H or V, from shape and property text orientation """ orientation = "H" horizontal_set = {'R0', 'R180', 'MY', 'MX'} vertical_set = {'R90', 'R270', 'MYR90', 'MXR90'} if prop_orient...
4887ded2031cba5169a9ac7866aca5a4fc2189b2
647,216
def _rotate_right(num: int, shift: int, size: int = 32): """Rotate an integer right.""" return (num >> shift) | (num << size - shift)
e59dfbdb11da107ae31e5940854ed3846b35a991
647,217
import sys def exceptional(func,alt_return=None,alt_exceptions=(Exception,),final=None,catch=None): """turns exceptions into alternative return value""" def _exceptional(*args,**kwargs): try: try: return func(*args,**kwargs) except alt_exceptions: return alt_ret...
63fd62746b96408e366a966ee69230b9558c2461
647,218
def prev(address, step=2): """Take vPC two bytes back, wrap around if needed to stay on page""" return (address & 0xff00) | ((address-step) & 0x00ff)
ed666ecb0728d6375f6d81c926500780e78d3722
647,219
def calc_exponentiation(num1, num2): """Returns num1 to the power of num2.""" result = None return result
6c73bae970f79a82a50d84c918314cb5dfb9a67a
647,220
def get_system_columns(columns): """Filters leaderboard columns to get the system column names. Args: columns(iterable): Iterable of leaderboard column names. Returns: list: A list of channel system names. """ excluded_prefices = ['channel_', 'parameter_', 'property_'] return [...
024dcdcd9c6327d3ac28a3b1c67bf7daa4953b99
647,222
def notas(*nota, sit=False): """ --> Função para analisar notas e situação de varios alunos. :param nota: Recebe varias notas a serem analisadas. :param sit: Opcional, mostra a situação dos alunos. :return: Mostra o dicionario com todas informações. """ alunos = dict() alunos['Total'] = ...
ce12904188fe248e9d1e1d468e38f27345ff19db
647,223
def wrap_functional_unit(dct): """Transform functional units for effective logging. Turns ``Activity`` objects into their keys.""" data = [] for key, amount in dct.items(): if isinstance(key, int): data.append({"id": key, "amount": amount}) else: try: ...
5f7b4e0f5e0e5d5c8d52395c629dab8edc02402f
647,224
def get_stolen_bits(num, bits_required): """ Returns binary representation of given number in given length :param num: Number to be converted :param bits_required: Length of Number of bits required :return: Binary string of given number """ binary = "{0:b}".format(int(num)) prefix = bits...
1488ddb5d3973583e6a811e661b5f6a6224cb94b
647,225
def _intersection_homogenous(homog_line_0, homog_line_1): """Find point of intersection of two lines in homogenous coordinates""" # NB: renamed from '_intersection' eps = 1e-13 a,b,c=homog_line_0 u,v,w=homog_line_1 D=float(b*u-v*a) if abs(D)<eps: # parallel lines return None,...
b529411a69870beb3128aebb151d8d3b13de5b61
647,226
def _len_title(content_list): """Length of titles. Look up each column string`s length. Args: contents (list): Print target. Returns: str: Table string. """ len_dict = {} for detail_dict in content_list: for key, value in detail_dict.items(): item_len...
530f8594733e2a4cec9a925405f82368ee576e33
647,227
from pathlib import Path from typing import Optional from typing import List import sys def collect_plugins( path: Path, package: Optional[str] = None, add_to_path: bool = False ) -> List[str]: """Collects the plugins from the given location. This function collects the modules and packages available in c...
5b8332fe9ec00b4f729ad508937abad584a4480d
647,230
def toggleLock(func): """ Decorator method used to toggle the lock state on a plug. :type func: function :rtype: function """ # Define wrapper function # def wrapper(*args, **kwargs): # Check number of arguments # numArgs = len(args) if numArgs == 2: ...
7bb3f4e56ca5e92aeafe6259847be11151368d2a
647,231
def date_to_weekday(num): """ Accpets datetime.date() object and turn it to week day. Precondition: Week starts with saturday. """ days = [ 'السبت', 'الحد', 'الاتنين', 'التلات', 'الأربع', 'الخميس', 'الجمعة' ] return days[num]
5fb8f23b0ad6710df6382c9449c31c18c606725f
647,232
from typing import Counter def make_gene_usage_counter(df, cols = ['v_b_gene', 'j_b_gene']): """ >>> """ gene_usage_list= df[cols].to_dict('split')['data'] gene_usage_list = [(x[0],x[1]) for x in gene_usage_list] gene_usage_counter = Counter(gene_usage_list ) return(gene_usage_counter)
b3e77094c4d97d9645adf44e71620715ced4c28a
647,233
def singleton(class_): """ Pros Decorators are additive in a way that is often more intuitive than multiple inheritance. Cons While objects created using MyClass() would be true singleton objects, MyClass itself is a function, not a class, so you cannot call class methods from ...
f1971e865ddcd75af7c40dccee500c0baac83c31
647,234
import time def wait_pipe_len(sock, expected, timeout=10): """ Wait up to ``timeout`` seconds for the length of sock.pipes to become ``expected`` value. This prevents hardcoding sleep times, which should be pretty small for local development but potentially pretty large for CI runs. """ ...
28d1b6e86f4ec5fd6f62e9e5e493df4badf64d24
647,235
import subprocess import os def extract_audio(video_file, target_name): """ parameters: video_file : file to extract wav from extract audio to wav and return the name of the extracted audio """ try: os.remove(target_name) except: pass base = os.path.basename(video_file) file_name = os.path.splitex...
a25a763145676f46c521c410a6661be0cbcc562c
647,237
def encode_into_magenta(f, encoder): """encode midi into 1d magenta format. f is a path""" return encoder.encode(f)
564d17b5d15a56b3e43a3d433e30293dfddde4e0
647,238
def clean_data(df): """ This function cleans data from the provided dataframe Parameters: df is the dataframe with the messages and categories Return: df is the dataframe already clean with no duplicates """ print("df shape=",df.shape) duplicate = df[df.duplicated()] print("df...
7becbeb82c79ac0319b1dbacc65afcca0a1f7359
647,239
def _get_subdir_list(dir_name): """ Get a list of subdirectories. """ subdir_list = [] if dir_name: dirlink = '' dir_items = dir_name.split('/') dir_items.pop() for dirname in dir_items: dirlink = dirlink + dirname + '/' subdir_list.append...
104f61dde8c05bc60dfdcc7c38dc7d9e9755c9a3
647,240
import re def _underscore(string): """ Convert a string from CamelCase to underscored """ string = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1_\2', string) return re.sub(r'([a-z0-9])([A-Z])', r'\1_\2', string).lower()
0a1e81dc2943b9657db355ca328fdee5d8a49a47
647,241
def double(number: float) -> float: """ Here, we say that 'number' should be a float and the double() function should return a float. Python treats these annotations as hints, they are not enforced at runtime """ return 2 * number
5f65f49ba4a2616824275af96050d8abe3ab3795
647,242
def is_rate_limit_error_message(message): """Check if the supplied error message belongs to a rate limit error.""" return isinstance(message, list) \ and len(message) > 0 \ and 'code' in message[0] \ and message[0]['code'] == 88
38db5d4f61d914339190bb78a13c58e0577f4ef7
647,243
import json def _read_missing_references_json(json_path): """ Convert from the JSON file to the form used internally by this extension. The JSON file is stored as ``{domain_type: {target: [locations,]}}`` since JSON can't store dictionary keys which are tuples. We convert this back to ``{(dom...
ae9a8dd23769b0e704fa3d1e9b69cf27817c6d06
647,244
import socket import struct def inet_nitoa(i): """Like inet_ntoa but expects an integer.""" return socket.inet_ntoa(struct.pack('>I', i))
09ce3d3ccbc396b94f37de5bce9d2fb5f3e30899
647,245
def RemoveExonPermutationsFromFront(segments): """remove exon permutations from the front. Only permutations are removed, that are completely out of sync with query. Overlapping segments are retained, as they might correspond to conflicting starting points and both should be checked by genewise. ...
1cf9dfcad43186a762559baa13091340d69960a4
647,246
import torch def get_soft_label(input_tensor, num_class, data_type = 'float'): """ convert a label tensor to one-hot soft label input_tensor: tensor with shae [B, 1] output_tensor: shape [B, num_class] """ tensor_list = [] for i in range(num_class): temp_prob = input_t...
13cace33535f1d594ea4fa3d0b9408ffe69671cb
647,248
import random def random_card(cards, remove=False): """ Returns a random card from the Stack. If ``remove=True``, it will also remove the card from the deck. :arg bool remove: Whether or not to remove the card from the deck. :returns: A random Card object, from the Stack. ""...
9fc5bac3a16beb5a693c4fa47c7ab2e2e2735e71
647,249
def needs_rename(string): """Search input string for illegal characters. If found, return True, list of characters found, cleaned name. If not, return False and two empty strings""" bad_characters = ["&", "$", "@", "=", ";", "+", ",", "?", "\\", "{", "^", "}", "%", "`", "]", "\"", ">", "[", "~", ...
1f49a8295d482828a4724c14b9af1579ea9e7d87
647,250
def big_diff(*args): """ param: *args (this is a list of arguments, it can be unknown which is why you use *args purpose: the purpose of this function is to find the highest and lowest value in an array of integers and subtract the differece between them return highest_value - lowest_value """ h...
a4dd7593c834d243276ea6c932a0ff0f1f4aa9a8
647,251
def listFile(*ignored_args, **ignored_kwargs): """No-op action callable that ignores arguments and returns (True, []). """ return True, [] # match only based on file names, which was done by caller
bbba2ccb4031ad3e74d595a20d43fee0eebe3da7
647,252
def repository(app): """GitHub repository.""" return app.repository.html_url
3a757deddcbaf910659c9e31594f42258134a3ad
647,253
def seasonFromDate(date): """ Returns the value of season from month and day data of the timestamp Parameters ---------- date : String Timestamp or date string in format of YYYY-MM-DD or followed by timestamp Returns ------- season : STRING Season corresponding to the d...
0d61a3951c5b997f79c75a11172cd5e3f913a560
647,254
from typing import List def parse_to_lines(content: str) -> List[str]: """Metin içerisindeki satırların listesini oluşturur Arguments: content {str} -- Metin Returns: List[str] -- Satır listesi Examles: >>> parse_to_lines('Selam\\nNaber\\nNasılsın') ['Selam', 'Naber'...
4c44803f451699f7142b7eccc455df2316ffa2e7
647,255
def update_state(reactants, products, state, rxn_ind, reverse): """ Updating the system state based on chosen reaction, during kMC simulation. Args: reactants: (n_rxns x 2) array, each row containing reactant mol_index of forward reaction products: (n_rxns x 2) array, each row containing pr...
7b8ce0daef2e43418dc43e9e37252024c6314bb7
647,256
def get_param_value(mode, memory, ptr): """Returns the value of the parameter at memory[ptr] based on the mode""" # position mode if mode == 0: return memory[memory[ptr]] # immediate mode elif mode == 1: return memory[ptr] else: raise Exception
3472207301a1c32cce2b8bfeaa0ecef44e85670d
647,257
import os def out_path(tmpdir): """ A path for an output .tif file. """ return os.path.join(str(tmpdir), "out.tif")
3e13414fa8312ac6e256dde2eb9b15d9a5c55dc0
647,258
def calc_tstart(num_bins, binsize, t_stop): """ Calculates the start point from given parameter. Calculates the start point :attr:`t_start` from the three parameter :attr:`t_stop`, :attr:`num_bins` and :attr`binsize`. Parameters ---------- num_bins: int Number of bins binsize: ...
fb1fa026bbfb3978bb0f4aaeeb3a93d3bc471fbd
647,259
def normalize_to_unicode(value): """ string convert to unicode """ if hasattr(value, "decode") and not isinstance(value, str): return value.decode("utf-8") return value
ab7b60064d7ff66afe3f655f838b006d15752277
647,260
def volCube(edge: float) -> float: """Finds volume of a cube""" volume: float = edge ** 3 return volume
a4f73fd9bc35a2f01148de463f59cd8bfc46dc16
647,261
import torch def pad_list(data): """ Pads a list :param data: list of things, first dimension is the length presumably :return: """ lens = [len(x) for x in data] data_pad = torch.zeros(max(lens), len(lens), *data[0].size()[1:]).long() for i, (x, l) in enumerate(zip(data, lens)): ...
52baa509a4e8759903dae6b35902a66ba9a30f7a
647,262
import requests def get_rates(url): """Method to get currency rates and returns status of request(boolean) and request response in JSON format. @:param str url: Exchange site url @:return boolean: True for successful response, else False. @:return dict: Response in case of success else empty dict...
5706d6dd6fd96d9f364c57b69a29e6c7dde791af
647,263
def _guess_desc(fname): """Attempts to guess the menu entry description from the function name.""" return fname.title().replace("_", " ")
30d346a77e680fb88b8dc80fdb6e465f26c52caa
647,264
def make_actual_args(members): """Comma-separated name list used in actual arguments a, b, c """ return ", ".join(name for _, name in members)
4fb0003a21f7b041ac4b5b30ac94ce044a3b2368
647,266
import subprocess def get_snps(region, snp_file): """ Take a region string and a tabix'ed snp file, return a list of snps which are lists of tab delimited information from the snp file. """ # extract snps using tabix, in tab separated lines snp_temp = subprocess.check_output(["tabix", snp_file, r...
c832f14204373e724fe1dbdcdeb7e210ec635dab
647,267
def update_parser(parser): """Parse the arguments from the CLI and update the parser.""" parser.add_argument( '--prepro_step', type=str, default='preprocessing', #'slicing', 'preprocessing' help='To execute a preprocessing method') #this is for allfeatures_preprocessi...
5cd74d2e50801db7ea7d27a37bca3c224a2b039a
647,268
import json def readJSONDict(filename): """ Retrieve stored dict from JSON file """ jsondict = {} with open(filename, 'rb') as infile: jsondata = infile.read() jsondict = json.loads(jsondata) return jsondict
7ce79e349538ff23409c5cebcce7317a1e2fe3ac
647,269
def OUTPUT_SOLVER(): """Return list of solved Sudoku boards for Solver class tests ./src/solver.py/Solver:class""" return { "nextpos": (0, 2), "exists": { "success": (), "row0": (0, 8), "column0": (2, 2), "3*3area0": (2, 1), }, "sol...
11ae7e81633eb81ea0faabe12436922b3a7d5dac
647,270
def balanced_parenthesis(string2check: str) -> bool: """Check for balanced parenthesis. Used for syntax check.""" pairs = {"(": ")"} match_chk = [] for char in string2check: if char == "(": match_chk.append(char) elif match_chk and char == pairs[match_chk[-1]]: ma...
6a7e2cdb2d1157cfe8966ec3e8a07b09c5c504cd
647,271
def get_weather_from_google(location_id, hl = ''): """Fetches weather report from Google. No longer functional, since Google discontinued their Weather API as of Sep 2012. Method retained for backwards compatibility. Returns: weather_data: a dictionary containing only the key 'error' """ ...
8cd4414e07a20f292d51f9011b61bd2c37c16697
647,272
def is_member_of_group(status: str): """check, whether a given status indicates group-association Args: status (str): status to check Returns: bool: is a person with status in this group? """ possibleStati = ['creator', 'administrator', 'member', 'restricted'] return status in...
2122e54557672c95cafea7fe3aa12e839241b4ae
647,274
import string def remove_digits(s): """ using technique from http://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python """ return s.translate({ord(c): None for c in string.digits})
7b3eb9a53b2ef9d342e3e62128a5b67eb36d1262
647,275
def yaml_transformer(value: str) -> str: """A YAML transformer for Ruamel that places a blank line between each top level section.""" lines = value.splitlines() output = [] for line_no, line in enumerate(lines): if line_no and not line.startswith(' '): output.append('') out...
b8aa628f78607fe837083421e068b801f4689648
647,276
from typing import Dict def __attempt_replace(line_args: str, labels_locs: Dict[str, int]) -> str: """ Atttempt to replace a label with its memory address. :param line_args: Part of the line including the arguments. :param labels_locs: Labels and their memory addresses. :return: Line with the labe...
4d08c304792f393220d7aa7259b1d2cffb7453aa
647,277
import sys import base64 def base64ify(bytes_or_str): """Helper method to perform base64 encoding across Python 2.7 and Python 3.X :param bytes_or_str: :type bytes_or_str: :return: :rtype: """ if sys.version_info[0] >= 3 and isinstance(bytes_or_str, str): input_bytes = bytes_or_st...
8cd1fe68b1e6a9e629562b81c3f9c524b09c89e0
647,278
def agg_loss(method): """ Extract aggregate loss from full name of method. Args: method (str): full name of method Returns: str: aggregate loss """ if method[:6] == "hinge_": return method[6:] if method[:9] == "logistic_": return method[9:] if method[:7]...
a6d8c0c9162788db02cee60aaaee8361595aeaeb
647,279
def nullility_corr(data, method="pearson"): """Calculates the nullility correlation between features in a DataFrame. Leverages pandas method to calculate correlation of nullility. Note that this method drops NA values to compute correlation. It also employs `check_missingness` decorator to ensure DataF...
17dcdaa60d0dd07c404e867f1231ffa61126592b
647,280
import re def clean_spaces(text: str) -> str: """Removes any consecutive white spaces in the text, as well as preceding and trailing whitespaces. Arguments: text: The text to be filtered. Returns: The filtered text. """ return re.sub( " +", " ", text )...
fd6b826eed4737c87c9c0cec36d33d602056c8af
647,281
def get_active_branch(repo): """Returns the active branch of the given local repository. Args: repo(git.Repo): Git Repo instance Returns: str: The name of the active branch. """ return repo.active_branch.name
cb82cbc988d34766050091c9b34fa73ff7506b6c
647,283
def df_set_diag(df, val, copy=True): """ Sets the diagonal of a dataframe to a value. Diagonal in this case is anything where row label == column label. :param df: pd.DataFrame DataFrame to modify :param val: numeric Value to insert into any cells where row label == column label :pa...
c8dc669fc23b6e38bcb552a72e4fbe418528a242
647,284
def force_zero(data, index, column): """ Parameters ---------- data index column Returns ------- """ data.loc[index, column] = "0" return data
c743b588a455cdcad8e554f57d0c3efec4295dc2
647,285
def get_matching(variables, strict=True, single=True, **criteria): """Given a set of criteria, find the matching variables(s). Args: variables (iterable of Variable): Variables to match against. strict (bool): If True, require that at least one match is found (see `single`). ...
f98683308726ef96001c629d8020c4cb730f3bff
647,286
import pickle def load_pickle(file_path: str, verbose: int = 0): """[summary] :param file_path: [description] :type file_path: str :return: [description] :rtype: [type] """ result = None try: result = pickle.load(open(file_path, "rb")) if verbose > 0: print...
2a75e688eed601f50106a95d0ed10e4bfdd4b319
647,287
def normalized_intersection(bbox1, bbox2): """ Intersection that is normalized with respect to the first bbox. :param bbox1: bounding boxes in the format [left, top, right, bottom] and shape [4]; dtype has to be np.ndarray or list :param bbox2: bounding boxes in the format [left, top, right, bot...
2b1b1db81c0b7a97aa3e0be74a60c7b87fd79f7d
647,288
def merge_properties(prop_sets): """ Perform an inner join on a list of dictionaries """ inner_keys = set.intersection(*[set(p.keys()) for p in prop_sets]) data = {} for key in inner_keys: data[key] = [p[key] for p in prop_sets] return data
0c49411680bc3c79aaa83b40aa7696572bac6b26
647,289
import typing def t3(a: typing.List[str]) -> str: """ This is a pedagogical demo that happens to do a reduction step. Flyte is higher-order orchestration platform, not a map-reduce framework and is not meant to supplant Spark et. al. """ return ",".join(a)
10f40e64617b6fba29b6ed6359a4c7eecdaaaeb5
647,291
def deep_copy(to_copy, rows, cols): """Need i say? """ clean_mtx = [] for i in range(rows): row = [] for j in range(cols): row.append(to_copy[i][j]) clean_mtx.append(row) return clean_mtx
23d5dc25c35904b78211114c5722e6b6a1d2fc35
647,292
from pathlib import Path import os def absolute(path): """Make path into an absolute Path object.""" return Path(os.path.abspath(path))
6d24e8806013c499e23a3dba8bec2ef9cc15dbe9
647,293
def get_token_index(text, offset, tokens): """ >>> text = "A quick brownDasheyBhgx fox jump's over the lazy dog" >>> tokens = ['[CLS]', 'a', 'quick', 'brown', '##das', '##hey', '##bh', ... '##g', '##x', 'fox', 'jump', "'", 's', 'over', 'the', 'lazy', ... 'dog', '[SEP]'] >>> t...
d56aab443b631ae1c8a3eb1f7c6790d5bb77b57f
647,294
import re import os def ls_r(directory, pattern): """Returns a sorted list of all the files present in a diretory, relative to this directory. """ myreg = re.compile(pattern) res = list() for root, dirs, files in os.walk(directory): new_root = os.path.relpath(root, directory) i...
8d8f78f45aa4e95635e3195f1188dc68f3d938d7
647,295
def multiSlice(s, cutpoints): """ Helper function for allPartitions """ k = len(cutpoints) if k == 0: return [s] else: multislices = [s[:cutpoints[0]]] multislices.extend(s[cutpoints[i]:cutpoints[i+1]] for i in range(k-1)) multislices.append(s[cutpoints[k-1]:]) ...
2da2648af30830d5b0051cb1eefdcf465f33b380
647,296
import numpy def xyz_at_latitude(local_xyz, lat): """ Rotate local XYZ coordinates into celestial XYZ coordinates. These coordinate systems are very similar, with X pointing towards the geographical east in both cases. However, before the rotation Z points towards the zenith, whereas afterwards it...
e076eded852adaa8d5a4b0ad9b62af160804a9dc
647,297
def const(v): """Return the value passed.""" def f(data): return v return f
d0e65671da465dea52a36e64c724645398af8400
647,298
import torch def LSIGF_DB(h, S, x, b=None): """ LSIGF_DB(filter_taps, GSO, input, bias=None) Computes the output of a linear shift-invariant graph filter (graph convolution) on delayed input and then adds bias. Denote as G the number of input features, F the number of output features, ...
2126b5b9a291c07e2b10fcb8dd9029fe44fcd3b0
647,299
def get_allow_copy(item_container): """ """ return item_container.item.app.name != 'dmsEduFolder'
079c5fa601469bd8d0bd0c1b14b373759708012a
647,300
def pad(source: str, pad_len: int, align: str) -> str: """Return a padded string. :param source: The string to be padded. :param pad_len: The total length of the string to be returned. :param align: The alignment for the string. :return: The padded string. """ return "{s:{a}{n}}".format(s=s...
6f4b587e224cfeb33ca2aba3ef2c67ff8eb86d3b
647,301
import subprocess def check_freesurfer(): """ This function checks for the correct installation of freesurfer. It does so by calling 'freesurfer' to the main terminal and checking for errors. """ # Open stream and pass 'freesurfer' command check_stream = subprocess.Popen(['freesurfer'], sh...
1899295db103772135d05793db84f27f55f17b53
647,302
import os def load_bearer_token(): """BEARER_TOKEN is exported by .bashrc""" return os.getenv("BEARER_TOKEN")
acd03ad80e1578a99ba6500a60b0154fe9b38a53
647,303
import configparser def read_setup_cfg(fname="setup.cfg"): """ Read the setup.cfg file into a dictionary. """ config = configparser.ConfigParser() # Use read_file to get a FileNotFoundError if setup.cfg is missing. Using # read returns an empty config instead of raising an exception. with ...
312c300dcf09060d86a8ce8f2d09a30b594f230f
647,304
import ast def _convert_to_expression(node): """ convert ast node to ast.Expression if possible, None if not """ node = ast.fix_missing_locations(node) if isinstance(node, ast.Module): if len(node.body) != 1: return None if isinstance(node.body[0], ast.Expr): expr ...
a24c8c304b21d2a4f90e7946267620a853db1a4b
647,305
def form_auth_headers(client_id, access_token): """ Form headers for OAuth clients :param client_id: :param access_token: :return: """ headers = { 'client-id': client_id, 'Authorization': 'Bearer ' + access_token } return headers
292ec749c73ea4492fe0796c76a34fee5d17585d
647,306
import platform def get_os(): """ Get the operating system information for the machine running this script. """ curr_os = "linux" if "Linux" in platform.platform() else "win" return curr_os
6e23caa989f9e8ffb3b1be516d1d0ca51a1227da
647,307
def removeListDups(base_list,remove_list): """Remove items from one list from another Args: base_list (list): list to keep the non-duplicated values from remove_list (list): list of items to remove from base_list Returns: list : list of items in base_list NOT in remove_list """...
52a968f074aa961fe2206c81692206839004c7da
647,309
def transition_model(corpus, page, damping_factor): """ Return a probability distribution over which page to visit next, given a current page. With probability `damping_factor`, choose a link at random linked to by `page`. With probability `1 - damping_factor`, choose a link at random chosen fr...
d42ac7df77fba60c7e91a2ccc309401c76fbfb84
647,310
def get_region_solution_attribute(data, attribute, func, intervention) -> dict: """Get given solution attribute for all regions""" # All regions regions = data.get('NEMSPDCaseFile').get('NemSpdOutputs').get('RegionSolution') return {i['@RegionID']: func(i[attribute]) for i in regions if i['@Interventi...
bd1bd59ae7938ff7ede14e7e4953bbe180fb2aa5
647,311
def determiner_valeur_cartes(joueur, cartes_jouables, manche, premiere_carte, donnees): # Voir les rappels /!\ """Fonction donnant la valeur de cartes en prenant en compte le risque d'un joueur, une situation particuliere et des donnees recoltees""" if manche > 5: # Au cas ou on joue plus de 5 manches ...
85f122802ff14344f254d6b2517a229711149f3e
647,312
def test_cache_memoize_arg_normalization(cache): """ Test taht cache.memoize() normalizes argument ordering for positional and keyword arguments. """ @cache.memoize(typed=True) def func(a, b, c, d, **kargs): return (a, b, c, d) for args, kargs in ( ((1, 2, 3, 4), {"e": 5}),...
170069c8af7f9debe94029018f8df8bdaf31c01d
647,313
import platform import os import sys def get_config_home(): """Returns the directory used for application settings""" if platform.system() == 'Linux': try: return os.environ.get('XDG_CONFIG_HOME', None) or os.environ['HOME'] except KeyError: raise KeyError("Neither $XDG...
04cacc35ddc3a36e4ec5ba88ba185b95f12bef27
647,314
def to_integer(obj): """Converts `obj` to an integer. Args: obj (str|int|float): Object to convert. Returns: int: Converted integer or ``0`` if it can't be converted. Example: >>> to_integer(3.2) 3 >>> to_integer('3.2') 3 >>> to_integer('3.9') ...
04247b146a0d9d9c6fbdb89c9de06e162d37652b
647,315
import pickle import os def clf_size(classifier, file_name): """Records the classifier size""" p = pickle.dump(classifier, open(file_name, "wb")) file_size = os.path.getsize(file_name) return file_size
7428d80e9b7e595eee0b951fe3a16c9c7909f5fd
647,316
def get_clinvar_accession_from_clinvarset(elem): """ Gets the Clinvar accession from a ClinVarSet element :param elem: ClinVarSet Element :return: ClinVar Accession """ ## elem.xpath("//ClinVarAccession")[0].attrib['Acc'] ## this only works sometimes try: # return elem.xpath("//Clin...
bb6620caba7c089dbad35b1c0cc718c5ed39655f
647,317
def categorize_estimated_risk(df): """ :param df: dataframe with column 'estimated_risk' containing risk, possibly followed by digit for footnote original data may contain string 'None', different from python object None :return: mutated dataframe by trimming estimated_risk and converting fro...
00ad2dec661a8b08f7e06ef01a28168968a9f4de
647,319
import os import tempfile def get_data_dir() -> str: """Get the DeepChem data directory. Returns ------- str The default path to store DeepChem data. If you want to change this path, please set your own path to `DEEPCHEM_DATA_DIR` as an environment variable. """ if 'DEEPCHEM_DATA_DIR' in os.e...
9f80c3a4e177c483d9fb751fa1b522a733897f67
647,320
def children(node): """Returns a list containing all child nodes of a Traversable type node. Returns empty list when the node has no children. Used by BF/DF/Flat iterative tree visitor functions.""" try: k = node.getChildren() return k except: return []
e2d2fda08c4f22682f599b90a915e94a9e9e599d
647,321
import numpy as numpy def writeMeshMatlabFormat(mesh,meshFileBase): """ build array data structures for matlab finite element mesh representation and write to a file to view and play with in matlatb in matlab can then print mesh with pdemesh(p,e,t) where p is the vertex or point matrix...
67941bc01298de054922be87e90388670620be83
647,322
def _get_prefix(bot, m): """Gets the prefix for a given server""" prefixes = ['`'] channel = m.channel # Return normal prefix for private channel if not channel.is_private and bot.__dict__.setdefault('configurations', {}).get(channel.server.id, {}).get('prefix'): prefixes.append(bot.config...
6203f96443c58907740282b4d06dd3785185c36e
647,323
import re def multiline_replace(content: str) -> str: """multiline_replace deals with more complicated statements which possibly span multiple lines""" # fix bad proc formatting # see: proc.tcl regexp = re.compile( r"^\s*proc(\s|\\\n)*([a-zA-Z0-9-_]+)(\s|\\\n)*({([a-zA-Z0-9-_\\\n ]*)}){0,1}(\s...
a6d1df85c78b81c11093339bc331bee154bd5a2d
647,324