content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import json def load_cexfreqtable(fname): """ Loads a Context Feature frequency table """ with open(fname) as fp: cexfreqtable = json.load(fp) return cexfreqtable
f8e48b67e1db501332e54294c3087b4f2b1fb938
650,052
def extend(key, term): """ extend a key with a another element in a tuple Works if they key is a string or a tuple >>> extend('x', '.dtype') ('x', '.dtype') >>> extend(('a', 'b', 'c'), '.dtype') ('a', 'b', 'c', '.dtype') """ if isinstance(term, tuple): pass elif isinstance(...
fdc14d4918618627d2c8dae5f54a0ad02a2b0feb
650,053
def _abs2(x): """Absolute square of data""" return x.real*x.real + x.imag*x.imag
17527d9aaed7fa0d9adf3f1a30abd625b291ca21
650,054
def str_or_list(value): """ String to list of string. """ if isinstance(value, list): return value return [value]
48e710af66d4f76980f7df92dd80f5848ea42c2a
650,055
import torch def to_device(data, device): """ :param data: :param device: :return: """ if isinstance(data, (tuple, list)): return to_device(data, device) elif isinstance(data, dict): return {name: to_device(item, device) for name, item in data.items()} elif isinstance(d...
d64839e23ab2dd9f8500497d2ab8c90798855bbb
650,056
def friendly_display(port,begin=8000): """for wehn you want some 'web' ports""" ret= port-begin if ret < 0 or port<0: raise ValueError('neg values') return ret
554002184d6a1d5c2fa01c0455dbc5c5dca72f5e
650,057
def contains_test_passer(t, test): """ Return whether t contains a value that test(value) returns True for. @param Tree t: tree to search for values that pass test @param function[Any, bool] test: predicate to check values with @rtype: bool >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4.5,...
56cbd48f9c416c64c1822b637fd4e8780ce72bc5
650,058
def description(): """return module description""" return 'modest map display'
2e9b91a5d18daa82b1e4185ee5b6ba3ec668c8c6
650,059
from typing import Any import re def int_comma(value: Any) -> Any: """Converts an integer to a string containing commas every three digits. For example, 3000 becomes '3,000' and 45000 becomes '45,000'. To maintain some compatability with Django's int_comma, this function also accepts floats. Ar...
2dadf87da42a88a937d35752ee9fb37688a4b1b1
650,060
import json def ReadMeasurements(test_result): """Read ad hoc measurements recorded on a test result.""" try: artifact = test_result['outputArtifacts']['measurements.json'] except KeyError: return {} with open(artifact['filePath']) as f: return json.load(f)['measurements']
ebb51702d9b45ee9103478161e72d567de719f03
650,061
def fib(n: int) -> int: """ This is a description """ old, new = 0, 1 for _ in range(n): old, new = new, old + new return old
81beb5e4c24f1afe61f4f2c60ebef48b977160ca
650,062
def process_job_execution_status(stderr, done_tag, fail_tag): """ Add execution status tail to job. If job completes properly adds `DONE`, else adds `FAIL`. Parameters ---------- done_tag : pathlib.Path Path where to generate the `DONE` file tag. Relative to the job header `wor...
30b75c74bd5bc5ede3189f2b035b69190b54a37a
650,064
def calculate_fibonacci(num: int) -> int: """ >>> calculate_fibonacci(-1) Traceback (most recent call last): ... ValueError: num must not be negative. >>> calculate_fibonacci(0) 0 >>> calculate_fibonacci(1) 1 >>> calculate_fibonacci(2) 1 >>> calculate_fibonacci(3) ...
b1532997b0ac20f8ac17bf7ab0a652ca0ec49b8b
650,066
import sys import inspect def find_base_class(name): """ Find a class LIKE name currently defined in this module. :param name: str :return: class matching "name" """ current_module = sys.modules[__name__] for obj_name, obj in inspect.getmembers(current_module): if inspect.isclass...
b50e63eb664216335d071379bb850c4f13aac0e2
650,067
import re def _process_domain(domain, is_subdomain = False): """ process_domain helper function. """ # turn a deities string into a list of deities deities = domain['deities'] deities_regex = re.compile(r'<a.*?>(?P<deity>.*?)</a>') domain['deities'] = deities_regex.findall(deities) # turn a po...
784eff6f52fd6d27c234d2dc4237dffd5a3804d5
650,068
def __neighcom(node, graph, status, weight_key): """ Compute the communities in the neighborhood of node in the graph given with the decomposition node2com """ weights = {} for neighbor, datas in graph[node].items(): if neighbor != node: edge_weight = datas.get(weight_key, 1)...
4ad88db3c7f8ea56356ba07441c929caac62c040
650,069
def make_tweet_content(preamble: str, message: str, link: str) -> str: """ Make formatted tweet message from preamble, message and link. Arguments: preamble (str): Preamble to be used in the beginning of the tweet. message (str): Main message of the tweet. link (str): Link to be add...
da349534af48e0614785a838f868130cb7ee0a57
650,070
import torch def linear_quantize(input, scale, zero_point, inplace=False): """ Quantize single-precision input tensor to integers with the given scaling factor and zeropoint. Args: input (`torch.Tensor`): Single-precision input tensor to be quantized. scale (`torch.Tensor`): ...
690fcc8250b989f1005cfac845b602dbb9d897bc
650,071
def rate_density(x, a): """simple linear rate density """ return a * x
9926078c59458f8b44da66bea515c6a58a694021
650,073
def clear_ironic_port_internalinfo(db, port_id): """Remove internal_info data from ports. When the data wasn't cleaned up, it appeared to block other instances from spawning on the node. Now it may not be required? More research needed. """ sql = '''\ UPDATE ironic.ports SET internal_info...
63f66963190927b8971c4d59a8655eda6df09873
650,075
def parser(response): """Parses the json response from CourtListener /opinions endpoint.""" results = response.get("results") if not results: return [] ids = [] for result in results: _id = result.get("id", None) if _id is not None: ids.append(_id) return ...
9632ba800b5de4978aa1c85615dfdeb389bfe5ca
650,076
def unknown_error1(*args): """ Mock requests to Misfit with Unknown error 1: 500 """ return {'status_code': 500, 'content': "I HAVE NO IDEA WHAT'S GOING ON!"}
fe6598197d3245a93afea6fa94d3efadfa1824ac
650,077
def equal_test_conditions(testapi_input, nfvbench_input): """Check test conditions in behave scenario results record. Check whether a behave scenario results record from testapi matches a given nfvbench input, ie whether the record comes from a test done under the same conditions (frame size, flow coun...
737f3ed9e4ff5e6bd73b9519c60bb555f3d3acc8
650,078
import optparse def Flags(): """ Consturcts a parser for extracting flags from the command line. """ result = optparse.OptionParser() result.add_option( "-t", "--target", help="The target html to generate", metavar="[js,dart]", default='js,dart') result.add_opti...
f38edbed5853c0a403ce1fa541b3e707cbc5f539
650,079
def merge_n_reduce(f, arity, data): """ Apply f cumulatively to the items of data, from left to right in n-tree structure, so as to reduce the data. :param f: function to apply to reduce data :param arity: Number of elements in group :param data: List of items to be reduced :return: List of...
7cb1c2c3dd7da95abcd1ab5b737d6f03c686a4b5
650,080
def is_substring_in_list(needle, haystack): """ Determine if any string in haystack:list contains the specified needle:string as a substring. """ for e in haystack: if needle in e: return True return False
f85ac189ec622aa91d543b5a2d82bc4edcbf0802
650,081
def deep_access(x, keylist): """Access an arbitrary nested part of dictionary x using keylist.""" val = x for key in keylist: val = val.get(key, 0) return val
1f100949a8603c7924ce1ab40e66a3a220cffa6d
650,082
def getcommontype(action): """Get common type from action.""" return action if action == 'stock' else 'product'
70de4e1fe270804fea883b96d7111db141cc3c22
650,083
from typing import Union def olt_value_str_to_str(value:str, field_id:int) -> Union[str, int]: """ convert value str in show oltqinq-domain to str value Args: value (str): 要处理的值 field_id (int): 字段类型ID Returns: str or int: 处理后的值 """ # 1(Dst Mac) 00 00 00 00 00 00 ...
2b42fd982ae868c1d34fa1deb4ea7ce6628c27f6
650,084
def get_next_page(resp_json): """Description.""" if "navigationLinks" in resp_json: if "next" in resp_json["navigationLinks"][0]["ref"]: return resp_json["navigationLinks"][0]["href"] else: if len(resp_json["navigationLinks"]) == 2: if "next" in resp_json[...
1236b46909cd9f7dcdcc1ccaeed4dc13a21d552d
650,085
def load_version(): """Return the version number""" with open("VERSION") as buffer: return buffer.readline().strip()
5853447fbfcdf3c792672538dec7c9810ff894e9
650,086
def format_import(source_module_name, source_name, dest_name): """Formats import statement. Args: source_module_name: (string) Source module to import from. source_name: (string) Source symbol name to import. dest_name: (string) Destination alias name. Returns: An import statement string. """ ...
7e11642cf0b8bd5fae42d34eb1b7233e7921be49
650,087
def check_uploaded_file(driver, set_login_data, downloads_page_opening, downloads_manager): """Upload file to Downloads page""" return downloads_manager.get_file_name()
91eb4828f2b3262e4f914405946850fc9fb093dd
650,088
def longest_in_dict( d:dict ) -> str: """ Returns longest item's string insde a dict """ longest:str = '' for i in d: if len(str(i)) > len(longest): longest=i return longest
ea6a8f1cc14c614b345f0c0d6df7906e18e0510f
650,089
import math def RelToAbsHumidity(relativeHumidity, temperature): """Convert Relative Humidity to Absolute Humidity, for a given temperature.""" absoluteHumidity = 6.112 * math.exp((17.67 * temperature)/(temperature+243.5)) * relativeHumidity * 2.1674 / (273.15+temperature) return absoluteHumidity
e339144a2a1862891cedeca540dc949215da09f5
650,090
def healthcheck(): """ Checks that the app is properly running. """ return "200 ok"
f1a576e815c110b97ef02378fff2f488f280ef62
650,091
import hashlib import json def get_app_hash(raw_cwl): """If the CWL has a field "sbg:hash" (as used by sevenbridges-cwl) use that, else compute it (again, just like sevenbridges-cwl) :param raw_cwl: :return: """ if "sbg:hash" in raw_cwl: return raw_cwl["sbg:hash"] else: sh...
490e6b416e2024711cccbd3de37652fcc8b16cc0
650,092
import yaml def data_file_read_yaml(filename): """ Reads a file as a yaml file. This is used to load data from fuzz-introspectors compiler plugin output. """ with open(filename, 'r') as stream: try: data_dict = yaml.safe_load(stream) return data_dict except ...
1ac2aa98d9628aab6637048a8f07f5ffa84aa750
650,093
def configureXRayAccumulators(xrts, charAccum=True, charFluorAccum=False, bremFluorAccum=False, printRes=False): """configureXRayAccumulators(xrts, charAccum = True, charFluorAccum = False, bremFluorAccum = False, printRes=False) Configures the x-ray accumulators for characteristic and both bremsstrahlung and c...
6ff94a742be01ba29039def59be1933338b97829
650,094
def clsn(obj): """Short-hand to get class name. Intended for use in __repr__ and such.""" if isinstance(obj, str): return obj else: return obj.__class__.__name__
e030359e86cf07db8e6869c219575c74c620de6a
650,096
import sympy def factorial(num, double=False, symbol=True): """阶乘或双阶乘""" if double: return sympy.factorial2(num) if symbol: return sympy.factorial(num) else: fa = 1 for i in range(2, num+1): fa *= i return fa
871ce0fd9443ec501a2bd8004dac4e204faf6d25
650,097
def count_values(tokens): """Identify the number of values ahead of the current token.""" ntoks = 0 for tok in tokens: if tok.isspace() or tok == ',': continue elif tok in ('=', '/', '$', '&'): if ntoks > 0 and tok == '=': ntoks -= 1 break ...
6e63f0e48a8a2014307f7a50738cc5f1035c8c4a
650,098
def quoteIfNeeded(txt, quoteChar='"'): """ quoteIfNeededtxt) surrounds txt with quotes if txt includes spaces or the quote char """ if isinstance(txt, bytes): txt=txt.decode() if txt.find(quoteChar) or txt.find(' '): return "%s%s%s" % (quoteChar, txt.replace(quoteChar, "\\%s" % quoteChar), quoteC...
7144d65a19c938789f2a6b9bcfc58021e89d4d43
650,099
def get_slurm_script_gpu(log_dir, command): """Returns contents of SLURM script for a gpu job.""" return """#!/bin/bash #SBATCH -N 1 #SBATCH --ntasks-per-node=1 #SBATCH --gres=gpu:tesla_p100:1 #SBATCH --mem=32GB #SBATCH --output={}/slurm_%j.out #SBATCH -t 5:59:00 module load anaconda3/2019.10 cudatoolkit/10.1 cudnn...
ffdd9d51a8d704013016f7126a53b8a13653055d
650,102
def make_jobjects(entities, transformer, *args): """Run a sequence of entities through a transformer function that produces objects suitable for serialization to JSON, returning a list of objects and a dictionary that maps each entity's key_name to its index in the list. Item 0 of the list is always Non...
6d891488dc95f6c3ed6d69ab21f743c2fa721177
650,103
import os def openbmc_seg(scratch_base, segment_base, dt): """Generate segment filenames""" return os.path.join( scratch_base, segment_base, f"openbmc-{dt.strftime('%Y%m%d')}-{dt.strftime('%H%M%S')}.parquet" )
d50757dcf28e39605626a6e0431cd2fceaf20928
650,104
import ctypes def _encode_string(value): """Encode a Python3 string in preparation to be passed across DLL boundary""" return ctypes.c_char_p(value.encode('utf-8'))
12bb88faf21431dfec433724eb2056366833f2e0
650,106
def ir(points=(1024,), snr=10): """Generate an IR dataset for testing""" return NotImplemented
b2592f5c6afbf6dbb66126a1fabe6fb0f82e2429
650,107
def _get_bin_sum(bin_result): """ Get the [min, max] of the sample; best-fit scatter and error. """ min_val = bin_result['samples'].min() max_val = bin_result['samples'].max() sig = bin_result['sig_med_bt'] err = bin_result['sig_err_bt'] return min_val, max_val, sig, err
7f7d7a9705fb0e4da80689e1c98cb159e90e3b32
650,108
def _modify_permissions_request_factory(path, settings): """ Constructs modify permissions request :param path: A path to apply permissions :param settings: An instance of ModifyPermissionsSettings :return: A constructed request """ modify_permissions_request = settings.to_pb() modify_pe...
4830d93fc94559940cc8f85a887476874f7e442f
650,109
import platform import pwd def GetUserId(user): """ On a Linux system attempt to get the UID value for a give 'user'. This uses a system call to obtain this data. :param user: User name to lookup. :return: UID value if the user is found, otherwise None """ if isinstance(user, int): ...
870556d8beedc513e6b4aa321a9f80807e9570ee
650,110
def to_landscape(diagram): """ Convert a diagram to a landscape (b,d) -> (b, d-b) """ diagram[:, 1] -= diagram[:, 0] return diagram
48f2712a0d7975b05a59bdaaee984ab5ba79c936
650,111
import argparse def arg_parser(): """ Arg parser for command line arguments. """ parser = argparse.ArgumentParser(prog='update_template') parser.add_argument('template', help='Input template file.') parser.add_argument('entry', help='the plugin entry') parser.add_argument('key', help='The para...
17087d0632a0b901dfa0cc74196dda40262c9f00
650,112
from typing import Tuple def cmyk_to_rgb(c: float, m: float, y: float, k: float) -> Tuple[int, int, int]: """Convert CMYK (Cyan Magenta Yellow Black) to RGB (Red Green Blue). :param c: Cyan (0.0 to 1.0 inclusive). :param m: Magenta (0.0 to 1.0 inclusive). :param y: Yellow (0.0 to 1.0 inclusive). ...
375481b55571b9ef456612c7544afe2dca4ef7ac
650,113
def get_url(artist): """ Get the url link for the artist in www.lyrics.com """ return f"https://www.lyrics.com/artist/{artist}"
84101cda872070f9106a3fb5e6349161ac20cc3c
650,114
def tag(tag_name: str, data: str): """ Generate tag include tag name and tag data """ return '<' + tag_name + '>' + data + '</' + tag_name + '>'
563dc33229f03b0ad45161819052ef46e4f65f59
650,115
def resolve(var_name, scope): """ Finds the given symbol (a function or a variable) in the scope. Reports error if not found. Args: var_name (str): Name of the symbol to be found. scope (dict): Local variables. Returns: Found variable or a function. """ variable = scope...
ce6983070d3425ce843593b7392090f1e3fe6186
650,116
def linking_patterns(max_word_length, current_pair=('LR', 'RL')): """ Returns the word base for the computation of enl. # The set of pairs form a binary tree which we fill in à la Pascal # The root pair is ('LR','TR') # The pairs to the extreme left are ('Ln R', 'R Ln') # The pairs on the ...
d9fa88d6ffa27d345aaf4d475d4a2cbf0f68db2c
650,117
def anySubs(UserDetails): """ Checks if the user has any subscriptions yet """ if('subscriptions' in UserDetails.keys()): return True return False
80f3c4e93300faea85247654b7c2328312e107c6
650,119
def __parse_version_from_service_name(service_name): """ Parse the actual service name and version from a service name in the "services" list of a scenario. Scenario services may include their specific version. If no version is specified, 'latest' is the default. :param service_name: The name of the ser...
7fc634b7159e7141e99cbec090275388f00e27c5
650,120
import random def class_colors(names): """ Create a dict with one random BGR color for each class name """ return {name: ( random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)) for name in names}
a91f84aa1e3012fc553744e941abd5e9aeca9074
650,121
def _gradient_centralization(grad, use_gc=True): """concept taken from https://github.com/Yonghongwei/Gradient-Centralization""" if use_gc and grad.ndim > 1: averaging_dimensions = tuple(range(1, grad.ndim)) # all except 0 axis grad -= grad.mean(axis=averaging_dimensions, keepdims=True) retu...
94b2634ccbf066bb621b294cfc2fe634df2ff569
650,122
import argparse def parse_args(argv): """ Parse the arguments. Args: argv: List of command line args. Returns: Parsed arguments. """ parser = argparse.ArgumentParser(description='') parser.add_argument('db_file', help='Sqlite3 db file.') parser.add_argument('ident', h...
d6de7018dd00484a7e6fd6eb2b19ff8acd918677
650,124
def collect(delta): """Return the states and alphabet used in the transition function delta.""" Q = set() Sigma = set() for (q, a), r in delta.items(): Q.add(q) Q.add(r) Sigma.add(a) return Q, Sigma
f300553f0ac8a9b03dfc371279b5af056fed9171
650,126
import torch def convert_to_one_hot(tensor, num_classes=None): """Convert dense classification targets to one-hot representation Parameters ---------- tensor : torch.Tensor Tensor of dimensionality N num_classes : int Number of entries C of the one-hot representation. If None, use maximum value...
48bfe87a0aea539b05076951c211353c85a3dd19
650,127
def enum_list_to_bitfield(enum_list, bitfield_enum_type): """ Converts a list of enums to a bitfield value. Args: enum_list (List[enum.Enum]): Specifies the list of enums. bitfield_enum_type (enum.Enum): Specifies the bitfield enum type from which to mask and extract the enum va...
7f64eebcfed27a027e7d40c127914cfe720b731c
650,128
def getCountryIndList(objMarket): """ get country index list in the market """ lsCountryList = list() for objZone in objMarket.lsZone: if objZone.iCountryIndex not in lsCountryList: lsCountryList.append(objZone.iCountryIndex ) return lsCountryList
0581f1662a0f8f54568ca4b69e1f32dfc551f0be
650,129
def calcSurroundingIdxs(idxs, before, after, idxLimit=None): """ Returns (idxs - before), (idxs + after), where elements of idxs that result in values < 0 or > idxLimit are removed; basically, this is useful for extracting ranges around certain indices (say, matches for a substring) that are contained fully in an ...
72b064dd8f79762e18d1dd2a9d1ab84628a4e1a8
650,130
from datetime import datetime import os def append_date_to_filename(filename, epoch): """ Append a date to a filename Parameters ---------- filename : Path-like The original filename to modify. epoch : Number The number of seconds since the beginning of 1970. Returns ------- str """ strftime = datet...
c701ed44be41d566ebd2949d16d82655382fe1b2
650,131
def islist(thing): """ return True if a thing is a list thing, False otherwise """ return isinstance(thing, list)
d2658b137a06b3b26cafe94bd9360607da49a466
650,132
def extract_grad(model): """returns list of gradients of a model model (float tensor): torch tensor with gradients Returns: (float tensor list): list of gradients of the model """ return [p.grad for p in [model]]
b63f18d83fdde6635e9ffebea91efce25a3e3889
650,134
def character_arena_progress(pvp_data): """Accepts a JSON object containing pvp data and returns the players current arena/bg progression. """ brackets = pvp_data["pvp"]["brackets"] two_v_two = brackets["ARENA_BRACKET_2v2"]["rating"] two_v_two_skirmish = brackets["ARENA_BRACKET_2v2_SKIRMISH"]["rati...
372d78409367e336373974e2d020cd66a2d7402b
650,135
def readLines(file, map=lambda line: line.strip()): """ Read and return a file as a list of files. Optionally, @map argument can be set to process the lines. """ # Read file line by line. results = [] with open(file, 'r') as infile: for line in infile: results.append(map(line)) return results
554e9360f2c52e7450455d92726296f2638ce99f
650,136
def get_daily_changes(df): """ Calculate daily change in case data, ie apply difference operator. """ diff = df.drop(['Date'], axis=1) - df.drop(['Date'], axis=1).shift(1) diff['Date'] = df['Date'] diff = diff.fillna(0) return diff
35f97908c05411ebebdd4c12183f2ae65d5e63bb
650,137
from typing import Counter def mltd(text): """Measure of Lexical Textual Diversity (McCarthy, 2005) From Saulo's description: 1. Start by adding words to a segment until type/token ratio falls to 0.72, then continue at the next segment 2. Measure ratio of tokens/number-of-segments""" seg_n = 0 se...
4d397e7e13cc962f28fb8a851eaf16aed77baca6
650,138
import socket import requests def get_server_ip(get_ip_urls=None): """Returns the IP of this server.""" get_ip_urls = get_ip_urls or ['http://techterminal.net/myip/',] for url in get_ip_urls: ip = requests.get(url).text if not ip == '127.0.0.1': try: assert sock...
31f1f37bd5b1af00eda28b279567f59577bbeed7
650,140
import torch def load_checkpoint(model, optimizer, device, checkpoint_file: str): """Loads a model checkpoint. Params: - model (nn.Module): instantised model to load weights into - optimizer (nn.optim): instantised optimizer to load state into - device (torch.device): device the model is on. -...
d37787c2aa97d86f5118c5d4bb8a36c7b75ad136
650,141
from typing import Optional from pathlib import Path def data_path(fname: Optional[str] = None) -> Path: """Location of data folder or file within.""" prefix = Path(__file__).parent if fname is None: return prefix return prefix / fname
2f47e3a604288ebb57572ab4b085ddad94c6cb4e
650,142
def device_get_from_facts(module, device_name): """ Get device information from CVP facts. Parameters ---------- module : AnsibleModule Ansible module. device_name : string Hostname to search in facts. Returns ------- dict Device facts if found, else None. ...
55549b178f14f665f3c48a4e750be39ca70d61ab
650,143
import ast from typing import Iterable def _query_to_list(val): """Call `ast.literal_eval` to get a list from a query string.""" if val is None: return None try: list_ = ast.literal_eval(val) except (SyntaxError, ValueError): return None if not isinstance(list_, Iterable): ...
ac2aa55bc03ba069025e46c28839d572803b3b7d
650,144
def image_resize(image, resize=None): """ Given an image and resize tuple (w,h), return an image with new size. """ if resize is not None: image = image.resize(resize) return image
d3af9d83cdd96956cffaf12f48763fd0528a696d
650,145
def process_views(df): """Takes a dataframe and quits commas. Parameters ---------- df : The dataframe to search. Returns ------- The dataframe processed. """ df['views'] = df['views'].str.replace(',', '').astype(float) return df
233a27ea67c7205cb1c7cedaf789ac70fbc91cee
650,146
def temperature_trans(air_in, fuel_in, ex_out): """ Convert degree celsius to kelvin. Optional keyword arguments: --------------------------- :param air_in: temperature of air coming in to fuel cell(FC) :param fuel_in: temperature of fuel coming into (FC)/ temperature of refo...
8b53781636062626fa8bfd93fb08ff783809d8ca
650,147
import re def parse_url(url): """Return a tuple of ``(host, port, ssl)`` from the URL specified in the ``url`` parameter. The returned ``ssl`` item is a boolean indicating the use of SSL, and is recognized from the URL scheme (http vs. https). If none of these schemes is specified in the URL, the...
8f3e3f824b3f6d49d95ff883917e70dd3d804766
650,148
def print_dictionary_category(category: str, dict: dict) -> int: """Wrote by: Nicholas Garth 101227727 Returns the number of books in a given category of a given book dictionary. As well prints the list of books in the category >>> print_dictionary_category("Superheroes", load_dataset(readfile('Google_Books...
4469a47cec969f7f0c9865ba073b7821cf441c4f
650,149
def get_bytes_from_gb(size_in_gb): """ Convert size from GB into bytes """ return size_in_gb*(1024*1024*1024)
9bfd7a0791a08a88ad83b388e25030ef8cc2df6b
650,150
def v12_add(*matrices): """Add corresponding numbers in given 2-D matrices.""" matrix_shapes = { tuple(len(r) for r in matrix) for matrix in matrices } if len(set(matrix_shapes)) > 1: raise ValueError("Given matrices are not the same size.") return [ [sum(values) for ...
934dbd82be527f113eeb2eaad01f8c867100a869
650,152
def mib_to_gib(value): """ Returns value in Gib. """ return float(float(value) / 1024.0)
5e6d3d15ab7f98a61805e922d25ab2b8a32f1c6d
650,153
import sys import subprocess import multiprocessing import shlex def build_ref(input_files, output, buffsize=100, aligner="bowtie2", path_to_aligner="", num_procs=1): """ Creates 2 reference files: one with all C's converted to T's, and one...
605d063925c7c89b63219768634756f6a2ec15f7
650,154
import getpass def get_password(): """ Returns JIRA password from the command prompt. """ return getpass.getpass('JIRA Password: ')
0290b9c2a432d4f3477bd1f2b7a93c7d93452f60
650,155
from typing import Any from typing import Callable def static_variable(variable_name: str, initial_value: Any) -> Callable[[Callable], Callable]: """A decorator to add a static variable to a function.""" def decorator(function): setattr(function, variable_name, initial_value) ...
cd1497335e490bfde9a49ec9e2bf46a3033f49ec
650,157
import sys def is_close(actual, expected, buffer=sys.float_info.min): """ :param actual: actual value :param expected: expected value :param buffer: acceptable variation from expected :return: bool """ return abs(actual - expected) < buffer
6a529ba5c340ed4a1edd7cffea7318a72576fe92
650,158
def read_smi_file(file_path): """ Reads a SMILES file. :param file_path: Path to a SMILES file. :return: A list with all the SMILES. """ with open(file_path, "r") as smi_file: return [smi.rstrip().split()[0] for smi in smi_file]
08d744a126814897323b45a4cbe0f4e7e977843c
650,159
def client_server_check(args): """ Check if running in server or in client mode :args: arguments given by user :returns: True if in client mode """ if args.server is True: return False if args.active is False: if args.add is None: if args.clear is False: if ar...
59bec195b9c69a215a7962c7a8519c7c03a58e4c
650,160
def _global_unique_search(lines): """Remove repeated lines so that the entire file is unique. Returns the unique lines. lines: the lines of the file to deduplicate """ unique_lines = [] _idx = {} for line in lines: try: _idx[line] except KeyError: _id...
380ff28df8111810a1a7c1de6f15d32dc581d2bf
650,161
import logging def get_mfa_response(mfa_result): """Extract json from mfa response. :param mfa_result: raw response from mfa api :return verify_mfa: json response from mfa api """ try: verify_mfa = mfa_result.json()["response"] except Exception as parse_error: logging.error( ...
d0cac07246d3d9367ff8cafd941d5c1b6e2f0957
650,163
import six def encode_ascii_xml(x): """Encode a string as fixed-length 7-bit ASCII with XML-encoding for characters outside of 7-bit ASCII. Respect python2 and python3, either unicode or binary. """ if isinstance(x, six.text_type): return x.encode('ascii', 'xmlcharrefreplace') elif is...
2303fc4c4a14984d0f457edb7ef7c2e254775499
650,164
import pwd import os def owner(path): """Return name of owner of file/directory at path""" return pwd.getpwuid(os.stat(path).st_uid).pw_name
5e172ec22b08fbdbec9b26f15a282aba7a44b636
650,165
def get_boolean_from_request(request, key, method='POST'): """ gets the value from request and returns it's boolean state """ value = getattr(request, method).get(key, False) if value == 'False' or value == 'false' or value == '0' or value == 0: value = False elif value: value = True ...
3ff2bbcfb7675bca508e712861672accae663328
650,167
def _change_js_file_import_style(ctx, owner, js_protoc_outputs, style): """ Calls the convert_to_amd tool to convert the generated JS code into AMD modules. """ js_outputs = [] for js_file in js_protoc_outputs: file_path = "/".join([p for p in [ owner.workspace_root, ...
41c89f6897af6667a96cb2a676f56759337639c5
650,168