content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def shuffle(self, nums, n): """ :type nums: List[int] :type n: int :rtype: List[int] 81% faster 5% less mem """ shuffled = [None] * len(nums) for i in range(len(nums)): if(i % 2 == 0): shuffled[i] = nums[i/2] else: shuffled[i] = nums[n+i/2] ...
2dad9fea90e421870317f36aeaf3e691e42b3a9f
679,916
def intersection_list(a, b): """ 取交集,并按顺序返回。 :param a: :param b: :return: """ result_list = list(set(a).intersection(set(b))) result_list.sort(key=lambda i: int(i)) return result_list
dea3c32b6cbc325b2489cf5717029e8923b171eb
679,917
def timestampToSeconds(timestamp: str): """xx:xx -> minutes past 17:00""" if not timestamp: return None try: hour, minute = map(int, timestamp.split(":")) return int((hour - 17) * 60 + minute) except: return timestamp
f8d274c5c2fd9239fb9e5881a1b179c6e1971111
679,918
def _tanh_to_255(x): """ range [-1. 1] to range [0, 255] :param x: :return: """ return x * 127.5 + 127.5
ac7b9c6aea395bb2289077a9ea83df07370ee06b
679,919
def respond(text): """Creates a response in-channel.""" return { "response_type" : "in_channel", "text" : text }
48ab977d0492245ab4dea05f6b1a4ed801563aeb
679,920
def concatenate_list_into_string(alist): """ Given a list like alist = ["ada", "subtract", "divide", "multiply"] the aim is to concatentate the to have a string of the form: "adasubstractdividemultiply" :param alist: list [list of items] :return: str """ string = "" for item in a...
91f95ce6ca146db2a0af3daa41f2f9aebd2f4ff1
679,921
def split(s, sep=None, maxsplit=None): """对一个长字符串按特定子字符串进行分割 :param s: 原长字符串 :type s: str :example s: "a b c d e f" :param sep: 子字符串,为None时值为 " " :type sep: str :example sep: " " :param maxsplit: 分割次数,为None时代表全部分割 :type maxsplit: int :example maxsplit: 3 :rtype list :...
7184746e0ebb15ea1d235a4fe1067f28466e636d
679,922
def normalize_qa(qa, max_qa=None): """ Normalize quantitative anisotropy. Used mostly with GQI rather than GQI2. Parameters ---------- qa : array, shape (X, Y, Z, N) where N is the maximum number of peaks stored max_qa : float, maximum qa value. Usually found in the CSF (corti...
1330434a0a630634c5284920fa35c7518bc34937
679,923
def Zulu2PTY(datetime): """ Convert from Zulu to PTY date-time. Parameters: datetime [Series]: a series of date/times stored in nanoseconds integer format Return: A series of date/times in nanoseconds integer format in Panama city If it is 1:00 pm Zulu, it is 6:00 pm PTY time (D...
045cdaa61144e35e77477b82171871dba6c44a8d
679,924
import torch def seq_and_vec(x): """ seq shape: [None, seq_len, s_size], vec shape: [None, v_size] Concat vec seq_len times: [None, seq_len, s_size+v_size] """ seq, vec = x vec = torch.unsqueeze(vec, 1) vec = torch.zeros_like(seq[:, :, :1]) + vec return torch.cat([seq, vec], 2)
c47dde547e7aff17588b776e3bca3a16071f4496
679,925
def stop_filter(record): """ A filter function to stop iteration. """ if record["int"] == 789: raise StopIteration return record
c0da5e80e77d37ca465f2a1afe4c575a4c223e0c
679,926
def distributeN(comm,N): """ Distribute N consecutive things (rows of a matrix , blocks of a 1D array) as evenly as possible over a given communicator. Uneven workload (differs by 1 at most) is on the initial ranks. Parameters ---------- comm: MPI communicator N: int Total number ...
8d62837abc4dfb5122216bcb46b8f04c020129d4
679,928
def hex_to_udec(hex_str): """ Function returns decimal equivalent to hexadecimal value """ return int(hex_str, 16)
ef978bb3be7894c507fce8db966c0c5861a7d926
679,929
import requests def _get_etag(uri): """ Gets the LDP Etag for a resource if it exists """ # could put in cache here - but for now just issue a HEAD result = requests.head(uri) return result.headers.get('ETag')
5296a8be8434edd605337a776963473d8c5c0a98
679,930
def load_classes(excel_data, slot_count): """ Load classes for a given excel_data string, containing 3 columns on each line separated by tabs. Load the schedule to a global variable for later access. E.g: Classname1 <tab> ClassName2 <tab> ClassName3 Classname4 <tab> ClassName5 <tab> ClassN...
2bc65238581aad0a236414bc3cd2cfa718e7bc84
679,931
import os def generate_host(): """ Generate submarine host :return: submarine host """ submarine_server_dns_name = str(os.environ.get("SUBMARINE_SERVER_DNS_NAME")) submarine_server_port = str(os.environ.get("SUBMARINE_SERVER_PORT")) host = "http://" + submarine_server_dns_name + ":" + subm...
acc25c51974c90bf84660a782c6222115c3325bf
679,933
def jmp(cur_position, value_change): """Jump relatively from cur_position by value_change.""" return cur_position + value_change
a64a19c90dc28f0d28418304f264dce8ad1b40ed
679,934
import functools def make_step_decorator(context, instance, update_instance_progress): """Factory to create a decorator that records instance progress as a series of discrete steps. Each time the decorator is invoked we bump the total-step-count, so after:: @step def step1(): ...
e5d041c7b47bd6061f9462fd7678796a034d5896
679,935
def correction_factor(rt, lt, icr=None, ocr=None): """ Calculate the deadtime correction factor. Parameters: ----------- * rt = real time, time the detector was requested to count for * lt = live time, actual time the detector was active and processing counts * icr = true inpu...
1edc03c9c8bea0ddc23a34a5b5918a6d440df110
679,936
def normalize_key(key): """ Return tuple of (group, key) from key. """ if isinstance(key, str): group, _, key = key.partition(".") elif isinstance(key, tuple): group, key = key else: raise TypeError(f"invalid key type: {type(key).__class__}") return group, key or Non...
9ff1c16bbd79937b32425d2b07188469653b911f
679,937
import random def random_sign(number): """Multiply number on 1 or -1""" return number*random.choice([-1, 1])
cc1dc61be0bf7a336ce18784e89b7a2b2f26ca1d
679,938
import os import subprocess import sys def _parse_lsb_release_command(): """Parse the output of the lsb_release command. Returns: A dictionary containing release information. """ distro = {} with open(os.devnull, "w") as devnull: try: stdout = subprocess.check_output( ...
634f34f9a058b0f910c6428ec79e1e98b8989683
679,939
def get_eligible_users(elig_check, usernames, elig_type): """ Takes an eligibility checker object, and a list of usernames. Returns a dictionary with lists of eligible and ineligible invitees. """ eligible = [x for x in usernames if elig_check.determine_user_eligibility(x, elig_type)] return el...
416e33e8b2042903c93b73d1a9e3359c092f6dd9
679,940
def average_rewards(arr_rewards): """ Average list of rewards """ avg_rewards = [] for i in range(len(arr_rewards[0])): avg_rewards.append(0) for _, rewards in enumerate(arr_rewards): avg_rewards[i] += rewards[i] avg_rewards[i] /= len(arr_rewards) return avg_...
906e834623c011ae350c4e9e2277ced5c641abaf
679,941
from typing import Counter def part1(lines): """ >>> part1(load_example(__file__, '2a')) 12 """ count_two = 0 count_three = 0 for line in lines: m = Counter(line).values() if 2 in m: count_two += 1 if 3 in m: count_three += 1 return count...
781978e65786096e9aa267ed733025e5d8ba52b7
679,942
import os def get_filtered_patterns(storage, ignore_patterns=None, location=''): """ Return a filtered list of patterns that match the storage location. """ if ignore_patterns is None: ignore_patterns = [] storage_prefix = getattr(storage, 'prefix', None) or '' if location: rel...
f48cec66086b70d7df2877b6d955e4b633a6f671
679,943
import os import tempfile import time def make_lockfile(lockfile, block=False, maxtry=300, waittime=2): """ Make a lockfile with atomic linking. Parameters ---------- lockfile: `str` Name of lockfile to create block: `bool`, optional Block execution until lockfile is created? D...
8e76d770dbb9884300adb7daf403b97347375c77
679,944
def compute_all_relationships(scene_struct, eps=0.2): """ Computes relationships between all pairs of objects in the scene. Returns a dictionary mapping string relationship names to lists of lists of integers, where output[rel][i] gives a list of object indices that have the relationship rel with object i....
a51269fe271c6dbdc949f73ba992c9a3bea692d1
679,945
import os def remove_data(url): """ A function delete_data delete_data, removes the data if it is present locally. Inputs: url - a webpage to download the data Outputs: test - a statement to the action """ # get the file name filename = os.path.basename(url) if os.path.exists(file...
72b0cd815576fd3ac5b1098f024f839dc93eb1e1
679,947
import colorsys def hsl_to_rgb(h, s, l): """ Converts HSL to RGB. Parameters ---------- h: :class:`int` The hue value in the range ``[0, 360]``. s: :class:`float` The saturation value in the range ``[0, 1]``. l: :class:`float` The lightness value in the range ``[0,...
16d1d135744bf1b2c158f19a1981f1ee7fabfd97
679,948
def break_camel_case(s): """ s: string of characters written in camel case return: s split between uppercase """ s_characters = ([char for char in str(s)]) for i in range(len(s_characters) - 1): if s_characters[i+1] == s_characters[i+1].upper(): s_characters[i] = s_characters[i] + " " return ""...
b638739d3fae78ecf38c4348e5c25396f53766d2
679,949
def is_callback_valid(callback_data): """Checking callback validity""" if (callback_data == 'player_x') or (callback_data == 'player_o'): return True if (len(callback_data) == 1) and (callback_data.isdigit()) and \ (callback_data != '9'): return True return False
0d9ee8815bb06c42c55f790d4a4986a0550a2a0b
679,950
from typing import Dict def recount_map_sample_to_study(metadata_file: str) -> Dict[str, str]: """ Parse the recount3 metadata file and extract the sample to study mappings Arguments --------- metadata_file: The path to where the metadata is stored Returns ------- sample_to_study: A ...
500f101c658867328f59587d509819593b9fc32c
679,951
import os def _ParseFilesCfg(files_file): """Return the dictionary of archive file info read from the given file.""" if not os.path.exists(files_file): raise IOError('Files list does not exist (%s).' % files_file) exec_globals = {'__builtins__': None} exec(open(files_file).read(), exec_globals) return ...
87d0e02c25cea90f9c34105ba9c09b3b5a99874b
679,953
def jx_gene_overlap(junction, cds_tree, id_name_dict): """Check found junctions for coding region overlap Input: junction information: chromosome, left and right boundaries of the junction, and strand CDS tree containing coding regions, created by gtf_to_cds dictionary mappi...
81bea45e17bb67497eecabae2f1603053b33d4f2
679,954
def df_ambig(df): """DataFrame with levels 'L1' and 'L2' and labels 'L1' and 'L3' """ df = df.set_index(['L1', 'L2']) df['L1'] = df['L3'] return df
eed01e514c1f8ed40a6725de7de6630299c4f419
679,955
import argparse def construct_argument_parser() -> dict: """Construct the argument parser and get the arguments Returns ------- dict Dictionary of arguments and paramenters """ ap = argparse.ArgumentParser( description=__doc__) ap.add_argument("-cp", "--csv2parquet", type=...
93c499fd635764c32f2339734ad6fc590d034f5a
679,956
import re def set_user_input_server(): """ Set and validate user inputs Oracle Commerce Cloud backend URL :return: string """ print("Backend URL format example: https://youroccsistanceurl.com") while True: server_url = input("Enter your Oracle Commerce Cloud backend URL: ") val...
1c1ab3ddd35ca6d0c438dfd359a2ea5e83ed1294
679,957
def XORencrypt(clear, pattern): """ XOR-encrypts an input against a specified pattern. :param clear: Input to be xor-ed. :param pattern: Pattern to be xor-ed against. :return: Encrypted input. note:: Author(s): Mitch - loosely based on a script by Kees Cook """ i = 0 ...
0aeb4c447caf37d421e0e9d5138936d7c518d482
679,958
def showTests(thisconfig): """ display all test sections in app config file """ sections = thisconfig.sections() tests = [s for s in sections if s != "internal"] return tests
baace86ee970aaf2107c679c4f76c407c86ce751
679,959
def data_sort(gdf,str): """ sort the geodataframe by special string Parameters ---------- gdf : geodataframe geodataframe of gnss data str: sort based on this string Returns ------- geodataframe: geodataframe of gnss data after sorting """ gdf = gdf.sort_valu...
8010c66872ec9c2954659bdcd34bfa313963ffc7
679,960
def pages(record): """ Convert double hyphen page range to single hyphen, eg. '4703--4705' --> '4703-4705' :param record: a record :type record: dict :return: dict -- the modified record """ try: record['pages'] = record['pages'].replace('--', '-') except KeyError: re...
4eafce92f501c473522e251b57c2a118908348d6
679,962
import tempfile import os def get_tmpfile(prefix="tributors-"): """get a temporary file with an optional prefix. By default, the file is closed (and just a name returned). Arguments: - prefix (str) : prefix with this string """ tmpdir = tempfile.gettempdir() prefix = os.path.join(tmpdir,...
e0898e0e491a68749d8bbf419bdcd0ee9fc9c698
679,963
def is_response(body): """judge if is http response by http status line""" return body.startswith(b'HTTP/')
c57da1a212642ad28dbba99871fc0d3ead025886
679,964
import inspect def func_to_jdict(func): """ >>> def multiplier(a, b): ... return a * b >>> jdict = func_to_jdict(multiplier) >>> assert jdict == {'$py_source_lines': 'def multiplier(a, b):\\n return a * b\\n'} """ lines = inspect.getsource(func) return {'$py_source_lines': lines...
d3d3b054b4535726a0987ddd7d3127c5a6e8f0dd
679,965
import hashlib def get_md5(string) -> str: """ use in python3.6: """ if isinstance(string, str): hash_md5 = hashlib.md5(string.encode("utf-8")) else: hash_md5 = hashlib.md5(string) return hash_md5.hexdigest()
c72ffd58ef6827f80dd60bd0b5ea6fc85611db60
679,966
import csv def get_valid_rows(report_data): """Fetch all the rows in the report until it hits a blank in first column. This is needed because sometimes DV360 inserts a weird additional metric at the end of all the rows. This prevents us from just counting backwards to get all the rows. Args: report_da...
39647d816c4fc9f8319aca988970d8294d8faa44
679,967
def format_isk_compact(value): """Nicely format an ISK value compactly.""" # Based on humanize.intword(). powers = [10 ** x for x in [3, 6, 9, 12, 15]] letters = ["k", "m", "b", "t", "q"] if value < powers[0]: return "{:,.2f}".format(value) for ordinal, power in enumerate(powers[1:], 1)...
55ffb181e1e91b795343f298246efb13061e0827
679,968
import numpy def getValMin( data, ignoreNan = True, ignoreInf = True, ): """ finds the minimum value of the given array/list. ignore nan and inf values as specified @param data a list or a numpy array @param ignoreNan if True, NaN (not a number) will be ignored @param ignoreInf if True, Inf (i.e., an infinit...
a527d2dd203e3c56652136f696810b3f35b13513
679,969
def to_settings(settings): """Return a dict of application settings. Args: settings (dict): Database-specific settings, formatted to use with :func:`connection_url`. Returns: dict: Application-level settings. """ return {'DATABASE_{}'.format(k.upper()): v for k, v in s...
a9cc486c07851a0019af63ec8bda4f763fe8ae30
679,970
def get_variables(request): """ Добавляет переменную с GET-параметрами Нужно для сохранения фильтрациии при переключении страниц """ variables = request.GET.copy() if 'page' in variables: del variables['page'] return {'variables': '&{0}'.format(variables.urlencode())}
6a09beb1dff5e0ee79532e5eae850cd11a28b29b
679,971
def get_items_as_list(items,keys,items_names='styles'): """ Returns a dict with an item per key Parameters: ----------- items : string, list or dict Items (ie line styles) keys: list List of keys items_names : string Name of items """ if type(items)!=dict: if type(items)==list: if len(items...
5fe7f85a6b6b5b22ab2e12f3f00c1cd2fcbb83f2
679,972
import random def crossover(parent_1, parent_2): """ get random crossover point swap alphabets between two parent keys after the crossover point """ key_size = len(parent_1) crossover_point = random.randint(1, key_size-1) child_1 = parent_1[:crossover_point] + parent_2[crossover_p...
0359f2dfb02dc11aefec7623b34b3c39bc669372
679,973
def index(): """Initial page, it contains links to go in a fast way to other pages.""" return dict()
9f5c3103fc062c835d61a46e9af37e39838edc19
679,974
import os def walk_files(folder, contains=True): """ Get all files in directory recursively @param str folder: the root directory @param bool contains: Whether to include the folder in file path """ file_list = [] for root, _, files in os.walk(folder): for name in files: ...
4ed3faed0fdfd8f0fbaa651f03223a77c752832c
679,975
def shout_echo(word1, echo=1): """Concatenate echo copies of word1 and three exclamation marks at the end of the string.""" # Initialize empty strings: echo_word, shout_words echo_word = '' shout_words = '' # Add exception handling with try-except try: # Concatenate echo copies of ...
e657684cec869fd060dea7f32ad59812b13196a5
679,976
def _calc_shortest_path(nodes_process, dist): """ Calculate shortest path Args: nodes_process: nodes that we met on path dist: distances Returns: int: length shortest path """ shortest_path = 10 ** 16 for node in nodes_process[1] + nodes_process[0]: if nod...
22baad3abdf1a05355cc98132d3752138d33896a
679,977
def pystr(s): """Output a string as an eval'able representation of a Python string.""" return s.__repr__()
19d379871ab1f11fd8d338dfbc07756fcfc9062d
679,978
import os def mdate(filename): """ :param filname: str of the file :return: float of the modified date of the file """ return os.stat(filename).st_mtime
d66deefbfe3125e3311619bc1bb8bcaa39535fd2
679,979
import os def find_classes(dir): """Find all folder names within `dir` Args: dir (string): parent directory Returns: classes: str[], sorted class_to_idx: dict[str, idx] """ classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))] classes.sort() ...
802a63c8067a34374b38e3ba0b1372f796732f9e
679,980
def test_otu_edit(): """ An :class:`tuple` containing old and new otu documents for testing history diffing. """ return ( { "_id": "6116cba1", "abbreviation": "PVF", "imported": True, "isolates": [ { "default": ...
1de8c92b1f4f36c55ca5c694295297538a30aef1
679,981
def get_catalog_record_embargo_available(cr): """ Get access rights embargo available date as string for a catalog record. :param cr: :return: """ return cr.get('research_dataset', {}).get('access_rights', {}).get('available', '')
5958649bf4b83043cc151ecc7a2f0e226e2c4b9c
679,982
from typing import Any def sum_values(obj: Any) -> Any: """Return sum of the object's values.""" return sum(obj.values())
e4e083bbd33a99cbaa8a57b553febc01416b448e
679,983
def compute_possible_scope_colors(color_pairs): """Computes all possible colors resulting from transparent backgrounds. Args: [(fg, bg)] - a list of color tuples to be processed Returns: [(fg, bg)] - a list of resulting color tuples """ # We can do a better job at determining exact...
8971701d77705f870e509d21009c4fe6f7930c4c
679,984
import numpy def is_robust_after_md(X_init, X_final, delta_2): """Assess probability change between different simulation stages up to some threshold""" X_init = numpy.array(X_init) X_final = numpy.array(X_final) dX = X_final - X_init bol_assessment = abs(dX) < delta_2 return bol_assessm...
8ff7aa3b802065ecd431131b88d521d799245c07
679,985
def name_queries(): """Create a list of titles for queries that are going to be run""" query_names = ["The Most Popular Articles of All Time", "The Most Popular Authors of All Time", "Days With Connection Issues"] return query_names
ac3c943ef0da26479f1f04a0707bc6ada520dab6
679,986
def get_contact_indices(layer_0, layer_1): """Get counter that finds index pairs of all contacts between layers. Args: layer_0: String. Must be key in state. layer_1: String. Must be key in state. Returns: _call: Function state --> list, where the elements of the returned list ...
847c3308cd54ede495245f0077d26fded584ab23
679,987
import subprocess def cdhit_python(cdhit_path, input_file, output_file, c=0.50, n=3): """ This function executes CD-HIT clustering commands from within Python. To install CD-HIT, do so via conda: conda install -c bioconda cd-hit. By default, CD-HIT works via a global alignment approach, this can be ch...
8e2b796265ff3eb783990b3010648e7952b1cde5
679,988
import os def tp_generate_random(n): """ 产生n字节的随机数,然后输出为16进制字符串 :param n: int :return : str """ ret = '' data = os.urandom(n) for i in data: ret += '%02X' % i return ret
46e9622c9c44e552796e7d97c8dfe07943501aec
679,989
def serialize_tree(root): """ Given a tree root node (some object with a 'data' attribute and a 'children' attribute which is a list of child nodes), serialize it to a list, each element of which is either a pair (data, has_children_flag), or None (which signals an end of a sibling chain). """ l...
830a0dcaad9921b7eae1714bd2c7758aa11c4ad0
679,991
def do_pick(pick_status : int): """ This function takes one integer type argument and returns a boolean. Pick Status = Even ==> return True (user's turn) Pick Status = Odd ==> return False (comp's turn) """ if (pick_status % 2) == 0: return True else: return False
752633fa65984463d2e7a251acb2c1e0b1bd7962
679,992
import json def load_nl2sql_bussiness(path_nl2sql, mode, bussiness_name): """ Load training sets """ sub_dir = mode # here!!!!!!! path_dir = path_nl2sql + '/' + bussiness_name + '/' path_data = path_dir + mode + '_' + bussiness_name+'_tok.json' path_data = path_dir + 'uer_' +mode + '_' + ...
e8ec65fbc14acbca5f618467d407babbe7ccfbc4
679,993
def build_sub_housenumber(hausnrzahl3, hausnrbuchstabe3, hausnrverbindung2, hausnrzahl4, hausnrbuchstabe4, hausnrverbindung3): """This function takes all the different single parts of the input file that belong to the sub address and combines them into one single string""" hausnr3 = hausnrzahl3 hausnr4...
6e521ddff1ccded3bf36604ff0f3d2e93af767ce
679,994
def search(key, table, prefix=True): """Search for `key` in `table`. :param key: str, The string to look for. :param table: dic, The table to look in. :param prefix: bool, So a prefix search. :returns: Value in table or None if it is a prefix search it returns the full key and the ...
9a5f677b66785c7b702e1e18633790e3e909d3cb
679,995
def get_list_url(list_name): """Get url from requested list name. Parameters ---------- list_name : str Name of the requested list. Valid names are: *nea_list, risk_list, risk_list_special, close_approaches_upcoming, close_approaches_recent, priority_list, priority_list_faint, ...
163f78223aaafa82b7e40ec53b37c1de6faabb51
679,996
def fake_train(lrate, batch_size, arch): """Optimum: lrate=0.2, batch_size=4, arch='conv'.""" f1 = ( (lrate - 0.2) ** 2 + (batch_size - 4) ** 2 + (0 if arch == "conv" else 10) ) return f1
9e6458fb79b697c4529d3f3b0fa39aad1b79810f
679,997
import os from typing import List def relative_module_name(modname) -> str: """Returns modname relative to the repo root. Assumes modname's go.mod file is in the current directory. """ dir = os.getcwd() components: List[str] = [] while dir != "/": if os.path.isdir(os.path.join(dir, "....
723c511fe86c5af94e2eb7de7e8193aa9d2b5a54
679,998
from contextlib import suppress import ipaddress def is_ip_address(value: str) -> bool: """Check if a value is a valid IPv4 or IPv6 address. :param value: value to check """ with suppress(ValueError): ipaddress.ip_address(value) return True return False
8522d946e637b466207fbccdb6d61e9bb485d1cf
679,999
def day_steps_already_added(db_conn, day): """ Returns True if given day already have steps info :param db_conn: :param day: :return: """ r = db_conn.query("select day from public.steps where day=$1", day) if r is not None and len(r) > 0 is not None: return True return False
67ddb9586830bba551bb8fc2200fd7a54e20e136
680,000
def defer(x): """Method to indicate defering property validation""" return x
e6547eff745e39751f70f3c4a41450c1caadabd1
680,001
from typing import Dict def get_example_brand_map() -> Dict[str, str]: """ Return notebooks brand mapping based on simple regex. The mapping is from patterns found in menu_items to the items brand. The returned dictionary {key, value} has the following structure: key is the regex search pattern ...
171a3b5de7c3a8f893a3b4f632f62072e38ca5d5
680,002
import re import os def get_version(): """Enables single source versioning by considering base project __init__.py authoritative source""" semver_re = re.compile(r"""^__version__[\s=]+["'](\d+\.\d+\.\d+)["'\s]+$""") init_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), "qcluster/__init__.py...
3b4f8a0cc1db2feba31658ca6148d63b06ed92e3
680,004
def rename_cols(df): """[This function takes in a df, subsets the desired column and renames them to have no spaces. It also replaces "--" with 0 when no data is given] Args: df ([df]): [raw original df needing to be cleaned] Returns: [df]: [properly subsetted and renamed df] ...
3aa954539b9c38166f3694b7718b806e4bb79c50
680,005
import uuid import os def path_and_rename(instance, filename): """ Stack Overflow Django ImageField change file name on upload https://stackoverflow.com/questions/15140942/django-imagefield-change-file-name-on-upload """ ext = filename.split(".")[-1] # get filename if instance.pk: ...
084686be1e3b66c5d9794c7e8da18715648f0bfd
680,006
def find_seed(x, y): """ from 2 randInt calls """ #deal with Java signed ints if x < 0: x += 1 << 32 if y < 0: y += 1 << 32 for i in range(1 << 16): seed = (x << 16) + i if ((seed * 0x5DEECE66D + 0xB) & ((1 << 48) - 1)) >> 16 == y: return seed
d008260235212faf6e8e47643da699d2e3ab9201
680,007
import os def _count_entries(open_fn, filepath): """Check the overall number of entries based on the line number""" count = 0 if os.path.exists(filepath): with open_fn(filepath, 'rb') as fp: while 1: buffer = fp.read(8192 * 1024) if not buffer: ...
61e8596745d755b5bf04b0ac31a56933d9f7e9bd
680,008
def append_write(filename="", text=""): """ Write a new file or append info if exists Args: filename: string containing the name or "" if not given. text: content of the file Return: number of chars written """ with open(filename, 'a', encoding="utf-8") a...
98f99d27f125048c81019483c2852e76cf773016
680,009
def perm_add_vo(issuer, kwargs): """ Checks if an account can add a VO. :param issuer: Account identifier which issues the command. :param kwargs: List of arguments for the action. :returns: True if account is allowed, otherwise False """ return (issuer.internal == 'super_root')
26767838db0e3403d7c054a032b84f13c3a756f5
680,011
def ij_to_dxdy(start_idx, end_idx, _row_size=14): """ Helper function to calculate _x, _y, _dx, _dy given two indexes from the board Determine the row, change in column, and change in row # of the start/end point pair :param start_idx: starting index :param end_idx: ending index :param _row_...
9f946d6189d6149d2cb38223848569dd03d13a68
680,012
def price_in_usd(usdprice, amount, base, dest='USD'): # print(amount, base, dest) """ Return price of any "dest" currency normalized to USD """ return usdprice.convert(amount, base=base, dest=dest)
d847dd43b73e6e98ff7d8c4c7d52704d62657280
680,014
import os def default_config_path(): # type: () -> str """ Returns the path to our working directory. """ path = os.getenv('CLOAK_CONFIG', None) if path is None: if os.geteuid() == 0: path = '/etc/encryptme/encryptme.conf' else: path = os.path.expanduser...
4b6d566d5e42251baad5930dc186fd21d1c18b16
680,018
def sanitize_message(msg): """Sanitizes the message removing possible http link formating""" http_prefix = "$<http://" if msg.startswith(http_prefix): index = msg.find("|") return "$" + msg[len(http_prefix):index] return msg
c7b7f883a018b26b20258aebe43fd59e33a7baed
680,019
import re import os def increment_index_in_filename(filename): """ filename should be in the form file.ext or file-2.ext - we check for the dash and index and increment appropriately """ # check for an index i.e. dash then number then dot extension regex = re.compile(r"(.+?)\-(\d+)(\..+)") ...
d11a2a5d75705a8e5cb4f433a20fa85a15bc4c86
680,020
import logging def get_logfile_from_logger(logger): """Return the path to the log file if there is a logging.FileHandler""" try: file_handlers = [h for h in logger.handlers if type(h) == logging.FileHandler] except: pass else: if file_handlers: return file_handlers[...
ed23bba0b5ea384cef64c323d77fecfff62b8216
680,021
import torch def as_numpy(tensor_or_array): """ If given a tensor or numpy array returns that object cast numpy array """ if isinstance(tensor_or_array, torch.Tensor): tensor_or_array = tensor_or_array.cpu().detach().numpy() return tensor_or_array
e81e04bb9aeb5e72d684d22ecf790581f2edf098
680,022
def get_indicator_publication(indicator): """ Build publications grid field from the indicator external_references field Args: indicator: The indicator with publication field Returns: list. publications grid field """ publications = [] for external_reference in indicator.ge...
f932c1f46c969661d2b6843ef19743c14344d199
680,023
import pickle def load_obj(name): """ Method to load pickle objects. input: name: path with the name of the pickle without file extension. """ with open(name + '.pkl', 'rb') as file: return pickle.load(file)
edf99286bb0d2f66cfa3b7d47a7929c7ea86bf30
680,024
import socket import os def bind_tcp_socket(address): """Takes (host, port) and returns (socket_object, (host, port)). If the passed-in port is None, bind an unused port and return it. """ host, port = address for res in set(socket.getaddrinfo(host, port, socket.AF_INET, ...
285225020941d03522b536340f9d2956c27d550b
680,025
def flatten(dictionary, prefix=''): """ Flatten nested dictionaries into dotted keys. >>> d = { ... 'a': { ... 'b': 1, ... 'c': { ... 'd': 2, ... 'e': { ... 'f': 3 ...
dbf4af7709a7b7178d2c1871065d69e812dc429c
680,026
def extract_domain_from_filename(filename: str) -> str: """ :param filename: :return: """ parts = filename.split(".") return parts[-2]
9cb66867573cc7c6b48e0f7f954e4c1232322f01
680,027