content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
from datetime import datetime def datetime_serializer(obj): """Convert a datetime object to its string representation for JSON serialization. :param obj: datetime """ if isinstance(obj, datetime): return obj.isoformat()
cbdb7e8d68d2f2485243db24f4083946635ab469
655,542
def compute_turbulence_intensity(mean_col, std_col): """ Compute turbulence intensity Args: mean_col(:obj:`array`): array containing the wind speed mean data; units of m/s std_col(:obj:`array`): array containing the wind speed standard deviation data; units of m/s Returns: :ob...
fc22720b98351006ab09580e2b0155ac76131deb
655,543
def get_data_files(): """Get the data files for the package. """ data_files = [ ('etc/jupyter/jupyter_server_config.d', ['etc/jupyter/jupyter_server_config.d/jupytexpr.json']), ('etc/jupyter/jupyter_notebook_config.d', ['etc/jupyter/jupyter_notebook_config.d/jupytexpr.json']) ] retur...
bc2626fbc5fb3a72637b918a670a720bc57ca3cd
655,544
def readconfig(config, servernum): """Reads cofig file""" fd = open(config, 'r') l = fd.readline() maxnum = int(l.strip().split(' ')[1]) if servernum >= maxnum or servernum < 0: raise Exception('Server number out of range.') d = fd.read() d = d.splitlines() host, port = None,...
3b40430c38120bae6700a0243c72f47e1e26e886
655,545
def get_os(parent, host, port, community): """ This is a plugin to be loaded by Ecks3 return the host operating system info """ oid = (1, 3, 6, 1, 2, 1, 1, 1) # HOST-RESOURCE-MIB::sysDescr data = parent.get_snmp_data(host, port, community, oid, 1) if data: return str(data[0][2]) ...
71e9c45874628cd7a45c33f5247369489d9eb82f
655,546
import os def validate_source_dir(script, directory): """Validate that the source directory exists and it contains the user script. Args: script (str): Script filename. directory (str): Directory containing the source file. Raises: ValueError: If ``directory`` does not exist, is n...
0bc34e3570b6411f57699e7972cbf05a78dc3d69
655,548
def set_pairing_bit_on_device_type(pairing_bit: bool, device_type: int): """ Shifts the pairing bit (True = 1, False = 0) 7 bits to the left and adds the device type """ return (pairing_bit << 7) + device_type
83d5f88c24103ef3086bc1f28e3335e132b053a1
655,550
def make_Alice_and_Bob(config): """ Set Alice and Bob policies / replay / algo etc ... from agent config TO DO : implem default Agent config """ # Alice config.policy_A.required_agent_modules = [ 'actor_A', 'action_noise', 'env', 'replay_buffer_A' ] config.policy_A.module_name = 'p...
34e2eddccc87bc888c38c54fab07acf251846e44
655,552
def bits2str(inp): """ Convert a list of bits into a string. If the number of bits is not a multiple of 8, the last group of bits will be padded with zeros. """ bs = [1<<i for i in range(8)] return ''.join(chr(sum(bv if bit else 0 for bv,bit in zip(bs, inp[i:i+8]))) for i in range(0, len(inp), ...
0babfa6786be16ce78e17affa1086a76739375d2
655,553
def health_check(): """ :return: string "ok" always """ return "ok"
7a9aa9bb1056bcde080772ac7ab288d50f951ffd
655,554
import random def Ui(lo, hi): """Uniformly distributed integer, inclusive limits.""" return random.randint(lo, hi)
f2cd9020ff8297367c387cd14b27cf50e75bb59f
655,555
def ashape(node): """Make sure shape isn't None, that makes relay crash later.""" shp = node.shape assert shp is not None return shp
ce00bb81bed862dea55663b636dd255326d6c6d6
655,556
def get_xpath_for_date_of_available_time_element(day_index: int) -> str: """ The element showing date of the available time is found in the div having the xpath: '/html/body/div[4]/div[2]/div/div[5]/div/div[2]/div[3]/div[N]/span' ^ where N ...
81a3cd1a88c47cfd2cb1b815354ce4a6d2f9dca8
655,557
def cropCenterSquare(img, w=None): """center crop to square""" width, height, _ = img.shape short_dim = min(height, width) img = img[int((width - short_dim) / 2) : int((width + short_dim) / 2), int((height - short_dim) / 2) : int((height + short_dim) / 2)] if w and w <= short_dim: ...
ea86f92769c5029e58f820b1c3e5fa23305ba0b3
655,558
def applyOrderDic(order, aDic): """ Apply order to aList. An order of the form ["a","b","c"] means that the first element should be aDic["a"], and so on. """ if order==[]: return aDic.value() else: return map(lambda v:aDic[v], order)
4850830bfdb9b1ad49885f783b65aa796e79d4a7
655,559
def _get_set_env_var_command(name, value): """Return command to set environment variable on device.""" return ['--env={n}={v}'.format(n=name, v=value)]
af01a35130b1b6e93fe4fc2b1de438108c6f0e08
655,561
def make_dict(table, key_col): """ Given a 2D table (list of lists) and a column index key_col, return a dictionary whose keys are entries of specified column and whose values are lists consisting of the remaining row entries """ table_dict = {} for key in table: table...
b52481a7e930857f62b9572a021dff83fbda5ef2
655,562
import math import numpy def _assort_subvoxels(input_array, shape): """ Rearrange pixels before downsampling a volume, so subvoxels to be combined are in a new fast-moving dimension """ axis_offsets = list() # Enumerates samples to combine in each direction axis_step = list() # Sampling stride in ...
230c1d6f494582a47c01e6123b15346cf9cab23e
655,563
from typing import Any import json def serialize_json(obj: Any) -> str: """Serialize an object to JSON, removing quotes for special strings.""" return json.dumps(obj).replace('"____', "").replace('____"', "")
a9eb1b7aadf05d1b6f588b3d1a260363010eb875
655,564
import re def get_index(part): """ check if the part is, e.g [123] return 123 or None """ index = None match = re.match(r'\[(\d+)\]', part) if match: index = int(match.group(1)) return index
0e554f5f2fdbd4ee2d950401158b334e14ca0b99
655,565
def _vars_dir_for_saved_model( saved_model_path # type: str ): # type: (str) -> str """ Args: saved_model_path: Root directory of a SavedModel on disk Returns the location of the directory where the indicated SavedModel will store its variables checkpoint. """ return saved_model_path + "/va...
231072db4b519f66b5722e175ea45ea814c3de56
655,567
from typing import Set from typing import Callable from typing import Any from typing import Dict def dict_by(keys: Set[str], f: Callable[[str], Any]) -> Dict[str, Any]: """Returns a dictionary with keys equal to the supplied keyset. Each value is the result of applying f to a key in keys. """ return {k: f(k...
d60ba87a0bc3912ea77e1b70a73c301f6813ecb7
655,568
def toX(x, y=None): """ This function is used to load value on Plottable.View :param x: Float value :return: x """ return x
32ff94906aaebf3305b4eb0ad4110838e2d38a08
655,569
import os def get_log_path(region, subregion, paths): """Returns path to log_file for given region/subregion. Parameters --------------------- region : str subregion : str paths : dict Returns --------------------- log_file : str """ region_clean = region.replace('/', '-'...
f221d36920232bda5dc1d323da5e2c75bf29af5f
655,571
import collections def _CalcSamplePositions(sharded_iids, sample_iids): """Return [(iid, shard_key, position_in_shard), ...] for each sample.""" # We keep track of how far index() has scanned in each shard to avoid # starting over at position 0 when looking for the next sample in # the same shard. scan_posi...
bccb6da815cf0a5ac32db30b9dcebfdadb8eb3b0
655,572
import subprocess import sys def _communicate(process, input=None, timeout=None): """subprocess.communicate() which kills subprocess on timeout.""" try: return process.communicate(input=input, timeout=timeout) except subprocess.TimeoutExpired: # kill() was added in Python 3.7. if s...
4ca4b569de2205fadd9d07fe0983a65225f3f727
655,574
from pathlib import Path def remove_root(file_path: str) -> str: """Remove the first directory of a path""" full_path = Path(file_path) relative_path = Path(*full_path.parts[1:]) return str(relative_path)
95dc0f948810f5a50a5c707a499d91c7c2045a4c
655,575
def does_task_have_task_runs(task, task_runs): """ Figure out if at least one task run exists for a given task Faster than get_task_runs() """ task_id = task['id'] for tr in task_runs: if task_id == tr['task_id']: return True else: return False
18cdc1e43fc51d6b2000448a2b3a95f68a741fb7
655,576
import torch def swish(x): """ Simple implementation of Swish activation function https://arxiv.org/pdf/1710.05941.pdf """ return x * torch.sigmoid(x)
68d3936d06c2cd8fda47df2bbc5d4d7b83aa3b06
655,577
import re def get_contig_lengths(sam_filename): """ Return a dictionary of contig names => contig lengths from a SAM file. Args: sam_filename: input SAM filename. Returns: Dictionary of contig names => contig lengths. """ sam_file = open(sam_filename, 'r') # Build dicti...
6042bae80a45520d261dc203af7c23cf8e453b6e
655,578
from pathlib import Path def get_definitions(base_directory_path): """ For given directory return all *_definition.py files in it and its subdirectories. """ return Path(base_directory_path).glob('**/*_definition.py')
08c63b778112f7d1ec2de806e6c94334b00f943f
655,579
import os def _get_full_param_path(file): """Get full path to parameter file.""" # this would be the standard file location (from the package) file_std = os.path.abspath(os.path.join(__file__, "../../param", file)) # this file would be the relative location file_custom = os.path.abspath(file) ...
b3a664d50ff547d88c9ff5d0a39f4be6ac7e8e48
655,581
import os def isTestFile(filename): """ Returns true if 'filename' looks like a file containing unit tests. False otherwise. Doesn't care whether filename exists. """ basename = os.path.basename(filename) return (basename.startswith('test_') and os.path.splitext(basename)[1] == ('...
a6ae3305ed1333ceebc9fcd73b0f3eefae518a8d
655,582
def overplot_lines(ax, linelabels, lineloc): """ Overplots emission lines on an already existing plot with axes Input: ax: matplolib axis linelabels: list of latex formatted names for the lines lineloc: list of wavelengths of the lines (most likely in Ang) Output: ax2: re...
d82f24ad9366defafc11e2d3ac7739659dcf1a04
655,583
def backToMenu(): """ A simple function that returns a boolean depending if you want to go back to the menu or not. """ while True: try: back = int(input("\nBack to Menu?\nNo [0]\nYes [1]\n")) except ValueError: print("Incorrect input, try again."); continue ...
658c8ac73542c9216518802d99a08cd918f9a147
655,584
def internet_access_by_households(): """ OFCOM NATIONS & REGIONS TECHNOLOGY TRACKER - 2019. 3rd January to 28th February 2019 https://www.ofcom.org.uk/__data/assets/pdf_file/0026/143981/technology-tracker-2019-uk-data-tables.pdf internet_access: p363 / 364, Table 52 """ return { 'i...
fe4b81696a91d5ae73b405ed2272063871a46a07
655,585
def processing_step1(data): """ 1. Remove outliers 2. Add avg. temperature, charge and capacity 3. Aggregate to hourly samples args: raw dataframe returns: transformed dataframe """ df = data print("Processing Raw Dataframe\n") print("Column names and datatypes:", df.dtypes, se...
a16e6e2360252a2e6b72fc34f71f052a647a4dc8
655,586
def convert(size, box, class_id): """归一化box坐标,符合yolo3格式""" dw = 1. / size[0] dh = 1. / size[1] x = (box[0] + box[2]) / 2.0 # x的中心点 y = (box[1] + box[3]) / 2.0 # 中心点y w = box[2] - box[0] h = box[3] - box[1] x = x * dw w = w * dw y = y * dh h = h * dh return class_id, x, ...
bba81b900019708b4ca56d93085d5d983bcdabe6
655,587
def marc21(): """marc21 record.""" return { "xml": "<record><controlfield tag='001'>990079940640203331</controlfield> \ <controlfield tag='003'>AT-OBV</controlfield> \ <controlfield tag='005'>20170703041800.0</controlfield>\ <controlfield tag='007'>cr</controlfield>\ <control...
770b0c0a3f55bc9d9f39ea66b95ce3e4115d74df
655,588
import numpy def zero(data): """ Given a signal, zero it out by finding a best fit curve and subtracting out the average value of the signal. """ result = [] [m, b] = numpy.polyfit(list(range(0, len(data))), data, 1) for i in range(0, len(data)): result.append(data[i] - m * i + b)...
d34cafe81b8d080c640d22dfcee206765ce94cb5
655,589
import re def remove_chars(text, chars, replace_with=None): """ Removes chars from text or replaces them with the input. Also removes any extra whitespaces which might have been introduced. : param text : text upon which the processing is done : param chars : chars to search fo...
074581e6ce3a45440d7822d1018ad19e0d98be2a
655,590
import os def format_paths(mydict): """ Ensure that paths have a standardized format before being allowed into an active working environment. Expands tilde character (~) in path strings and expands absolute paths :type mydict: dict :param mydict: dictionary of paths to be expanded :rtype:...
42bc9d8281a97499a0e1c4ea85e193f8e6b67d42
655,591
def myreadlines(self): """Read and return the list of all logical lines using readline.""" lines = [] while True: line = self.readline() if not line: return lines else: lines.append(line)
ca0693ef7073588883e7537a3b588cd4b07b3597
655,592
def common_superclass_wnid(group_name): """ Get WordNet IDs of common superclasses. Args: group_name (str): Name of group Returns: superclass_wnid (list): List of WordNet IDs of superclasses """ common_groups = { # ancestor_wnid = 'n0000425...
3a8eab12790f761a382dbfda2443818a578822f9
655,593
def suma_serie(n: int) -> int: """Suma los elementos de la serie E_i = i^3 + 5, desde 1 hasta n. :param n: número de elementos de la serie :n type: int :return: suma de los elementos de la serie :rtype: int """ if n == 1: return 6 else: return (n ** 3 + 5) + suma_ser...
a876e7c274f7f390da3575733944a10a8a17bf8c
655,594
def NonsfiLoaderArch(target): """Returns the arch for the nonsfi_loader""" arch_map = { 'arm32' : 'arm', 'x8632' : 'x86-32', 'mips32' : 'mips32', } return arch_map[target]
39d5ebc6839e57d2c052d702b052418a262d8edf
655,595
def tree_unflatten(flat): """Nest depth-1 tree to nested tree {'a.b.c': x} -> {'a': {'b': {'c': x}}} """ def recursion(k, v, out): k, *rest = k.split('.', 1) if rest: recursion(rest[0], v, out.setdefault(k, {})) else: out[k] = v d = {} for k, ...
db66f3cf55e7f6d1ec247d4643226188bc793a6d
655,596
import argparse def parameter_parser(): """ A method to parse up command line parameters. By default it gives an embedding of the Facebook tvshow network. The default hyperparameters give a good quality representation and good candidate cluster means without grid search. """ parser = argparse.Ar...
4988297b8666acab7b4d9a250ecb66efa99c8776
655,598
def get_ali(filename): """#{{{ load label file and transform to dict """ lf = open(filename, 'r') labels = {} ali_keylist = [] value = [] while(1): line = lf.readline() if not line: # print 'end of file' break line_split = line.strip()....
d77779eb64c5761d63cd471596e6e287241e43f5
655,599
def sum_pairs(nums, goal): """Return tuple of first pair of nums that sum to goal. For example: >>> sum_pairs([1, 2, 2, 10], 4) (2, 2) (4, 2) sum to 6, and come before (5, 1): >>> sum_pairs([4, 2, 10, 5, 1], 6) # (4, 2) (4, 2) (4, 3) sum to 7, and finish before (5, 2): ...
be621cbe00b8e30633fc4daf34c15678f307fd88
655,600
def cipher_bytes(cipher: str) -> str: """ :param cipher: :return: """ if cipher == "": return "00" list_bytes = [b"\x00\x04", b"\x00\x05", b"\x00\x07", b"\x00\x0a", b"\x00\x16", b"\x00\x2f", b"\x00\x33", b"\x00\x35", b"\x00\x39", b"\x00\x3c", b"\x00\x3d", b"\x00\x41", b"\x00\x45", b"\x0...
3e2189591d803d97f7735ac763ac97c0c0031923
655,601
def linear_derivative(z): """Linear activation function derivative""" return 1
9e8dd4cdbb54d0ddfa90a375a4b539706db9d0e9
655,602
def magnitude(v): """Finds the magnitude of a binary vector (array). Args: v: A binary vector (array). Returns: The magnitude of the vector. """ sum = 0 for x in v: sum += x return sum
9f084f4362a7f5550f6ebeb5cea42e5d6012c5aa
655,603
def _season_overflow(season, moved_year, now): """Pushes illegal seasons ints into the next/previous year.""" if season > 4: while season > 4: if moved_year is None: moved_year = now.year + 1 else: moved_year += 1 season -= 5 elif ...
086b3a54700cc0aa447499ffedf33a58e32173c7
655,604
def get_slope(vector_one, vector_two): """Get the slope of a line specified by two vectors""" return(vector_two[1] - vector_one[1])/(vector_two[0] - vector_one[0])
2d20b5fe0fe3734fb66b0b2fc7a3a7aee2811694
655,605
import os def format_path(file: str) -> str: """Format a path according to the systems separator.""" return os.path.abspath([file.replace('/', os.path.sep)][0])
17030c8708a9b694d10cc7de0522487454205df7
655,606
import random def get_action_sequence_bulldozer(): """ Specify the action sequence for Bulldozer, the scripted lumberjack. """ action_sequence_bulldozer = [] action_sequence_bulldozer += [''] * 100 # wait 5 secs action_sequence_bulldozer += ['camera:[10,0]'] * 3 # look down 30 degrees f...
e2adc186b6405413cda00436435c32c50a217dd8
655,607
import itertools def find_anagrams(word, dictionary): """Find all anagrams for a word. This function only runs as fast as the test for membership in the 'dictionary' container. It will be slow if the dictionary is a list and fast if it's a set. Args: word: String of the target word. ...
a7b7f32e673858124ef2ab63284387fdc1d077d2
655,608
def count_on_screen(screen, wanted): """Count occurrences of wanted on the screen.""" return list(screen.values()).count(wanted)
49a0fc0773139e3279de5b19d0e26bcfb1e722a5
655,609
import subprocess def test_call(*args, **kwargs): """ Test whether a subprocess call succeeds. """ try: subprocess.check_output(*args, **kwargs, timeout=10) return True except Exception: return False
f593bbe98ee451a621a570aa7dd2ed7b177b8b40
655,610
def googlenet_params(model_name): """ Map VGGNet model name to parameter coefficients. """ params_dict = { # Coefficients: aux_logits, transform_input, blocks, image_size "googlenet": (True, True, None, 224), } return params_dict[model_name]
e7a3320b1dbc118569e12ec736c7faa4843d3338
655,612
import re import glob import os def get_direct_sub_files(path, abs_path=False, extension=re.compile("\..*")): """ Gets the direct child sub-files of the given directory Args: path: Absolute path to the directory abs_path: If set to True, it returns a list of absolute paths to the sub-files...
bc1a54b4a295ee48e3db32d2a08eaa66a23c3855
655,613
import os def check_path(data_pointer, msg): """Check that the path exists.""" if not os.path.exists(data_pointer): print(msg) return False else: return data_pointer
c55bfb884b1971e04862a5f5bbcfe59956e82a14
655,614
import hashlib def make_merkle(blob_name: str) -> str: """Creates a "merkle" by hashing the blob_name to get a unique value. """ m = hashlib.sha256() m.update(blob_name.encode("utf-8")) return m.hexdigest()
1f61b235746e8ae34fe1e0b24e6d141d99517b64
655,615
def blosum50(file): """This function takes a file as input and generates a dictionary with the blosum matrix""" blosum=[] for line in file: line=line.rstrip() line=line.split() blosum.append(line) file.close() for list in blosum[1:]: for i in range(1,len(list)): ...
6f299c6f674fe7917a8215315cda1e03cb7c4436
655,616
import math def pi_archimedes(n): """ Calculate n iterations of Archimedes PI recurrence relation """ polygon_edge_length_squared = 2.0 polygon_sides = 4 for i in range(n): polygon_edge_length_squared = 2 - 2 * math.sqrt(1 - polygon_edge_length_squared / 4) polygon_sides *= 2 ...
a6610649b71d304894e3acd57f9b83462b416e4b
655,617
def _get_query_parameters(module_params): """Builds query parameter. :return: dict :example: {"$filter": Name eq 'template name'} """ system_query_param = module_params.get("system_query_options") query_param = {} if system_query_param: query_param = dict([("$" + k, v) for k, v in s...
42f98957b3de2661f36a15fd768a6c10b1a62615
655,618
def pipes(stream, *transformers): """Pipe several transformers end to end.""" for transformer in transformers: stream = stream.pipe(transformer) return stream
93e0ae105e03500d9cb912f900384457910eea72
655,619
def dive_k(tree, k): """ diving in k levels and return city names of nodes Args: tree (dict): binary tree with keys (city, ...) k (int): describes how many levels to dive Returns: [string]: all city names for given levels """ roots = "{0}".format(tree["city"]) if k == 1:...
bdddc53ab3900493e9a65e0a489ef12f75b0d600
655,620
import re def get_num_cpus(headers): """Get the number of CPUs from the system.cpu header property. As the CPU utilization graphs are relative, the number of CPUs currently makes no difference.""" if headers is None: return 1 if headers.get("system.cpu.num"): return max (int (heade...
bea60f4a5ac176a4bdabcd6f7830e2ce06400f1a
655,622
def build() -> str: """ Returns current build version :return: """ return "0.1"
b2e9d4bec6897afcea70c6324838f14ed081fa36
655,623
import math def sigmoid_function(x): """ Calculate the sigmoid value of the inputs Parameters: X: values Return value: the sigmoid value """ return 1 / (1 + math.e**(-x))
4d0c455e2e21f4a800db3d12df49413013c81fea
655,624
def pad_sentence_batch(sentence_batch, pad_int): """Pad char seq with <PAD> so that each char sequence of a batch has the same length""" max_seq = max([len(seq) for seq in sentence_batch]) padded_batch=[] for seq in sentence_batch: temp=[] for char in seq: temp.append(char) ...
80466026bb0d422984c6eff40c62f65be16b51fa
655,625
def mergeRegisters(*qregs): """ Returns a single register containing all the qubits (or cbits) from multiple registers """ bigReg = [] for qreg in qregs: bigReg += [q for q in qreg] return bigReg
30daf1677511881d7df81801183f8d27e4f3e5b8
655,627
def user_menu(user): """Меню для авторизованных пользователей""" if user is not None: user_menu = [{"name": "Моя страница", "url": f"/profile/{user}/"}, {"name": "Мой вес", "url": f"/profile/{user}/weight/"}, {"name": "Добавить вес", "url": "/add/"}, ...
fb71d6521edc74a86421bdcf3a0459cf642edc00
655,628
def moveIntToBoolList(i): """ Convert an integer in the range [0, 7] to a list of 3 boolean values, corresponding to the binary representation :param i: The integer :return: The list of 3 boolean values """ # not using loops or append because this is faster, and this method only needs to work fo...
c150231abc31db538caa8df583c0389aadc38ce9
655,629
import sys def msgevalgen(pattern): """ Generates a function that returns the relevant field (aka 'subtopic') of a Message object :param pattern: subtopic, e.g. /x. Must have a leading '/' if specified, ``str`` :returns: function that converts a message into the desired value, ``fn(Message) -> value``...
c8944b2962deabb68cf25f0b63ed1126819f5f54
655,630
import itertools def Kartezijev_produkt(*skupovi): """Skup uređenih n-torki.""" return set(itertools.product(*skupovi))
4f207001115bf56859dfd532a9ca2367c1fb44f2
655,631
from typing import Mapping from typing import Set def preimage(x, d: Mapping) -> Set: """Find preimage of x in d""" p = {key for key, value in d.items() if value == x} if len(p) == 0: raise ValueError(f"No values for {x} found in dictionary {d}") return p
dfd452a96ba159dbd2aa54242154cf01c5789f17
655,632
def fix_read_order_keys(key, start_value=7): """fix reading restored ckpt order_dict keys, by Hao.""" return key[start_value:]
bde6a46029f20c3a8022dbe6d2bded6135333b35
655,633
import re def get_sql_statement_sep(): """ Returns SQL statement separator regex. Default is '--run' on its own line. """ return re.compile('^\s*--\s*run\s*$', flags=re.MULTILINE|re.IGNORECASE)
5c5dde1c6fd780b027bf72363b4d6144c1e62a1f
655,634
def as_text(value): """Returns the string representation of given value Arguments: value {any} -- Value to get the string representation for Returns: stringified text {String} -- String representation of given value """ return "" if value is None else str(value)
bf44d8dfb5878f8ff35239fe22b5c5558a6312f9
655,635
def isHole(ring): """# problem due to inverted Tkinker canvas, so i do opposite of below: Checks to see if points are in counterclockwise order which denotes a inner ring of a polygon that has a donut-like shape or a hole such as a lake etc. Argument: ring - a list of tuples denoting x,y c...
cc43a856dd78ba9bf3da4ced63f5099ac3ed2209
655,638
import random def gen_mac(last_octet=None): """Generate a random MAC address that is in the qemu OUI space and that has the given last octet. """ return "52:54:00:%02x:%02x:%02x" % ( random.randint(0x00, 0xFF), random.randint(0x00, 0xFF), last_octet, )
66ebfc64ebd2851e0cefab3a5cab2c60a4943ec5
655,639
def safe_division(dividend: float, divisor: float) -> float: """Checks to make sure no divide by 0 error""" if divisor == 0: return 0 else: return dividend / divisor
3e3a9aa6b53bba03f8f3053ea35d3989cd3288f0
655,640
def user_privileges(connection): """Get the list of privileges for the authenticated user. The response includes the name, ID, and description of each privilege and specifies which projects the privileges are valid for. Args: connection: MicroStrategy REST API connection object Returns: ...
74cc492f0d56714c7e3ccb7cb0822b22a9344a94
655,642
def combine_first_last_name(df): """ Combine first and last name if df has those columns. """ if 'first_name' in df.columns and 'last_name' in df.columns: df['full_name'] = df['first_name'] + ' ' + df['last_name'] df.drop(['first_name', 'last_name'], axis=1, inplace=True) return df
ae10f70b86c485e0ed65cbdb44036f03b485250a
655,644
import os import shutil import re def linkFile(src, dest): """Link src file to destination. Return True upon success.""" if os.path.isdir(dest): dest = os.path.abspath(os.path.join(dest, os.path.basename(src))) try: os.link(src, dest) except: try: os.symlink(src, ...
5911f9962b478de9ce349561ac9a41b2f0afbb33
655,645
def min_if_exist(n1, n2): """ Returns the minimum between two numbers, or the only defined number (in case the other is `None`) or `None` if none of the numbers are defined. """ if n1 is None and n2 is None: return None elif n1 is None: return n2 elif n2 is None: retu...
e50092db053254c6b4f0d1ae284b0d49b21a392b
655,646
import hashlib def generate_identifier(metadata: str) -> str: """Generate a (hopefully) unique identifier.""" obj = hashlib.md5(metadata.encode()) dig = obj.hexdigest() return str(int(dig[:6], 16))
bdd9f7bf0323f28d78bfbb1072a0b31189091fff
655,647
def mse_func(target, mse_input): """Return error of interpolation. This function returns eval_numeric()the mean squared error for two sequences of numeric values. """ counter = 0 error = [] while counter < len(target): error.append((abs(target[counter]-mse_input[counter]))**2) ...
44e1ac3aedd09dc02c57aca789316cb6d2904552
655,648
def getmainwindow(win): """ win : QWidget Return the QMainWindow that is in `win` ancestors list, if found. """ parent = win while parent is not None: if parent.inherits('QMainWindow'): return parent parent = parent.parent() raise RuntimeError('Count not find QMa...
59b3f3f66adbc9c8ac1b4e22eba6516d0d738b1f
655,649
def calc_kinetic_energy(ux, uz, xp, params): """ Calculates the kinetic energy from velocity Args: ux (np.ndarray): x-velocity uz (np.ndarray): z-velocity xp (module): numpy module params (Parameters): parameters Returns: float: kinetic energy """ nx, n...
33628b601bf1f1dc02381437780888fb2f12dbde
655,650
import re def check_global_attr_against_regex(ds, attr, regex): """ Returns 0 if attribute `attr` not found, 1 if found but doesn't match and 2 if found and matches `regex`. :param ds: netCDF4 Dataset object :param attr: global attribute name [string] :regex: a regular expression definition [...
66ada65616c8e6bb713a4e17dfa5298a2f332ae9
655,651
def num_unique_words(stanza_doc): """Returns the number of unique words Args: stanza_doc (nltk.Tree): The dependency parse tree Returns: number of unique words """ return len(set([word.text for word in stanza_doc.sentences[0].words]))
78d097e94f9fb58b7805731b73d20ce8b0ff7fa3
655,652
import struct import base64 def read_line(line): """read line""" m_id, image_search_rank, image_url, page_url, face_id, face_rectangle, face_data = line.split("\t") rect = struct.unpack("ffff", base64.b64decode(face_rectangle)) result = { 'm_id': m_id, 'image_search_rank': image_search...
6045cade03b0e552616f76c0a997f170046a7402
655,653
def ordinal(n, combine=False): """ Return the ordinal of the number n. If combine then return the number concatenated with the ordinal """ number_string = str(n) if combine else "" special_cases = {1: "st", 2: "nd", 3: "rd"} if not 10 <= n % 100 <= 20 and n % 10 in special_cases: re...
9c2ceaff2f1f9b7d1d0ac3ff4951a65c9c4afae6
655,654
def npieces(request): """Number of collocation pieces.""" return request.param
c98349245b5d846ff45e295e70898a2b36429efc
655,655
def normalize(word): """Helper function for comparing words for anagram-ness""" return sorted(word)
2852ebf056ec61fabdc84d7f4a1d6236474bcb03
655,656
def apply_op(input_layer, operation, *op_args, **op_kwargs): """Applies the given operation to this before without adding any summaries. Args: input_layer: The input layer for this op. operation: An operation that takes a tensor and the supplied args. *op_args: Extra arguments for operation. **op_k...
9c1b47180772689ea2bc5316b35765823b6ea2e8
655,657