content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def spectral_projection(u, eigenpairs): """ Returns the coefficients of each eigenvector in a projection of the vector u onto the normalized eigenvectors which are contained in eigenpairs. eigenpairs should be a list of two objects. The first is a list of eigenvalues and the second a list ...
2b877e2e9a606c449b38101e1a23504bff999409
699,727
def _get_native_location(name): # type: (str) -> str """ Fetches the location of a native MacOS library. :param name: The name of the library to be loaded. :return: The location of the library on a MacOS filesystem. """ return '/System/Library/Frameworks/{0}.framework/{0}'.format(name)
53cb9ac2a771883b791a111e53e23bd77c08f43b
699,728
def ra2float(ra): """ Convert ra to degress (float). ra can be given as a time string, HH:MM:SS.SS or as string like '25.6554' or (trivially) as a float. An exception is thrown if ra is invalid 360 deg = 24 hrs, 360/24 = 15 """ if ra is None: return ra if type(ra) is float or...
d16e1163f9e821fdff4344eacf7c29b08a8ba266
699,729
def split_unknown_args(argv: list[str]) -> tuple[list[str], list[str]]: """Separate known command-line arguments from unknown one. Unknown arguments are separated from known arguments by the special **--** argument. :param argv: command-line arguments :return: tuple (known_args, unknown_args) ""...
14e6f202e105cb1001563e9a5a5fc1c5f4bd9fd0
699,730
def season_validation(season): """ Decide if the season inputs are valid then return valid inputs. Parameters: season(str): A user's inputs to the season factor. Return: (str): Valid strings without commas or spaces or characters. """ def is_valid_digit(season): ...
8633c7a1a39103daa212a227317a7d147c3a4bb3
699,731
def byte_to_megabyte(byte): """ Convert byte value to megabyte """ return byte / (1024.0 ** 2)
1b410bcec539e3946a7b5751b984758f89a7ed96
699,732
import string def decode(digits, base): """Decode given digits in given base to number in base 10. digits: str -- string representation of number (in given base) base: int -- base of given number return: int -- integer representation of number (in base 10)""" # Handle up to base 36 [0-9a-z] as...
febdf9973a73de5b3686a20b8c2a5738391a815e
699,734
import argparse def parseArgs(): """Parse script parameters and return its values.""" parser = argparse.ArgumentParser( description="Social Media Profile Cross Reference Tool.") parser.add_argument("-i", help="input csv file with emails", required=Tr...
a3697b1d90f4cd868aac0f085f8a41674b729855
699,735
def pass_args(args): """Possible argument to attr_handler()""" return args
5681a5f80c1f01bcae099d4baaf7fb07785c5983
699,736
def least_significan_bit(n): """Least significant bit of a number num AND -num = LSB Args: n ([type]): [description] Raises: TypeError: [description] Returns: [type]: [description] """ if type(n) != int: raise TypeError("Number must be Integer.") if...
5fcde70104f885eeb753697fb74d8ec2e7156eae
699,737
def is_k_anonymous(df,partition,sensitive_column,k =3): """ params df: The dataframe on which to check the partition. partition: The partition of the dataframe to check. sensitive_column: The name of the sensitive column k: The desired k returns True if the partition...
e58ae8f65524c8a9f7b404d391c2b1d3d0b188c2
699,738
def normalize_variant(variant: str) -> str: """ Normalize variant. Reformat variant replace colons as separators to underscore. chromosome:position:reference:alternative to chromosome_position_reference_alternative :param variant: string representation of variant :return: reformat...
2dc97b7f7b09add6a8062db94376c1ab030ff07c
699,739
from typing import Tuple def compute_limits( numdata: int, numblocks: int, blocksize: int, blockn: int ) -> Tuple[int, ...]: """Generates the limit of indices corresponding to a specific block. It takes into account the non-exact divisibility of numdata into numblocks letting the last block to take th...
748344d60baa8f2ecd31ce822c0e33aca981bc13
699,740
import json def getToken(response): """ Get the tokenised card reference from the API response :param response: Response object in JSON :return: String - token """ resp_dict = json.loads(response.text) try: token = resp_dict["token"] except KeyError: print('Retrieval ...
b849f3b021b995b164b99690a82ecabf881bb18b
699,741
def _read_transition_statistics_from_files(model, verbose): """Parses the transitions statistics from the simulation output files for later analysis Parameters ------- model : obj object containing all anchor and milestone information Returns --------- total_steps : int total number ...
1a4f326bd628e6ddd9475c9610b92cb2ba564bba
699,742
def createSubsetGafDict(subset, gafDict): """ Generates a dictionary that maps the subset's Uniprot ACs to the GO IDs, based on the provided gene subset and the gaf dictionary. Parameters ---------- subset : set of str A subset of Uniprot ACs of interest. gafDict : dict of str mappi...
76e69cd79c984a19254df171403c008405276408
699,743
def shortest_paths(graph, vertex_key): """Uses Dijkstra's algorithm to find the shortest path from `vertex_key` to all other vertices. If we have no lengths, then each edge has length 1. :return: `(lengths, prevs)` where `lengths` is a dictionary from key to length. A length of -1 means t...
f2ac9abf9292364099748475988d4ee1dbeb4b23
699,744
def process_overall_mode_choice(mode_choice_data): """Processing and reorganizing the data in a dataframe ready for plotting Parameters ---------- mode_choice_data: pandas DataFrame From the `modeChoice.csv` input file (located in the output directory of the simulation) Returns ------...
870685017d223f8a277265f80eea56e50eedec90
699,745
def flatten_datasets(rel_datasets): """Take a dictionary of relations, and returns them in tuple format.""" flattened_datasets = [[], [], []] for kind in rel_datasets.keys(): for i in range(0, 3): for rel in rel_datasets[kind][i]: flattened_datasets[i].append([*rel, kind]...
70affa370a98c8328effed0bdb015999c5874913
699,746
import torch def log_sum_exp(x, dim=None): """Log-sum-exp trick implementation""" x_max, _ = torch.max(x, dim=dim, keepdim=True) x_log = torch.log(torch.sum(torch.exp(x - x_max), dim=dim, keepdim=True)) return x_log+x_max
45b1f6d198569567d3284bab4116a4703b0589a3
699,747
def nb_year(p0, percent, aug, p): """ Finds the amount of years required for the population to reach a desired amount. :param p0: integer of starting population. :param percent: float of percent increase per year. :param aug: integer of new inhabitants. :param p: integer of desired population. ...
054496347fc8bedca3424143d48d122712dd1363
699,748
def tshark_read( device, capture_file, packet_details=False, filter_str=None, timeout=60, rm_file=True, ): """Read the packets via tshark :param device: lan or wan... :type device: Object :param capture_file: Filename in which the packets were captured :type capture_file: St...
8fc31098e750691a1aa7c27a868abf0d6254adec
699,749
def resize_image(img): """resize images prior to utilizing in trianing model""" width, height = img.size ratio = width/height new_height = 100 new_width = int(new_height*ratio) img = img.resize((new_width, new_height)) return img
1aa0164e1e25ef0f22e55a15a654fda2dfef5b12
699,750
def _filter_calibration(time_field, items, start, stop): """filter calibration data based on time stamp range [ns]""" if len(items) == 0: return [] def timestamp(x): return x[time_field] items = sorted(items, key=timestamp) calibration_items = [x for x in items if start < timestam...
c7575ec85c7da9f1872150a1da3d7b02718df8a0
699,751
import torch def phi_inv(D): """ Inverse of the reallification phi""" AB,_ = torch.chunk(D,2,dim=0) A,B = torch.chunk(AB,2,dim=1) return torch.stack([A,B],dim=len(D.shape))
b8198764b89f3f1261e96014697cf1346e1c7d43
699,752
import os def is_created(): """ Checks to see if ginger new command has already been run on dir """ return os.path.isfile(os.getcwd()+'/_config.yaml')
3a91185bd5c17d659e8cd30bf57c781c6a657092
699,753
import argparse def read_param() -> dict: """ read parameters from terminal """ parser = argparse.ArgumentParser() parser.add_argument( "--ScreenType", help="type of screen ['enrichment'/'depletion']", type=str, choices=["enrichment", "depletion"] ) parser.add_argument("--LibFilen...
5efb8419266b34807b286a411cfd36365c66c628
699,754
def Get_foregroundapp(device): """Return the foreground app""" return device.shell("dumpsys activity recents | grep 'Recent #0' | cut -d= -f2 | sed 's| .*||' | cut -d '/' -f1").strip()
236986e3d08f6a4c7dd4cd8c8441806d25e76654
699,755
def chunk_size(request): """ Set the chunk size for the source (or None to use the default). """ return request.param
c57269f434790953d475a2791c862d70d204ed86
699,756
from datetime import datetime def isoformat(dt: datetime) -> str: """ISO format datetime object with max precision limited to seconds. Args: dt: datatime object to be formatted Returns: ISO 8601 formatted string """ # IMPORTANT should the format be ever changed, be sure to updat...
679ce7aa71ab30e4c78a0953272c17f487714177
699,758
import sqlite3 import os def get_db_cache(cache_dir: str) -> sqlite3.Connection: """ Open cache and return sqlite3 connection Table is created if it does not exists """ cache_file = os.path.join(cache_dir, "cache.sqlite3") conn = sqlite3.connect(cache_file) cursor = conn.cursor() curso...
7dd6a909ba210a261196ddd1273795d76a27464a
699,759
def _recursive_namedtuple_convert(data): """ Recursively converts the named tuples in the given object to dictionaries :param data: An object in a named tuple or its children :return: The converted object """ if isinstance(data, list): # List return [_recursive_namedtuple_conver...
292bc249b056c14eb1c700561d366ff4e6e64a10
699,760
def _find_start(score_matrix, align_globally): """Return a list of starting points (score, (row, col)). Indicating every possible place to start the tracebacks. """ nrows, ncols = len(score_matrix), len(score_matrix[0]) # In this implementation of the global algorithm, the start will always be ...
361a1ea87ecf9bbef0950521ed0fdcfd70b7b608
699,761
def get_f1_score(precision, recall): """ Calculate and return F1 score :param precision: precision score :param recall: recall score :return: F1 score """ return (2 * (precision * recall)) / (precision + recall)
e94dd20acac443be9856b9dbb43adf2ead2e0ba5
699,762
def bh2u(x: bytes) -> str: """ str with hex representation of a bytes-like object >>> x = bytes((1, 2, 10)) >>> bh2u(x) '01020A' """ return x.hex()
8ab7bf9b536d13a1944e014ea83a4302917c2306
699,763
def vis_FasterRCNN_loss(self, scale_weight): """ Calculate the roi losses for faster rcnn. Args: -- self: FastRCNNOutputs. -- scale_weight: the weight for loss from different scale. Returns: -- losses. """ return{ "loss_cls": self.vis_softmax_cross_entropy_loss_(scale_weigh...
5832d7f28179085db939a7bd624e9ffb08461fe4
699,764
from typing import List from functools import reduce def decode(obs: int, spaces: List[int]) -> List[int]: """ Decode an observation from a list of gym.Discrete spaces in a list of integers. It assumes that obs has been encoded by using the 'utils.encode' function. :param obs: the encoded observation ...
6c3c1348776b7b164cf70a5bfa9da3e8b53a280f
699,765
def anagram_solution_1(words): """ Complexity O(n2) If it is possible to “checkoff” each character, then the two strings must be anagrams :param words: Tuple :return: bool """ s1, s2 = words still_ok = True if len(s1) != len(s2): still_ok = False a_list = list(s2) po...
942ef7bb631bd803d89e71643e994505cb9b827a
699,766
import re def empty_template(pattern, template): """F() to extract all {words} from the template using pattern""" template = re.sub(pattern, "{}", template) return template
b62592a449ce38971cc81083928cfd034be1984b
699,767
import pickle def read_pickle(file_name): """Reload the dataset""" with open (file_name,'rb') as file: return pickle.load(file)
404d578de68db726e14f6214aed3e512a9abf947
699,768
import re def duration_to_seconds(duration): """ Convert duration string to seconds :param duration: as string (either 00:00 or 00:00:00) :return: duration in seconds :class:`int` or None if it's in the wrong format """ if not re.match("^\\d\\d:\\d\\d(:\\d\\d)?$", duration): return Non...
25340e85fdc2db03eaa65aba60a158f951da389a
699,769
def flatten_tests(test_classes): """ >>> test_classes = {x: [x] for x in range(5)} >>> flatten_tests(test_classes) [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)] >>> test_classes = {x: [x + 1, x + 2] for x in range(2)} >>> flatten_tests(test_classes) [(0, 1), (0, 2), (1, 2), (1, 3)] """ te...
332b98ab499ff53ba974d51ac862e7015f616e64
699,770
def clues_too_many(text: str) -> bool: """ Check for any "too many connections" clues in the response code """ text = text.lower() for clue in ("exceed", "connections", "too many", "threads", "limit"): # Not 'download limit exceeded' error if (clue in text) and ("download" not in text) and (...
0d105985d7eb032668ad8b08704658846da725b7
699,771
def load_vocab(filename: str): """ load vocabulary from given dataset file """ with open(filename, 'r', encoding='utf-8') as f: text = f.read().strip().split('\n') text = [word.split(' ') for word in text] vocab_dict = {word[0]: word[1:] for word in text} vocab_dict = {k: [float(d) f...
fe11e129439173ba13ca276c788c0f27053f5e6a
699,773
import re def normalize_whitespace(s: str) -> str: """Convert all whitespace (tabs, newlines, etc) into spaces.""" return re.sub(r"\s+", " ", s, flags=re.MULTILINE)
6d8b65bcdca9838aa0f4d16d158db5d2218cbf24
699,774
import os import glob def find_granule_metafiles_in_SAFE(inSAFE, tile_glob_pattern='*', tile_name=None): """Find granule metadata files in SAFE Paramters --------- inSAFE : str path to .SAFE folder tile_glob_pattern : str, optional granule glob search pattern e.g. '32???' ...
8aed455fd01e9b74ec870ad6e4646521bc4cbe40
699,775
def set_dist_names(spc_dct_i, saddle): """ Set various things needed for TSs """ dist_names = [] if saddle: dist_names = [] mig = 'migration' in spc_dct_i['class'] elm = 'elimination' in spc_dct_i['class'] if mig or elm: dist_names.append(spc_dct_i['dist_info...
cb5f72b3d00efb8272f7b5012f776bbd63e38634
699,776
def fit_loss(ac, fit): """Loss of the fit """ r = ac - fit error = sum(r ** 2) / sum(ac ** 2) return error
00d41891dea7d914299d87d971fb2a41df2109ed
699,777
def growth_pos_check(clods, pos): """for checking the position of a growing seed tip Like position_calc but amended for growing seed each time the seed grows there is a cheek for clod collisions :param clods: All the clod objects in the bed :param pos: The proposed position of the seed tip :retu...
743455907cc81dc3950db202b4f23a79c1eafd33
699,778
def determine_letter(current_score): """ Calculates the letter grade for a given score :param current_score: the score to be evaluated :return: the letter grade that score falls within """ if current_score >= 90: return "A" elif current_score >= 80: return "B" elif curren...
324aaa8e28a0cbc298410ecd83ea4eee6d39a970
699,779
from typing import Tuple from typing import Dict def parse_icf(icf_file: str) -> Tuple[Dict, Dict]: """Parse ICF linker file. ST only provides .icf linker files for many products, so there is a need to generate basic GCC compatible .ld files for all products. This parses the basic features from the ....
ddc1288603d0697bf915eb82a712f210f54efacd
699,780
def translate(word): """ translates third person words into first person words """ forms = {"is" : "am", 'she' : 'I', 'he' : 'I', 'her' : 'my', 'him' : 'me', 'hers' : 'mine', 'your' : 'my', 'has' : 'have'} if word.lower() in forms: return forms[word.lower()] return word
ac433a4db5154c065e2cec1263976dba72863ad8
699,781
def normalize_attribute(attr): """ Normalizes the name of an attribute which is spelled in slightly different ways in paizo HTMLs """ attr = attr.strip() if attr.endswith(':'): attr = attr[:-1] # Remove trailing ':' if any if attr == 'Prerequisites': attr = 'Prerequisite' # N...
2cb66878547ee8a98c14bf08261f2610def57a37
699,782
from typing import List import shutil def _get_build_bf_command(args: dict, in_fn: List[str]) -> List[str]: """Helper function to compose command to get the final Bloom Filter :arg dict args: Dict of arguments. :arg str in_fn: Path to file where the reads will be read :ivar dict args: Dict of argume...
9736a1825613dd518361bb1a5ded9b266293017a
699,783
import sys def _is_venv(): """ :return: """ return hasattr(sys, 'real_prefix') or getattr(sys, 'base_prefix', sys.prefix) != sys.prefix
87a6434bd4b572abbacf5b8bb81250e6287181d4
699,784
def is_user_diabetic(avg_glucose_level): """ desc: converts avg_glucose_level to category based on ADA Guidelines https://www.diabetes.org/a1c/diagnosis args: avg_glucose_level (float) : glucose level in blood based on mg/dL returns: blood_cat (string) : blood sugar category """ ...
59b8a9937f620c28eb51da4ef56c493d1b2177d8
699,785
import array def formatTilePlanar(tile, nPlanes): """Convert an 8x8 pixel image to planar tile data, 8 bytes per plane.""" if (tile.size != (8, 8)): return None pixels = iter(tile.getdata()) outplanes = [array.array('B') for i in range(nPlanes)] for y in range(8): ...
5ff30470a1392744139a5577f2a51a519f58ab42
699,786
def gen_factory(func, seq): """Generator factory returning a generator.""" # do stuff ... immediately when factory gets called print("build generator & return") return (func(*args) for args in seq)
9188f5959ec2feb52b83f20f40474f91f4cbfe08
699,787
def _parseExpectedWords(wordList, defaultSensitivity=80): """Parse expected words list. This function is used internally by other functions and classes within the `transcribe` module. Expected words or phrases are usually specified as a list of strings. CMU Pocket Sphinx allows for additional 'sen...
83512a86ae112de79bd84e1d9ea3ebebcb4cdefd
699,788
import six import os def get_file_name_list(paths, ending=None): """Returns the list of files contained in any sub-folder in the given paths (can be a single path or a list of paths). :param paths: paths to the directory (a string or a list of strings) :param ending: if given, restrict to fil...
c02e81e426937caed9c1d17c5e83147597e54a1a
699,790
import requests def delete_menu(access_token): """ 删除菜单 请谨慎使用 http请求方式:GET https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN :param str access_token: ACCESS_TOKEN :rtype: json """ menu_url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token={ac...
fb52f406d52b2dad2aedfd8c04913a3ca94b6ca1
699,791
def _generate_trades_df_response(trades_df): """ Generates JSON response from trades Attributes ---------- trades_df: DataFrame of Trades """ trades_df = trades_df.drop( columns=["symbol", "trade_id", "stop_loss", "take_profit"] ) trades_df = trades_df.rename( colum...
34244801babedeb75ec21001ea99a9e8aef863e2
699,792
def measurement(qreg=int(0), creg=int(0)): """Generate QASM that takes a measurement from a qubit and stores it in a classical register. Args: qreg(int): Number of the Qubit to measure. (default 0) creg(int): Number of the Classical Register to store the measurement to. (default...
9a9a24f390bf0745e7cdfe80bb1893f77161c171
699,794
def get_vplex_port_parameters(): """This method provide parameter required for the ansible port module on VPLEX""" return dict( cluster_name=dict(required=True, type='str'), port_name=dict(required=True, type='str'), enabled=dict(required=False, type='bool'), state=dict(requi...
9533cf6ff8eedd943b88c9cd08ea16407aa9ee64
699,795
def adjacent(p): """Return the positions adjacent to position p""" return ( (p[0] + 1, p[1], p[2]), (p[0] - 1, p[1], p[2]), (p[0], p[1] + 1, p[2]), (p[0], p[1] - 1, p[2]), (p[0], p[1], p[2] + 1), (p[0], p[1], p[2] - 1), )
988597e0abd150ae60b556e52a217bd8a136707b
699,796
async def goodbye(): """ used in our randomized redirect """ return {"message": "Goodbye"}
2a0ce1fe99497b55cfd9a9853cd75a0c7eddac40
699,797
def make_table(*list_of_list): """ :param list_of_list: list of list of strings :returns: a valid rst table """ lcols = [len(x) for x in list_of_list[0]] for li in list_of_list : # compute the max length of the columns lcols = [ max(len(x), y) for x,y in zip(li, lcols)] form = '| ' ...
77153451571e70a77d6bd525bd252aa7efe1c693
699,798
import re def replace_special_whitespace_chars(text: str) -> str: """It's annoying to deal with nonbreaking whitespace chars like u'xa0' or other whitespace chars. Let's replace all of them with the standard char before doing any other processing.""" text = re.sub(r"\s", " ", text) return text
17be082a827039264cd75fb7459fc31eb7f617dd
699,799
import re def processSets(results): """Process set results to be displayed in the set selection window :param List[Dict[str, Union[int, str, Dict[str, str]]]] results: A list of raw set results :return: A list of processed results in table form :rtype: List[Union[str, int]] """ rows = [] ...
bf050015474691402d2d992070c487b45cc34a42
699,800
def two_sequences_in_parallel(sequence1, sequence2): """ Demonstrates iterating (looping) through TWO sequences in PARALLEL. This particular example assumes that the two sequences are of equal length and returns the number of items in sequence2 that are bigger than their corresponding item in sequ...
c5dbce5f99d5c2efeee4048ec1451ea63f404fef
699,801
def image_crop(src, x1, y1, x2, y2): """ Crop image from (x1, y1) to (x2, y2). Parameters ---------- :param src: Input image in BGR format :param x1: Initial coordinates for image cropping :param y1: Initial coordinates for image cropping :param x2: End coordinates of image cropping ...
6ab70dc644d0d7054ea70fadcf7ec0ca381918d8
699,802
import argparse def parse_arguments(): """ Simple argument parsing using python's argparse return: Python's argparse parser object """ parser = argparse.ArgumentParser() parser.add_argument("--input", help="Single XML file or directory", action="store") parser.add_argument("--log", help...
0dcf19b43923c8e59af1444372421a07d6695534
699,803
import re def get_doc(src) : """get comments from Python source code Parameter -------------- src@str - the source code """ pat = re.compile(r'((?:def|class)\s+[^\n]*\s*)"""(.*?)"""',re.MULTILINE|re.DOTALL) return [gs for gs in pat.findall(src)]
bb9716a9f7b3c99d5ea3e468b7f69f893773feda
699,804
def _GetBinaryName(client): """Gets the GRR binary name on the client.""" client_data = client.Get().data return client_data.agent_info.client_binary_name
c363a4a42e81184ce2cb74bfdc9c2fd01a746cb1
699,805
def fill_with_gauss(df, w=12): """ Fill missing values in a time series data using gaussian """ return df.fillna( df.rolling(window=w, win_type="gaussian", center=True, min_periods=1).mean( std=2 ) )
fdfdedaf7968f617ff98df586b89c30053a6c886
699,806
def swap(heights_list, index01, index02): """swap two positions in a list at given indexes Args: heights_list (list): iterable in which swapping occurs index01 (int): index of first element index02 (int): index of second element Returns: list: list with element positions s...
f7add4a06a79837766b5840840d17c3247b0bcae
699,807
def calibrate_seq(cigar_seq, sequence, md_seq, ref_positions): """ making cigar seq and seq as same length with Deletions as '-' """ new_sequence = '' new_pos = [] new_cigar = '' new_md = '' seq = iter(sequence) pos = iter(ref_positions) md = iter(md_seq) current_positio...
b149587d8f61a4e7c82d4bde94e62512a5682346
699,808
def create_first_n_1_bits_mask(n, k): """ Return a binary mask of first n bits of 1, k bits of 0s""" if n < 0 or k < 0: raise ValueError("n and k cannot be negative number") if n == 0: return 0 mask = (2 << n) - 1 return mask << k
5a9b637a8973f004da2330c8ebb06ea63fd542c3
699,809
import re def clean_str(string): """ Strip and replace some special characters. """ msg = str(string) msg = msg.replace("\n", " ") msg = re.sub(r"\s+", r" ", msg) msg = re.sub(r"^\s", r"", msg) msg = re.sub(r"\s$", r"", msg) return msg
50132d2c56498f4590fcba7837deb791500f3110
699,810
def char_to_ix(chars): """ Make a dictionary that maps a character to an index Arguments: chars -- list of character set Returns: dictionary that maps a character to an index """ return {ch: i for i, ch in enumerate(chars)}
8bfc5b99c7f5aef6d88276fe4b3ad005ce9a017e
699,811
def bool_tag(name, value): """Create a DMAP tag with boolean data.""" return name.encode('utf-8') + \ b'\x00\x00\x00\x01' + \ (b'\x01' if value else b'\x00')
dc914d262a20eed0732e477f75641daa4811fd9f
699,812
def _concat(*lists): """Concatenates the items in `lists`, ignoring `None` arguments.""" concatenated = [] for list in lists: if list: concatenated += list return concatenated
a1eea1c074fe1eee1ca454899bf9dec2719a333e
699,813
def get_least_squares_size(modelform, r, m=0, affines=None): """Calculate the number of columns in the operator matrix O in the Operator Inference least-squares problem. Parameters --------- modelform : str containing 'c', 'A', 'H', 'G', and/or 'B' The structure of the desired reduced-order...
86cf6a0b3e4b256eaccb3f061d21f7de74dcc604
699,814
def read(rows): """Reads the list of rows and returns the sudoku dict. The sudoku dict maps an index to a known value. Unknown values are not written. Indices go from 0 to 80. """ sudoku = {} i = 0 for rn, row in enumerate(rows): if rn in (3, 7): continue j = 0 ...
1f1a06a32d1be70f3d912bd42b9cca07f7d4879d
699,815
import subprocess def get_server_info(): """ Returns server information """ container_name = subprocess.check_output("uname -n", shell=True).decode("ascii").strip() ip_addr = subprocess.check_output("hostname -I", shell=True).decode("ascii").strip() cores = subprocess.check_output("nproc", she...
0bbe71a91bd6e183fd3980f49935b801dede9fbf
699,816
def uniquify(iterable): """Remove duplicates in given iterable, preserving order.""" uniq = set() return (x for x in iterable if x not in uniq and (uniq.add(x) or True))
563953cc6450a0136a4996d4a5f5a0057f6ad69b
699,817
def count_candidate_votes(candidate_dict: dict, csv_data: list) -> dict: """ Go through the candidate list and count the number of votes each time it appears. :param candidate_dict: :param csv_data: :return: """ # Go through the csv and get the candidate's name for row in csv_data: ...
b2ca61d78183c1b152e22bb413ebb89a8dff8b0a
699,818
def __getDeviceByUDN(deviceElements, udn): """Search and return the device element defined by the UDN from the listDevices elements""" for device_element in deviceElements: if device_element.getAttribute("udn") == udn: return device_element
84d271b18dbcdf60688c1d921469bef45b4e4721
699,819
def createTable(c): """This makes a table Keyword arguments: c -- the cursor object of the connected database """ try: c.execute(""" CREATE TABLE IF NOT EXISTS members ( username TEXT, password TEXT ); """) except: print("Error") ...
37e7eb9fda45871c0b8890c3111c920d608f80fb
699,820
import os def link_to_frontend(): """ The backend expects a link to a directory called frontend at the same level. Attempt to create one if it does not exist. """ backend_path = os.path.dirname(os.path.realpath(__file__)) link_path = backend_path + '/frontend' frontend_path = backend_path....
3e1ebad7bd42ce25f52416aa88eb09886b42b7d8
699,822
def badFormatting(s, charSet): """Tells if a character from charSet appears in a string s.""" for c in charSet: if c in s: return True return False
23baba28be306e0d0c1ccaa0df48e1a9f94bdc8c
699,823
def column_to_width(df_in, column, width): """Pad the column header and the values in the column with whitespace to a specific width. """ df = df_in.copy() df[column] = df[column].apply(lambda x: ('{:>' + str(width) + '}').format(x)) df = df.rename(columns={column: ('{:>' + str(width) + '}').f...
988f021c7ff2f296ecacd83ddbced0de6404e3fc
699,824
def use_netrc(netrc, urls, patterns): """compute an auth dict from a parsed netrc file and a list of URLs Args: netrc: a netrc file already parsed to a dict, e.g., as obtained from read_netrc urls: a list of URLs. patterns: optional dict of url to authorization patterns Returns: ...
561ee1388dbdde74614fdef1fb29b78c7ecc687b
699,825
def str_cutoff(string: str, max_length: int, cut_tail: bool = False) -> str: """ Abbreviate a string to a given length. The resulting string will carry an indicator if it's abbreviated, like ``stri#``. Parameters ---------- string : str String which is to be cut. max_length : i...
05fdab8700dd07710c31d4007c9bc6b3f9eb6155
699,826
def is_over(board): """Returns True if the game is over, False if not""" for player in range(2): for move_x in range(board.height): for move_y in range(board.width): list_near_points = [] #list of the number of the player payns in each direction starting from the last one beg...
9302d53f72ece8928763a70b10fb265bc6b8151b
699,827
def wireless(card, mode=None, apn=None): """Retrieve wireless modem info or customize modem behavior. Args: card (Notecard): The current Notecard object. mode (string): The wireless module mode to set. apn (string): Access Point Name (APN) when using an external SIM. Returns: ...
355256bd8123f0f749561f61a2df3be93b91db61
699,828
def filter_none(x): """ Recursively removes key, value pairs or items that is None. """ if isinstance(x, dict): return {k: filter_none(v) for k, v in x.items() if v is not None} elif isinstance(x, list): return [filter_none(i) for i in x if x is not None] else: return x
c1c478b2c367dd9453b5504bbfece7dfd8c05376
699,829
def _dmet_orb_list(mol, atom_list): """Rearrange the orbital label Args: mol (pyscf.gto.Mole): The molecule to simulate. atom_list (list): Atom list for IAO assignment (int). Returns: newlist (list): The orbital list in new order (int). """ newlist = [] for i in range(m...
7998d9cec104bc02ad3daf600d2e24d9b1f5f243
699,830
def _post_processing(metric_map: dict[str, float]) -> dict[str, float]: """ unit conversion etc... time: taskTime, executorDeserializeTime, executorRunTime, jvmGcTime are milliseconds executorDeserializeCpuTime, executorCpuTime are nanoseconds """ metric_map["executorDeserializeCpuTime"] = ...
23ff301d55e0dc2d2208aca5761059fb8ade3e4e
699,831
import re def wildcard_to_regex(wildcard): """ Converts a * syntax into a parsed regular expression Maya wildcard validation: 1. Maya does not support '-' characters so we change those characters by '_' 2. Maya uses | as separators, so we scape them 3. We need to replace any '*' i...
aa8460305a6129d1a114845882dfcf29b547431b
699,832