content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import socket import errno def check_port_is_available(host, port): """Check if a given port it's available Parameters ---------- host : str port : int Returns ------- available : bool """ available = True s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: ...
14e120a38d70f9b7471c94f46743400b93eda8f8
680,909
def get_name(container_object): """Parse out first name of container""" return container_object['Name'].replace('/', '')
fcd47324f00fc89e993370978ad6bb5cbf7f6bdf
680,910
def get_list_index(str_list, selection): """ Gets the index of the string in a list of strings. This is case case insensitive and returns the index of the default string. It removes any EOL in the strings. Parameters: str_list(list of (:term:`String`)) selection (:term:`String`):...
5b2974efb0bed3c43251b7fa727fe48d39146115
680,912
def poly(start, end, steps, total_steps, period, power): """ Default goes from start to end """ delta = end - start rate = float(steps) / total_steps if rate <= period[0]: return start elif rate >= period[1]: return end base = total_steps * period[0] ceil = total_step...
7aad6c4b64fca29434e7d85c9deb500589e122ca
680,913
import argparse def parse_args() -> argparse.Namespace: """Handle command line arguments, returning the arguments ns""" parser = argparse.ArgumentParser(description="Build a graph of the act datamodel") parser.add_argument('url', type=str, help="Url of the act instance to graph") parser.add_argument(...
7ca8dddbf2f8118df3910b8b7b03616351b294dd
680,915
import re def _clean_maxspeed(value, convert_mph=True): """ Clean a maxspeed string and convert mph to kph if necessary. Parameters ---------- value : string an OSM way maxspeed value convert_mph : bool if True, convert mph to kph Returns ------- value_clean : str...
49cf4a46d1be664c51c6eaa6734b919f649dad93
680,916
def equalContents(arr1, arr2) -> bool: """ Checks if the set of unique elements of arr1 and arr2 are equivalent. """ return frozenset(arr1) == frozenset(arr2)
cb27f12e8a16f47f78b754bf797e247b604d5990
680,917
def colorbar_extension(colour_min, colour_max, data_min, data_max): """ For the range specified by `colour_min' to `colour_max', return whether the data range specified by `data_min' and `data_max' is inside, outside or partially overlapping. This allows you to automatically set the `extend' keyword on ...
517c71e7d0cd1792e48d87e2275a82f129d51fca
680,918
def agents_cleanup(agents, n) -> set: """ Remove all agents that are outside of the city boundaries. If agent coordinates are outside of the map, they are simply not considered. :param agents: is an array of agent coordinates :param n: defines the size of the city that Bassi needs to hide in, ...
b5a77ac4bbeb12b865df611c017d7f20d9d80fe2
680,919
def publish_changes(isamAppliance, check_mode=False, force=False): """ Publish configuration changes """ if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isamAppliance.invoke_put("Publishing configuration changes", "/docker/publish", {})
6d7d5efcd1930ad365617bed36d64e4e2aa2b326
680,921
def to_disentangled(poses, pcd): """ Add rotation-induced translation to translation vector - see eq. 11 in paper. """ mu = pcd[..., :3].mean(dim=1) if len(poses.shape) == 4: mu = mu[:, None, ...] # dim for symmetries poses[..., :3, 3] = poses[..., :3, 3] - mu \ + ...
41b1ba5036fe93a040cc0225854af3b8625b6023
680,922
import pandas def _read_csv_wind_parameters(csv_path, parameter_list): """Construct a dictionary from a csv file given a list of keys. The list of keys corresponds to the parameters names in 'csv_path' which are represented in the first column of the file. Args: csv_path (str): a path to a C...
b12dcc841fb02a7dd5fb5937ed52ce30d70ae311
680,923
def convert_list_in_str(list_in: list) -> str: """Не создавая новый список (как говорят, in place), обособляет каждое целое число кавычками, добавляя кавычку до и после элемента списка, являющегося числом, и дополняет нулём до двух целочисленных разрядов. Формирует из списка результирующую с...
850d8867a5e9e6bf9b0074bbadb4db531a6c2704
680,926
import re def remove_other(s): """Replaces a new line with a space.""" space_count = len(re.findall(r"\n|\r", s)) return re.sub(r"\n|\r", " ", s), space_count
a5f2b8552e3f946617f39aac3dfe558003bf0c5e
680,927
def createTests(ec_seq, ec_info): """ Creates the graphic output for all tests. :param ec_seq: Entity category sequence as a list." \ :param ec_info: Entity category dictionary with. :return: A graphic element for each category. """ element = "" for ec in ec_seq: name = ec de...
7988216ef65a5f9e5dda89f3fd5d6c6d910efebc
680,928
def toposort(graph, start): """Standard topological sort of graph from start nodes. Vertices are represented by integer ids. Args: graph: graph represented by dictionary keyed by vertex id, each value being a list of the connected vertex ids. start: list of starting vertices' ids for initializing ...
97c0c8fab6ad5c2c5a8f71f41bf756fe02093021
680,929
import os import time def set_system_log(json_obj): """ Print error message and write to log file """ return_msg = {} return_msg["result"] = "fail" file_name = "static/log/impossible_error.txt" if "result" not in json_obj: return_msg["error"] = "set_system_log failed no `result` i...
9d92e0ff3a94dbb67f2402cbdcdfc3a1efbc6dec
680,930
def custom_generator(min : int, max :int, divisable_by : int): """Make your own generator""" try: for i in range(min, max): if i % divisable_by == 0: yield i except ZeroDivisionError: return "divisable_by cannot be 0" except: return "Error, please chec...
a233b4b97ed9591eeca5a7e5190169e4e2a14592
680,932
from typing import Tuple from typing import List import csv import json def load_tsv_data(path: str) -> Tuple[List[str], List[List[str]], List[str]]: """Load arbitrary tsv file of formed like (id, dialogue, summary) with header each `dialogue` should be dumped json string from a list of utterances. ex) '[...
81cbd1d150311d832bea0d498faf1b339cb564f6
680,933
import os def get_cls_to_idx(datasetpath): """Method to map the foldernames/empnames into integers Args: datasetpath ([str]): Path to the folders whose names are of emperors, which contains images Returns: [dict]: A dictionary of the mapping. Key is the Emperor name and value is associa...
524b26059c24e431c02e3eb1d636233ad3755876
680,934
def add_def_args(func, def_args): """ func (fun): function which to add defaults arguments to def_args (dict): default argument given as a dictionary Examples >>> def addn(x,n): ... return x + n >>> add3 = add_def_args(addn, {'n':3}) >>> add3(2) 5 """ def func_wrapper(*arg...
afe2375a73004ad07b8462d4390785739fb9c250
680,935
def search(lst: list, target: int): """search the element in list and return index of all the occurances Args: lst (list): List of elements target (int): Element to find Returns: list: list of index. """ left = 0 right = len(lst) - 1 mid = 0 index = [] whi...
9b01c88d55eebcd0dc77581365a8794b498cc511
680,937
import argparse def get_argparser(): """Build the argument parser for main.""" parser = argparse.ArgumentParser(description='WikiExtractor') parser.add_argument('--infn', type=str, required=False, help="The location/file of the Wiki Dump. Supports uncompressed, bz2, and gzip.") #parser.add_argument('-...
332b15d024dcd349f5aba0b87817cafaecaaa59e
680,938
import cmath import math def op_acos(x): """Returns the inverse cosine of this mathematical object.""" if isinstance(x, list): return [op_acos(a) for a in x] elif isinstance(x, complex): return cmath.acos(x) else: return math.acos(x)
3da04b1d9c69184a7c4f7a6f19a46cf3d451d0fa
680,939
def readfileasmac(): """docstring for readfileasmac""" return None
df1c32810312ade43bcafe57540138988c9ef336
680,940
def make_reverse_dict(in_dict, warn=True): """ Build a reverse dictionary from a cluster dictionary Parameters ---------- in_dict : dict(int:[int,]) A dictionary of clusters. Each cluster is a source index and the list of other source in the cluster. Returns ------- ou...
7126107779524026f3bf04ec37235413984ea583
680,941
def sum_total_emissions(emissions, areas, mask): """ Function to sum total emissions across the region of interest. Arguments: emissions : xarray data array for emissions across inversion domain areas : xarray data array for grid-cell areas across inversion domain mask : xa...
e4c0d1b75216ffe8efab275b780268863e6cdd76
680,942
import math def get_Ty(duration, sr, hop_length, r): """Calculates number of paddings for reduction""" def _roundup(x): return math.ceil(x * 0.1) * 10 T = _roundup(duration * sr / hop_length) num_paddings = r - (T % r) if T % r != 0 else 0 T += num_paddings return T
79f11f787c7d7fc35a3c7cba1f64cd98ac93edb5
680,943
def upper_power_of_two(value) -> int: """Returns the value of 2 raised to some power which is the smallest such value that is just >= *value*.""" result = 1 while result < value: result <<= 1 return result
592bf0c6dbdf87916dfb1abc9b0a84c1bb27a79b
680,944
def get_maximum_index(indices): """Internally used.""" def _maximum_idx_single(idx): if isinstance(idx, slice): start = -1 stop = 0 if idx.start is not None: start = idx.start.__index__() if idx.stop is not None: stop = idx....
c869780ec8566120859361cbb75de1fe02dfa0ef
680,945
from datetime import datetime def log(message, when=None): """ Log a message with a timestamp. :param message: Message to print. :param when: datetime of when the message occured. Defaults to the present time. :return: """ when = datetime.now() if when is None else when ...
81cd215cc94673bd4669026ebe160a9c12e33fa1
680,946
def isNumber(cad): """ Chequea si el conjunto de caracteres que componen un string puede ser convertidos a un numero. Excepciones: Si un determinado string no puede ser convertido a numero Input: str, string al cual se le analiza para determinar si convertible a un numero o no Retu...
041de310d8e79581e64c336df875e2f71ef5f019
680,947
def ten_pairs(n): """Return the number of ten-pairs within positive integer n. >>> ten_pairs(7823952) 3 >>> ten_pairs(55055) 6 >>> ten_pairs(9641469) 6 """ def count_digit(n, digit): if n == 0: return 0 if n % 10 == digit: return 1 + count_dig...
98919fdc66f958dfa8a441bf5041bf3aa98f4cc0
680,949
def sorter(data): """ Sort dictinary :param data: dict :return: """ return sorted(data.items(), key=lambda kv: kv[0], reverse=False)
7d61b495b603202dd614ae488e0d7f001ebe9de0
680,950
def tkeo(x): """Calculate the TKEO of a given recording by using 2 samples. github.com/lvanderlinden/OnsetDetective/blob/master/OnsetDetective/tkeo.py Parameters ---------- x : array_like Row vector of data. Returns ------- a_tkeo : array_like Row vector containing the...
b32e4f6e004f144fd70ffecc4b424360f5f20492
680,951
def _get_winner(sgf_game): """Reads the games winner from an sgf. Args: sgf_game: from bytes parsed sgf Returns: 1 if BLACK won -1 if WHITE won 0 if it was a DRAW """ sgf_winner = sgf_game.get_winner() if sgf_winner == 'b': winner = 1 elif sgf_winner =...
5597e3ac26eb6bd4b8fdf3e2a1fb080f5f8b9ae0
680,952
import argparse def parse_arguments(): """Parses command line arguments for this script. Returns: tuple containing all of the arguments """ parser = argparse.ArgumentParser() parser.add_argument("tar1", help="First image tar path", type=str) parser.add_argument("tar2", help="Second image tar path", ...
236c9255766c947a8f3abf018afd50e6a5f3de93
680,953
def first_post(reddit_api_respond: dict): """ This function will return first post :param reddit_api_respond: json respond from api ( checker.reddit_json() ) :return: list """ if reddit_api_respond["data"] == "Too Many Requests": return ["STOP NOW"] else: post_data = reddit_a...
16c2e66213f5000eda0a9f5bbae5226f4d3464fd
680,954
def GetPlatformArchiveName(platform): """Get the basename of an archive given a platform string. Args: platform: One of ('win', 'mac', 'linux'). Returns: The basename of the sdk archive for that platform. """ return 'naclsdk_%s.tar.bz2' % platform
a5da4972c532dac98486cee6e29400858127f6db
680,955
def decompress_base85(data: str) -> str: """Replace "z" with equivalent "!!!!!" in `data`.""" return data.replace('z', '!!!!!')
20ec40db40625052b8e8de365f41ddf0e75a87f1
680,956
def parse_mcs_raw_header(filename): """ This is a from-scratch implementation, with some inspiration (but no code) taken from the following files: https://github.com/spyking-circus/spyking-circus/blob/master/circus/files/mcs_raw_binary.py https://github.com/jeffalstott/Multi-Channel-Systems-Import/b...
d41534b184e666d4b371550ed795660c5a6149a8
680,957
def get_angularity(current_fur, previous_fur): """kind of like the acceleration of fingers and hands; indicated by sudden changes in fury""" ang = abs(previous_fur - current_fur) return ang
3f62f7646e8635e0c1b3af0551510aee41ceef87
680,958
def featurewise_norm(x, mean=None, std=None, epsilon=1e-7): """Normalize every pixels by the same given mean and std, which are usually compute from all examples. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). mean : float Value ...
d1fe5e58efc60bf0dd755e402ddf0368c0743b4c
680,959
def filter_python_file(files): """filter python files from simulation folder""" python_files = [] for i in files: parent_dir = i.split("/")[0] if parent_dir == "simulations" and i.endswith(".py"): python_files.append(i) return python_files
631132d82c8b115bbb90774c09726a3ca36d9338
680,961
def shapestring(array): """Returns a compact string describing shape of an array.""" shape = array.shape s = str(shape[0]) for i in range(1, len(shape)): s += 'x' + str(shape[i]) return s
21572d955b1520239c4b6d4a236a56578f42f426
680,962
def waypoint_menu(waypoints_exist): """asks what to do with waypoints""" print("\nWas moechtest du als naechstes tun?") print("1: Wegpunkte hinzufuegen") if waypoints_exist: print("2: Wegpunkte zu Geocaches zuordnen oder loeschen") print("3: nichts") else: print("2: nichts")...
775650c4039c04b92b46d47d13b88302fa609a3d
680,963
import copy def clone_processor(p): """ Create a new processor with the same properties as the original Recursive copy child processors :param p: :return: """ return copy.deepcopy(p)
5b1178584d2e64a57d84035d4de67173bdc2aa60
680,964
def psqlize_int_list(int_list): """Formats int_list as a list for the postgres "IN" operator. `See postgres documentation for what constitutes as a list for this operator. <https://www.postgresql.org/docs/9/functions-comparisons.html>`_ :param list[int] int_list: List to format :return: Format...
71101e4f00b982e621bee3072ba5ce7d7048affd
680,965
def binary_search(sorted_list, target): """Find where a number lies in a sorted list. Return lowest item that is greater than or equal to target, or None if no item in list greater than or equal to target """ if sorted_list==[]: return None if len(sorted_list)==1: if target <= so...
c90302825dcb5b2e6989b261357e7362ccd175be
680,966
def findpeptide(pep, seq, returnEnd = False): """Find pep in seq ignoring gaps but returning a start position that counts gaps pep must match seq exactly (otherwise you should be using pairwise alignment) Parameters ---------- pep : str Peptide to be found in seq. seq : str Sequ...
3af5afa60fd29f28fd5d3d7ebfbd727c60db3948
680,968
import re def research(needle, haystack, result): """ Look for rgx *needle* in str *haystack*. Put any match in result. If a match was found, return True, else return False. Note that result must be a list. """ found = re.findall(needle, haystack) if found: result.append(found[0]) ...
06abf1d234c598eddab450b4d780f8f9a11794c1
680,969
def tweak_severity(tool_name, issue_severity): """ Tweak severity for certain tools :param tool_name: :param issue_severity: :return: """ if tool_name == "staticcheck": issue_severity = "MEDIUM" return issue_severity
3b0d14068c27558d8735d9e92eb44476f950f721
680,970
def findStringLength(string: str) -> int: """ >>> findStringLength("IoT Lab KiiT") 12 """ return len(string)
26c4d030d1329b2b68bdef105c14c6f32abc2ee8
680,971
def foo(a, b): """ >>> foo(2, 3) 6 >>> foo('a', 3) 'aaa' """ return a*b
b6cd0c35b13a8d52c1f4e46d5be3cb8dbfdf2e61
680,972
def bisect_right(a, x, lo=0, hi=None, *, key=None): """Return the index where to insert item x in list a, assuming a is sorted. The return value i is such that all e in a[:i] have e <= x, and all e in a[i:] have e > x. So if x already appears in the list, a.insert(i, x) will insert just after the right...
780780f7d444eca6067e82d4c2534b83336ff806
680,974
def _calc_nodes_top_position(nodes): """ ノードリストの上端位置を取得 Args: nodes (bpy.types.Nodes): ノードリスト Returns: float: 上端の位置 """ topPos = None for node in nodes: posY = node.location[1] if topPos == None or topPos < posY: topPos = posY return topPos
25fa1278628d7afa2822a50bfb78adb9b156c161
680,975
import random def RandCallSign(Nmin,Nmax,charset): """Generate random Call Signs""" length = random.randint(Nmin,Nmax) call_sign = ''.join([random.choice(charset) for i in range(length)]) return (call_sign,) #the braces are doubly encloes because the whole document is also a format string
5dc1d86903e6e420664af19357544ca2ea89be58
680,976
import ast def check_return(node): """ Returns `False` if `ast.Return` only appears at the end of `ast.FunctionDef`. """ class Visitor(ast.NodeVisitor): def __init__(self): self.found = False def visit_Return(self, node): self.found ...
3ef86b9a88c04c78738606215df55f411bfd46c7
680,977
def Number(s): """Support for ssf testing: the Number function from JavaScript""" f = float(s) if int(f) == f: return int(f) return f
81a1d78f013ce19a2017030293a75bbc45114941
680,978
import os def get_private_key(conf, node_name): """Return the node's private key""" runtime_dir = os.path.join(conf.configuration["CA_default"]["runtimes_dir"], node_name) with open(os.path.join(runtime_dir, "private", "private.key"), 'rb') as f: return f.read()
89bb1754f160cfe4bf4bcd4e8443f65c8a58d518
680,979
def ndvi( redchan, nirchan ): """ Normalized Difference Vegetation Index ndvi( redchan, nirchan ) """ redchan = 1.0*redchan nirchan = 1.0*nirchan if( ( nirchan + redchan ) == 0.0 ): result = -1.0 else: result = ( nirchan - redchan ) / ( nirchan + redchan ) return result
ca35eb06a9f38eb2052af0cc1b0e33e753992729
680,980
def get_root_cause(g): """ 通过关系图获取根因列表 Args: g: 关系图 Returns: 根因列表 """ result = list() node_ids = g.nodes() # 获取原因最多的节点 max_pre_node, max_pre_size = None, 0 for node_id in node_ids: if len(list(g.predecessors(node_id))) > max_pre_size: max_pre_node = ...
96c3e52847afeb4538475254e0599cecbaea69e3
680,981
def read_file(ref_file): """Reads a reference file and converts it to a dictionary. Args: ref_file: String of the path to the file that contains the reference data. Returns: gene_UID_dict: Taxonomic_UID_dic, this is an dictionary where the key is the UID and the value the taxonomic in...
5e5d1a4ad17d178f45435c7c82b01bb1a840d08a
680,982
def fake_uname(): """Fake version of os.uname.""" return ('Linux', '', '', '', '')
0e4e89405e98bfde6d7b6f258960b36a221d5d66
680,983
import json def getDefaultColumnsForScope(syn, scope): """ Fetches the columns which would be used in the creation of a file view with the given scope. Parameters ---------- syn : synapseclient.Synapse scope : str, list The Synapse IDs of the entites to fetch columns for. Returns...
55f3a4d13f9cc88d11f1cce2e157f0d88600803d
680,984
def _fill_sequence_and_annotation(df_group, s_exon2char): """Create a list of sequences and s-exons (annotation).""" s_exon_annot = [] seqs = [] for row in df_group.itertuples(): s_exon = s_exon2char[row.S_exonID] seq = str(row.S_exon_Sequence).replace('*', '') for _ in range(len...
ce6401de25dc1f08fd55c27d0a46febf422850ec
680,985
def bootstrap_field(field, param1=''): """Take a FormField and produce nice HTML for its label, input, etc.""" value = '' if hasattr(field.form, 'cleaned_data'): value = field.form.cleaned_data.get(field.name, '') return { 'field': field, 'type': field.__class__.__name__, 'value': value, 'param1': param1...
d78ef588613862c0e760cbb73cbc02d2070ef1fc
680,986
def get_role(keystone, name): """ Retrieve a role by name""" roles = [x for x in keystone.roles.list() if x.name == name] count = len(roles) if count == 0: raise KeyError("No keystone roles with name %s" % name) elif count > 1: raise ValueError("%d roles with name %s" % (count, name)...
d18247388dadc0c0cb9b6e51fce5ba808dd13a4c
680,987
def cross(a,b): """Compute the cross generalized product of a x b, assuming that both fall into the w=1 hyperplane """ return [ a[1]*b[2] - a[2]*b[1], a[2]*b[0] - a[0]*b[2], a[0]*b[1] - a[1]*b[0], 1.0 ]
a9c682b6415ea008ac79e0814a196b0d49357dc2
680,988
import torch def _torch_hist(label_true, label_pred, n_class): """Calculates the confusion matrix for the labels Args: label_true ([type]): [description] label_pred ([type]): [description] n_class ([type]): [description] Returns: [type]: [description] """ ...
e2c4a6445868341ef0ef9df279449f8b60fb4244
680,989
import requests def icmp_echo(baseurl, host, cookie_header): """ Test IP connectivity to a given host :param baseurl: Imported from yaml :param host: IP address of destination :param cookie_header: Object created by loginOS.login_os() :return: REST call response JSON """ url = baseurl ...
2a2489931fb01d6a32c2bfb64c7df094fe424ada
680,990
def user_is_mozillian(user): """Check if a user belongs to Mozillians's group.""" return user.groups.filter(name='Mozillians').exists()
09216ccdfaadbe44be9a0113bddea901b709447e
680,991
def compute_age(date, dob): """ Compute a victim's age. :param datetime.date date: crash date :param datetime.date dob: date of birth :return: the victim's age. :rtype: int """ DAYS_IN_YEAR = 365 # Compute the age. return (date - dob).days // DAYS_IN_YEAR
39a88d3f780f46b50d4d64aa0f05f54d20389396
680,992
import io def _read_bytes(fp, size, error_template="ran out of data"): """ Read from file-like object until size bytes are read. Raises ValueError if not EOF is encountered before size bytes are read. Non-blocking objects only supported if they derive from io objects. Required as e.g. ZipExtFile ...
388a244d26bf030db1fc18086c64779a34bf904e
680,993
import re def tosymbol(name, _tosymbol_re=re.compile(r"[^A-Za-z0-9_]+")): """Make 'name' into a valid C++ symbol.""" if len(name) == 0: return name name = _tosymbol_re.sub("_", name) if name[0] in "0123456789_": name = "N"+name return name
c33eba7400b4475f6d6596906f35a19555f80d4d
680,994
import uuid def autofill_user(user): """ Updates the username and password of the provided user by assigning the lowercase user_id as username and generating a random password. :param user: :type=: User :return: """ user.username = user.id.lower() user.password = uuid.uuid4().hex ...
4d681b3f0c15b73a2f538d6be5024cd44883a836
680,995
import requests def get_l2vpn_service_json(proxy_url, sessiontoken): """Returns JSON response with L2VPN services""" myHeader = {'csp-auth-token': sessiontoken} myURL = f'{proxy_url}/policy/api/v1/infra/tier-0s/vmc/locale-services/default/l2vpn-services/default' response = requests.get(myURL, headers=...
295a6ed0c6add54c3c1bbd7385c407241d340b77
680,996
import logging def build_sql_query_from_yaml_schema(db_schema: dict) -> str: """ Build CREATE TABLE query :param table_name: DB table name :param db_schema: table field names and their types :return: """ val = [] table_name = db_schema['table_name'] for field_name, field_value in d...
8684ab8fcff2874c0ac9fca526267ecaf5abbf22
680,997
import secrets def gen_project_code(): """ return: str """ return secrets.token_hex(10)
4f07b8968db3923cce24439f57e5f4db6456eaf3
680,998
def divisibleBy(i, nums): """assumes nums is a list of ints assumes i is an int returns a boolean, True if all the ints in nums are divisible by i. else false """ for num in nums: if num % i != 0: return False return True
283bca97ee361c6b03f847599767b409b565c298
680,999
def list_words(): """return a list of words""" fin = open('words.txt') words = [] for line in fin: words.append(line.strip()) fin.close() return words
cf44d86fe43183b684348a7d5183bf35b147b2cc
681,000
from pathlib import Path def extract_extension_from_file(file: str) -> str: """Extract extension from file name. :param file: Path of file we want to extract the extension from. :return: Extension of file (e.g., mp3) """ return Path(file).suffix.lower()[1:]
e20a50662c519c69187ae2cb3d929afc6cfb615c
681,001
def get_server_type(server_type_str): """Check wether string is contained""" server_type_list = server_type_str.split(' ') if len(server_type_list) < 2: if server_type_str == 'Backup': return 'backup' else: return 'unknown' return server_type_list[1].split('-')[0]
745c8988fbfc86f78097507199f7f54764e24c34
681,002
def _is_model(layer): """Returns True if layer is a model. Args: layer: a dict representing a Keras model configuration. Returns: bool: True if layer is a model. """ return layer.get('config').get('layers') is not None
bb19a8c2da747a98c3d34c85902a3a1f989b6c44
681,003
def broken_node_lookup_2(selectors): """Returns a list of various garbage, not strings""" return [{"this": "that"}, 7, "node3"]
0f4f77362bfdfaa19e680102459af07ae2d10830
681,004
def helptext() -> str: """ Simple Helptext For Plugin """ return "For managing plugins for use by forge."
4950fec7f95a8226f09ba51e4a1b4200a0c470eb
681,005
def accuracy(predictions, targets): """Returns mean accuracy over a mini-batch""" predictions = predictions.argmax(dim=1).view(targets.shape) return (predictions == targets).sum().float() / targets.size(0)
d0e9ca2c1c09e9a841b46573092f88e016247e69
681,006
def transmission_joint(epaipm_dfs, epaipm_transformed_dfs): """Transforms transmission constraints between multiple inter-regional links. Args: epaipm_dfs (dict): Each entry in this dictionary of DataFrame objects corresponds to a table from EPA's IPM, as reported in the Excel s...
0793d04e1846d938b4b8bffc1f0c2ea9e6fcf2b1
681,007
import logging def get_split_value(text,keyword,last_match=False,split_opt=None,split_idx=0): """ Parse text to return the value corresponding to the keyword and other options. """ val ='' if last_match: i = text.rfind(keyword) else: i = text.find(keyword) if i > 0: ...
187ba0bfa008ed1b149285d611b1494ec601b78d
681,008
import subprocess def check_output(command, stderr=None, shell = True): """ Ensures python 3 compatibility by always decoding the return value of subprocess.check_output Input: A command string""" output = subprocess.check_output(command, shell=shell, stderr=stderr) return output.decode('utf-8')
fddc57132e2ece71e70c17a924f03ac977551fa8
681,009
import binascii def int_to_str(int_arg: int) -> str: """reverse map int to string""" return binascii.unhexlify(format(int_arg, 'x')).decode('utf-8')
fa6b1382c14c8887bdb19625a888945b9215cc2a
681,010
def find_credentials(cls,account): """ method that collects an account_name and outputs the credential that matches the account_name """ for credentials in cls.credentials_list: if credentials.account == account: return credentials
f920a62f2aca6647e9fb7b753059e6250176ef6f
681,011
def check_line_number(co, lasti): """ Get line number and lower/upper bounds of bytecode instructions according to given code object and index of last instruction (f_lasti). See also: cython/Objects/codeobject.c::_PyCode_CheckLineNumber """ lnotab = co.co_lnotab addr_offsets, line_offsets = lno...
bccb9be41d2035f430ebf45a16672feaf10bff46
681,012
def check_blank_after_last_paragraph(docstring, context, is_script): """Multiline docstring should end with 1 blank line. The BDFL recommends inserting a blank line between the last paragraph in a multi-line docstring and its closing quotes, placing the closing quotes on a line by themselves. """ ...
64f32e62a65d513e092a501db6fcdcd1ca9ce9db
681,013
import re def normalize(tokens : list) -> str: """ Removes non-english characters and returns lower case versions of words in string form. """ subbed = [re.sub("[^a-zA-Z]+", "", s).lower() for s in tokens] filtered = filter(None, subbed) return " ".join(list(filtered))
9997d779f8b92894aa641b1b14e43ab182018619
681,015
def one_or_more(pattern, greedy=True): """ one or more repeats of a pattern :param pattern: an `re` pattern :type pattern: str :param greedy: match as much as possible? :type greedy: bool :rtype: str """ return (r'(?:{:s})+'.format(pattern) if greedy else r'(?:{:s})+?'.form...
83158602e863210c178e6dcee2b650655971fef0
681,016
from typing import Optional from typing import Dict def build_cat_labels( boundaries, other_bucket: int, missing_bucket: int, start_special_bucket: int, specials: Optional[Dict[str, list]], ) -> Dict[int, str]: """ Build categorical labels. """ assert other_bucket is not None a...
47c8e3ee201473deb5fb4f59782d61e3f039fac6
681,017
def isstringlike(item): """Checks whether a term is a string or not""" return isinstance(item, str)
db0a88ebea37a5050e212db130da02bc6bdc07d5
681,018
def task_imports(): """find imports from a python module""" return { 'file_dep': ['projects/requests/requests/models.py'], 'targets': ['requests.models.deps'], 'actions': ['python -m import_deps %(dependencies)s > %(targets)s'], 'clean': True, }
7c3ea28a72f778fe17165fa7bea73f096fa011fe
681,019
def _update_gn_executable_output_directory(commands): """Update the output path of executables and response files. The GN and ZN builds place their executables in different locations so adjust then GN ones to match the ZN ones. Args: commands: list of command strings from the GN build. Retur...
68e14ca2e8d20b5d8a7462de8883a60c071636bf
681,020