content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import math def get_parallel_line(line_x_y, dist): """Расчёт параллельного заданному (line_x_y) отрезка""" x_1 = line_x_y[0][0] y_1 = line_x_y[0][1] x_2 = line_x_y[1][0] y_2 = line_x_y[1][1] # Нахождение вектора нормали к исходной прямой norm = [y_2 - y_1, x_1 - x_2] # Длина вектора ...
4c12254f40e28c996bade59c735eca8aa691c539
637,417
def parse_argstring(magic_func, argstring): """ Parse the string of arguments for the given magic function. """ return magic_func.parser.parse_argstring(argstring)
32a2d2e2014023eca67049eb1396013e2fa9eda2
637,418
import sys def get8digithex(dec_num): """Convert a decimal # into an 8-digit hex""" if dec_num > 4294967295: print ("ERROR: Decimal # %d can't be represented in 8 hex digits" % (dec_num)) sys.exit() hex_num = hex(dec_num) return hex_num[2:].zfill(8)
b70924dd41d98648b364b090e23546a068bb35e8
637,419
def geo_zoom(geo_df): """ Matches census tract Parameters ---------- geo_df: pd.DataFrame Dataframe with geo data """ geo_df = geo_df[(geo_df.HN_Match == 1) & (geo_df.ZIP_Match == 1)] return (geo_df)
d27d594a2add98465e32082aacd98b5aea7e692c
637,420
def lin_func(p, x): """ Die Funktion wird von der ODR-Fitprozedur intern aufgerufen Funktionsargumente: p: ein numpy-array aus zwei Elementen (Steigung und y-Achsenabschnitt einer Gerade). x: Funktionswert Die Funktion berechnet den Ausdrck p[0] * x + p[1] und gibt diesen zu...
87207f5b8d1b293b1bf0220960924177f638668c
637,421
def _base32hex160(bs: bytes) -> str: """Encodes 20-byte sequence into base32hex.""" cs = "0123456789ABCDEFGHIJKLMNOPQRSTUV" buffer = [] for i in [0, 5, 10, 15]: buffer += [ cs[31 & (bs[i + 0] >> 3)], cs[31 & (bs[i + 0] << 2) | (bs[i + 1] >> 6)], cs[31 & (bs[i ...
6e855ef26abbd6f0cc194bae78c9a1e92c7c6165
637,422
def factorizeByBase(n, base, m = None): """ Find a factorization of n with factors from base, if one exists. If the modulus m is given, the base is allowed to contain -1. All other elements must be positive. """ assert n > 0 if m is not None and -1 in base: idx = base.index(-1) ...
c9846d9c8a9a8dd805f6158b952b56ec44cf6f6f
637,423
def read_file(path): """Returns document read in by line""" with open(path, 'r') as f_in: # read in text file doc = f_in.readlines() return doc
d2c5df99bb9e6589a3be59a358ab04b50857978c
637,425
def is_int(num): """Test whether a given number is an integer or not. Tests whether a given number is an integer or not using the in-built isinstance() Python function, which returns True if the given object is of the specified type, otherwise False. Args: num (int): The number to test whe...
45e8a0a323a5463e7649cb58b93b8a2908a09519
637,426
import os def basename(path): """ Return the final component of a pathname, after normalizing the path (os.path.basename returns a empty string when given a path with a trailing slash) """ return os.path.basename(os.path.normpath(path))
8b35a5263d73d4d4af50cdad95d287fee2380d00
637,427
import requests def post_as_json(url, payload): """post the payload as JSON data""" return requests.post(url, json=payload)
c8e250f5942fe2f3a5b979740af597260ddd2426
637,428
def find_Pythagorean(n): """ find_Pythagorean() takes an integer n and returns the all the triples from 1 to n """ # set all to 1 because triangle cannot have a side of length 1 a = 1 # side a b = 1 # side b c = 1 # side c # list used to store the triples, in tuple form. initialized to empty...
541f993d7f0845ffaa3ddb5b1bd4265fac112869
637,429
import getpass import os import tempfile def temp_file(file='temporal'): """ return: str with tempfilename """ # Append uid to end of filename file += '_{}'.format(getpass.getuser()) # Simplified and reutilized core funtionally from python cache_path = os.path.join(tempfile.gettempdir(), f...
fffe7bcb209598ae268c726d88e7d685c8cf165f
637,430
def determine_jit_name(coreclr_args): """ Determine the jit based on the OS. If "-jit_name" is specified, then use the specified jit. This function is called for cases where the "-jit_name" flag is not used, so be careful not to depend on the "jit_name" attribute existing. Args: coreclr...
26b2557a18fb0964daeb719e7c2e3fe97870f6b7
637,433
def get_other_causes(effect, cause, relations): """ For each effect-cause combination, return a list of the other prima facie causes. Parameters: effect: the variable representing the effect (key of the relations dict). cause: the cause to filter out. relations: the dict containing ...
68388c128e846ec736a26f4e9f970eaf598af610
637,434
def getNewBoard(): """Return a dictionary representing a Mancala board in the starting state: 4 seeds in each pocket and 0 in the mancalas.""" # Create the data structure for the board, with 4 seeds in each pocket. board = {'1': 0, '2': 0} for pocket in 'ABCDEFGHIJKL': board[pocket] = 4 # E...
c7bc3bb5a568ab9c5e29c1e39f07245e108382c3
637,435
def _IsReadableStream(obj): """Checks whether obj is a file-like readable stream. :rtype: boolean """ if (hasattr(obj, 'read') and callable(getattr(obj, 'read'))): return True return False
3f616a6e68686427c383af3aaca83478152737db
637,436
import textwrap def break_long_lines(text, *args, **kwargs): """ Wraps the single paragraph in text (a string) so every line is at most width characters long. Short lines in text will not be touched. """ result = [] for line in text.split('\n'): result.append(textwrap.fill(line, *args,...
5e88006cc03a50e3e7c5ecaae8bfb6334275c96c
637,437
import os def append_to_path(end_str, prefix=os.getcwd()): """Joins the given end string to the end of the file path prefix.""" return os.path.join(os.sep, prefix, end_str)
32148fafc5342a8d69a5958b2bae482a8caa65cd
637,438
import uuid import json def gen_default_zones_esa(): """gen_default_zones.""" template = { "useDangerZone": True, "dangerZones": [ { "id": "$UUID_PLACE_HOLDER", "type": "BBox", "label": {"x1": 415, "y1": 83, "x2": 513, "y2": 198}, ...
7bb15e7dfbc0a31183bf07315f97be34f8aa1e4b
637,439
import yaml def read_yaml(file_path: str) -> dict: """ Safely reads a yaml-file. Parameters ---------- file_path : str File path to YAML-file. Returns ------- dict Loaded YAML-file. """ with open(file_path, 'r') as stream: try: retu...
21e59f65ffee8994999cce9d21b6697a20a1b759
637,440
import logging def IndexFileOrInameToPrefixInfo(inp_d): """ There are two options: Either an index file path to get index information, or an index name, in which case prefix is a list with length 1 Args: inp_d: (dict) [indexfile_fp] (str) OR index_nam...
ea552b6e60d26798b00966fd2a8bd8ac25233177
637,441
import os import shutil def copy_if_different(source: str, dest: str) -> bool: """Copy a file from src to dest, if newer or a different size""" do_copy = False if not os.path.exists(source): return False if os.path.isdir(dest): dest = os.path.join(dest, os.path.basename(source)) if...
5119557bc12084bdd4e10493293bf3472b713909
637,442
def get_column_names(connection_or_cursor, table): """Return list of column names from given database table.""" cur = connection_or_cursor.execute(f'PRAGMA table_info({table})') return [row[1] for row in cur.fetchall()]
9e41c62180b46e2b9f2006b66563585761b1c50a
637,443
from typing import Optional import re def parse_timestamp(timestamp: str) -> Optional[int]: """Parse a playback timestamp into a number of seconds. Expects the timestamp to be in HH:MM:SS or MM:SS format. """ match = re.match( r"^(?:(?P<hours>\d+):)?(?P<minutes>\d+):(?P<seconds>\d+)$", timest...
e408a9fb7a1373467359a6cf59d239b82f774b82
637,444
import ast def get_bool_input(input_parameter): """Returns a boolean corresponding to a string "True/False" input Args: input_parameter (str): String input for a boolean Returns: bool: True/False input """ if input_parameter.lower().capitalize() in ["True","False"]: return ast.literal_eval(input_...
48fefc90d88cc455e9859565fc16a4cdb290b165
637,445
def getVidLocalizations(binaryPreds): """ Receive a list of binary predictions and generate the action localizations for a video """ vLocalizations = [] act_beg, act_end = -1, -1 isAction = False for i,pred in enumerate(binaryPreds): if not isAction: if pred == 1: #...
562471645c6dc1a0d48d707eb7a6f01a172ed2cb
637,446
from typing import List def xlnet_tokens_pre_processor(token_ids: List[int]) -> List[int]: """Add XLNET style special tokens. Args: token_ids: List of token ids without any special tokens. Returns: List of token ids augmented with special tokens. """ XLNET_CLS_ID = 3 XLNET_SE...
1f8703021d3c543ecda234f06430fbb1ec690c62
637,447
def find_value(db, value_to_find, sheet_name=''): """Return the first address in the xlsx file where the value matches.""" # create in memory database from file # db = xl.readxl(file_path) # list of worksheet names if sheet_name == '': # if no sheet provided, check them all wsheets...
aed2b1721b723d1e422d6bcea5e8d871b0a1e6ca
637,448
def rolling_variance(old,newValue): """Rolling variance computation according to Welford's algorithm. https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Welford's_Online_algorithm Parameters ---------- old : tuple containing the triplet count, mean, M2. Initialize with (0,0,...
caa36948d44cb64186de66e74dc3a226f0e1a65e
637,449
import random def _get_quantity(): """ Get random product order quantity from 1 to 5. Values are given a weight, decreasing as the quantity number increases. :return: Product quantity number """ return random.choices([1, 2, 3, 4, 5], weights=[50, 20, 20, 5, 5], k=1)[0]
77128ea4c12f76286826fadd8241ab3592cb8a99
637,450
def convert_labels(Lorig, params, toLasStandard=True): """ Convert the labels from the original CLS file to consecutive integer values starting at 0 :param Lorig: numpy array containing original labels :param params: input parameters from params.py :param toLasStandard: determines if labels are conv...
b3f7a1165faba0b2aaabebcdd34a592367800a83
637,451
def unevenly_expand_xywh(x, y, w, h, image_w, image_h, left_w_ratio, right_w_ratio, top_h_ratio, bottom_h_ratio): """Expand each side by their respective ratio.""" x_expanded = max(0, x - int(w * left_w_ratio)) y_expanded = max(0, y - int(h * top_h_ratio)) x_end_expanded = min(image_w, x + int(w * (1.0 + right_...
4f39741f02eb1fe94f1c7dd28889204c4cedf45a
637,453
def max_len(seq_list): """Returns the maximum sequence length within the given list""" lmax=0 for seq in seq_list: lmax=max( lmax, len(seq) ) return lmax
dad4290683c5a386a16147ebe87df346148935d8
637,455
def indicates_division(token): """A helper function that helps the tokenizer to decide if the current token may be followed by a division operator. """ if token.type == 'operator': return token.value in (')', ']', '}', '++', '--') return token.type in ('name', 'number', 'string', 'regexp')
a4ad7885e67c5747995be44433bb38288f04b7de
637,456
def account_from_role_arn(role_arn): """ Returns the AWS account ID portion of the given IAM role ARN. """ parts = role_arn.split(':') if len(parts) == 6: return parts[4] return '-'
4754089a654e52862b11b56d6991096621f2b292
637,457
def zip_builtin(): """zip: Merge elements of different iterables.""" return ''.join(first + second for first, second in zip("Jh o", "onDe"))
d7cf216b149ada342e2ca7d166b2f3c8639ad268
637,458
def check_for_empty_values(dictionary): """ checking dict for empty values :param dictionary: dict for checking :return: check result """ return all(dictionary.values())
d4446016ac83b511d9012782da5be03a138c3be3
637,459
def sec1_uncompressed_public_key(public_key): """ Generates the copressed point representation (SEC1, section 2.3.3) for the given public key. """ return public_key.to_string('uncompressed')
ae610286fec758af67fb16a36d3142382c040deb
637,460
def run_plan_after_opt(plan): """Runs a plan after it is optimized""" rows = list() for row in plan: vals = [] for v in row: if isinstance(v, str): vals.append(v) else: vals.append(float(v)) rows.append(vals) return rows
262b860628ebe10dfbe12cc5a75907885ecf186f
637,461
def has_issue(item): """Return True if the testcase has an issue.""" return bool(item.issue_id)
1afd227555ed9a58e50a167eff5d344cd3ec56f5
637,462
def gl_get_group_membership(gl, user_id): """ Get a list of all groups where user_id is a member :param gl: GitLab instance :param user_id: user id (not username!) this field is (gitlab User object).id """ groups=[] for gl_gp in gl.groups.list(as_list=False): for gl_mem in gl_gp.memb...
b63ac0b8a333587718fc164061b0d0097bd172d4
637,463
def _i2col(i): """Given an index, return the column string: 0 = 'A' 27 = 'AB' 758 = 'ACE' """ b = (i//26) - 1 if b>=0: return _i2col(b) + chr(65+(i%26)) return chr(65+(i%26))
ae3ea60f149df46b501d6e61ba4b816a8236cb80
637,464
def makeSimple(*args, **kwargs): """ Creates Bitcoin Transation with One Input and One Output; value must be specified in Satoshis""" makeComplex, inHash, inIndex, inScript, outValue, outScript = args[0:6] inputs = [[ inHash, inIndex, inScript, 0xffffffff ]] o...
1bf3f0d66c9397e86265174dc9f1f7c143096ffc
637,465
import math def rotate_coordinate(x, y, cx, cy, theta): """Return a new point (x', y') as rotating an existing point (x, y) theta radians around the point (cx, cy). """ x_p = ((x - cx) * math.cos(theta) + (y - cy) * math.sin(theta)) + cx y_p = (-(x - cx) * math.sin(theta) + (y - cy) * math.cos(the...
689220526937e5a139df49a627b393c1331f445a
637,466
from typing import List def _enumerate_cores(bounds: List[int], ring_bounds: List[int], ring_sizes: List[int], host_bounds: List[int], host_sizes: List[int]) -> List[List[int]]: """Enumerates cores within `bounds` from fatest to slowest varying axes. Args: bounds: Up...
50e4fbbdb9b57e0133a2d71916aa83c75c312a40
637,467
def to_numpy(x): """Helper to convert TensorFlow tensors to Numpy. """ return x.numpy()
94c6bad544bf8de97fbbebeaa98a795e150d3fa0
637,468
def convert_to_factors(die): """Converts a sympy factor_list tuple to a list of the factors and returns the list""" sub_list = die[1] # Create a list from the tuple factor_list = [] for i in sub_list: # Iterate through the `sub_list` which contains all the factors for j in range(i[1]): # Nesting...
568063246155befdf078da51887b9e513b961688
637,470
def get_points(json_file): """ Returns json_files points @param: json_file - given json file """ try: return int(json_file['points']) except KeyError: return 0
db5896a91873ba4352f48dff867e3c6988c22aac
637,471
def clean_state(state): """ Upper cases the state and fixes a few weird issues. """ new_state = state.upper() if state else None # NF -> NL for Newfoundland and Labrador. if new_state == "NF": new_state = "NL" # PQ -> QC for Quebec. if new_state == "PQ": new_state = "QC" ...
5e4012d5edc2ffa581010f11ff5de02de8990d7c
637,472
def ensure_tz_UTC(df): """ Function to ensure that the tzinfo of a data frame is in UTC :param df: a pandas data frame with datetime_index :returns: the dataframe with df.index.tzinfo='UTC' """ # ensure tzinfo is in UTC if (str(df.index.tzinfo)=='None'): #print('The time...
4e8fb68dc648b32138dda66a415c9c5e660665f1
637,473
import os def ext(fname): """return the extension of a filename.""" if "." in fname: return os.path.splitext(fname)[1] return fname
7b76d4ebdc797bc20053a05a63bce04ec5f6b503
637,475
from typing import List from typing import Optional def determine_tests_to_run( test_candidates: List[str], ignore_paths: List[str], filter: Optional[str] ) -> List[str]: """ Applies a number of filters to a list of test candidates in order to determine the final output to be fed to pytest. """ ...
912d942a21e1c9d4b89735906a6eea313a3d5776
637,476
def format_report_object(r): """Format an IRRD HTTP response for a specific object into a human-friendly text.""" status = "succeeded" if r["successful"] else "FAILED" report = f'{r["type"]} {status}: [{r["object_class"]}] {r["rpsl_pk"]}\n' if r["info_messages"] or r["error_messages"]: if r["er...
5589f149cd2b656378fe27eb9bbeee76b146ed1a
637,477
import ast def _SingleLiteralEval(value): """Parse value as a Python literal only. Args: value: A string to be parsed as a literal only. Returns: The Python value representing the value arg. Raises: ValueError: If the value is not an expression with only containers and literals. SyntaxE...
675f4dd48ca515454668b3e8af86e5cf60ff222e
637,478
import heapq def dijkstra(graph, start, end): """Return the cost of the shortest path between vertices start and end. >>> dijkstra(G, "E", "C") 6 >>> dijkstra(G2, "E", "F") 3 >>> dijkstra(G3, "E", "F") 3 """ heap = [(0, start)] # cost from start node,end node visited = set()...
cce4677f0af1555c0efa4d629d9eea99a26541b7
637,479
def count_two_mers(sequence, two_mers): """Returns dictionary, keys are possible couplesl of letters, values are number of their occurances in a given sequence. """ dictionary = {} for mer in two_mers: dictionary[mer] = sequence.count(mer) return dictionary
c27122f3fd0c43a37c22ef718568e8e3cb4faefc
637,480
from functools import reduce def list2bitvec(lst): """Convert list of bits to bitvec""" bitvec = reduce(lambda p,q: (int(p)<<1)|int(q),lst) return bitvec
abc27058ad0dddbae0a363302d14d5957fbb30b2
637,481
def create_query_string(title:str="", auth:str="", startindex:int=0)->str: """ googlebooksapiでデータを取得する為のurlを作成する Args: auth (str, optional): 作者. Defaults to "". title (str, optional): 本の題名. Defaults to "". Returns: [str]: url """ url = 'https://www.googleapis.com/books/...
ec752dbaf6f5b1582b09509c3c1f509a78f18013
637,482
def get_service_start_name(start): """ Translate a Windows service start number to a friendly service start name. """ return { 0: 'Boot', 1: 'System', 2: 'Automatic', 3: 'Manual', 4: 'Disabled' }.get(start, 'Unknown')
f97e6476e187c22243ad1907314bc1443581e2aa
637,483
def execution_time(start_time, end_time): """ :summary: Difference of supplied time in seconds :param start_time: Start time :param end_time: End time :return: Difference of supplied time in seconds """ return str(((end_time-start_time).total_seconds()) * 1000)
0bb227d521c4305e14cd7bd3315a9bcab2ac33d2
637,484
import re import sys def parse_cigar(cigar, strand, sequence, offset): """ Parses cigar string and finds intervals in sequence with boundary information """ operations_t = re.findall(r"\d+\D", cigar) operations = [] for operation in operations_t: nr, op = [int(operation[:-1]), operation[-1]] ...
e469d26446e68e23dc6369c3178baea17e841c47
637,487
import re def fix_reserved_name(name): """Returns a tuple of (<name>, <replacement_name>) if name is a reserved word, otherwise returns (<name>, <name>). """ reserved_names = [ ('^key$', '_key_rr'), ('^interval$', '_interval_rr'), ('^load$', '_load_rr'), ('^primary$', '_pri...
713e8e3d5cc505241e488f4c70d68bd13e3b8c9a
637,488
import requests def get_id_list(token, custom_id): """ 通过校内模板id获取校内打卡具体的每个时间段id :param token: 用户令牌 :param custom_id: 校内打卡模板id :return: 返回校内打卡id列表 """ post_data = { "customerAppTypeId": custom_id, "longitude": "", "latitude": "", "token": token, } try...
f5b0e764e2674179a9bb341da2678c5522f8a1fc
637,489
def gray_code_sequence_string(bit_count: int) -> list: """ Will output the n-bit grey sequence as a string of bits >>> gray_code_sequence_string(2) ['00', '01', '11', '10'] >>> gray_code_sequence_string(1) ['0', '1'] """ # The approach is a recursive one # Base case achieved w...
d1f75e9ea4b607ef9720568dfa3f5504efa9ecfe
637,490
def pool_url(aws_region, aws_user_pool): """ Create an Amazon cognito issuer URL from a region and pool id Args: aws_region (string): The region the pool was created in. aws_user_pool (string): The Amazon region ID. Returns: string: a URL """ return ( "https://cogni...
e5d3653c10b4a5f5fe033625893ea7816224a4a2
637,491
def parse_to_graphql_query(deployments,survey_type): """ Parse a deployments dict to graphql query type to post to zendro api. Parameters: deployments (dict): A dict containing the deployments of devices. survey_type (string): A string that indicate...
10d92fed501c18ab99e1e29eea621061a2cad63c
637,492
def environ_app(environ, start_response): """ Outputs the full server environ passed in to the request. Wsgiref populates environ with a few extra things thay may normally/actually be there. """ response_body = ['%s: %s' % (key, value) for key, value in sorted(environ.i...
453f79083047fc15172a074387cf459626d05435
637,493
def timedelta_to_integral_seconds(delta): """ Convert a pd.Timedelta to a number of seconds as an int. """ return int(delta.total_seconds())
8a049b167e2cc793785f24c16a2583634b1cb17c
637,494
def file_number(number, string_length): """Generate number strings with leading zeros so that numerical and string order coincide""" number_to_string = str(number+1) length = len(number_to_string) final_name = '0'*(string_length-length) + number_to_string return final_name
f224f3a7117c80a7d553c904a4f7a0176611e0be
637,495
import subprocess def process_exists(process_name: str) -> bool: """Ts true if the process exists, if not then false. Args: process_name (str): Name of an Prozess Returns: bool """ call = 'TASKLIST', '/FI', f'imagename eq {process_name}' # use buildin check_output right away ...
bf9946f0cbf55a8725054750a0f3e7dd3361ba38
637,496
def get_by_path(obj, path): """ Iteratively get on obj for each key in path. :param (list|dict) obj: The top-level object. :param (tuple[str]|tuple[int]) path: Keys to access parts of obj. :return: (*) Example: >>> figure = {'data': [{'x': [5]}]} >>> path = ('data', 0, 'x') ...
1cba19902076f732e61dc5647b084172c3f67ebc
637,498
def binary_search(data, target, low_index, high_index): """ Binary Search recursiva """ if (low_index > high_index): return False mid_index = (low_index + high_index) // 2 if target == data[mid_index]: return True elif target < data[mid_index]: return binary_search(data, ta...
0051d88fa1f15a36d5bcc23d8c850096beb0767c
637,500
import os def dir_path(string): """Validate provided directory path""" if os.path.exists(string): if not os.path.isdir(string): raise NotADirectoryError(string) else: # create if it does not exist os.mkdir(string) # make the path absolute before giving it back r...
24c4ebdec06f5c75db16cecbec01e58d9e8006cb
637,501
def check_game_over(boardPlaceTestList): """Check in the "boardPlaceTestList" if there is still a piece that can be placed on the board. If there is not, retrun gameOverTest as true else as false.""" gameOverTest = False for currentTest in boardPlaceTestList: if currentTest == True: ...
b5094f4232466e1658176509d58e440ec54159bd
637,502
def test_rows(data_frame): """ Checks that the dataframe has more than 1 row. :params dataframe df: :returns bool: """ nrows = len(data_frame) one_row = True if nrows < 1: one_row = False return one_row
02ce650bad8d3735e9d8ec86d4500529fbe57d2b
637,503
def find_multiples(integer, limit): """ Finds all integers multiples. :param integer: integer value. :param limit: integer value. :return: a list of its multiples up to another value, limit. """ return [x for x in range(1, limit + 1) if x % integer == 0]
36b438541f6f067a92aad6317f3ce919b6e4bde2
637,504
def scaling_ratios(net_data, costs): """Get the scaling ratio---the cost per MAC---for convolutional and fully-connected layers with the given cost set. """ # Total numerators and denominators. totals = { 'conv': { 'cost': 0, 'macs': 0 }, 'fc': { 'cost': 0, 'macs': 0 }, } # ...
481ef265b9eec6794d9f705440edfe7f3b4231f9
637,506
import math def get_ticks(start, end, target_n_labels=10): """ Tries to put an appropriate number of ticks at nice round coordinates between the genomic positions `start` and `end`. Tries but doesn't guarantee to create `target_n_labels` number of ticks / labels. Returns: a list of tupl...
a91a090777e5b3697163bb6dcf88bdef501b9302
637,507
def ida_offset(string): """ Converts non-IDA conforming offset representation to a more IDAesk form. :param string: a non IDA conform string :return: IDA conform string """ segment, rest = string.split(':', 2) offset_start = rest.rfind('+') offset = rest[offset_start + 1:-1] operands...
71ec528603b172550e28c57c832317b6065fbd1e
637,508
def format_grid(grid): """ Formats each row to represent list value delimited by spaces :param list grid: input with nested lists to format """ formatted_grid = '' for row in grid: # list comprehension used to explicitly cast items to str # this allows for the grid param to cons...
7a2305f459740b991cfe57f510032eea6bcf15a0
637,509
import collections def invert_dict(d): """Invert a dictionary. Converts a dictionary (mapping strings to lists of strings) to a dictionary that maps into the other direction. Arguments: d: Dictionary to be inverted Returns: A dictionary n with the property that if "y in d[x]", then "x in n[y]". ...
b1ff7ebb163640b25132670a95e1826f2f5ed985
637,510
def points_from_bbox(minx, miny, maxx, maxy): """Construct polygon coordinates in page representation from a numeric list representing a bounding box.""" return "%i,%i %i,%i %i,%i %i,%i" % ( minx, miny, maxx, miny, maxx, maxy, minx, maxy)
448e5dcd60d17f0e6ddda8feabc889579fa07518
637,511
def _is_technical(computation: str) -> bool: """ Check if a computation is a technical computation. Parameters ---------- computation: str a computation name. Returns ------- True if it is a technical computation, false otherwise. """ if computation.startswith('_'): ...
f2cdd49d36d6558f95e736374c2c475bccda388c
637,512
def getPlaylists(sp, username, offset=0): """ Retrieves all the playlists a user has :param sp: A spotipy.Spotify object to be used for the request. :param username: The username of the user who's playlists you want the retrieve. :param offset: Do not worry about this ...
c4d3b8a651fc20bd9234c8949b3248cee68210d8
637,513
def get_sleep_loss(generative_model, guide, num_samples): """ Args: generative_model guide num_samples (int) Returns: [num_samples] """ latent, obs = generative_model.sample(sample_shape=(num_samples,)) return -guide.log_prob(obs, latent)
e2520a5b6382c5ec01f5cdc25fc8ca02cd1fc78c
637,515
from typing import Optional def color_mid(value: float) -> Optional[str]: """Determine color for efficiency value where "mid" values are the target. Args: value: percent (0-100) of value to color Returns: The color string for click or None if color should be unchanged """ if valu...
b9418fcc41ae3453b39d8e4fed7a0e473d2bba1a
637,517
def _localize(dt, tzinfo): """ :return: A localized datetime :paramd dt: Naive datetime :param tzinfo: A pytz or python time zone object Attempts to localize the datetime using pytz if possible. Falls back to the builtin timezone handling otherwise. """ try: return tzinfo.locali...
f68588195197b250d88a710f01196d6dd701c2d1
637,518
import json def get_all_block_transactions(blocks_file_path): """ Return the number of transactions for blocks in the file in a dictionary """ transaction_counts = {} with open(blocks_file_path) as blocks_file: for line in blocks_file: block = json.loads(line) ...
1ded6ef1730e6124ff6d76da6fef1f53358802a9
637,519
from typing import Counter def static(): """ 统计下 Returns: """ examples = [] filename = "/opt/salt-daily-check/notes/paper_train.md" with open(filename, 'r') as f: lines = f.readlines() # 每5行一个样本, for i in range(0, len(lines), 5): eng_word = lines[i] ...
584381934db2d17d0f2de1f2359a627b95507842
637,520
def _is_file_valid(name): """Decide if a file is valid.""" return not name.startswith('.')
a7f00223686279f0e648e6bf828a3e51d5d5e988
637,521
def remove_non_ascii(x): # pragma: nocover (No idea how to generate non-ASCII characters.. """ Assumes utf-8 Taken from https://stackoverflow.com/questions/1342000/how-to-make-the-python-interpreter-correctly-handle-non-ascii-characters-in-stri :param x: :return: """ return "".join(i for i ...
3a93fcac8a0252d96106ffea5c1e46aff0fd0f4d
637,523
import itertools def getdates(yr1=2009, yr2=2016, month1=1, month2=12, day1=1, day2=31): """Returns a list of all possible dates as a set of tuples: E.G. date1 = (2009, 01, 01) or datex = (2011, 12, 06) The form is therefore a [(yyyy, mm, dd), ... (yyyy, mm, dd)] This function is set up to return all possible...
b6329add7199be6ab2ea57e623b12f09533d79f1
637,524
from typing import List from typing import Dict def _add_annotation(objs: List[Dict], annotation_key: str) -> List[Dict]: """ Adds a boolean annotation (set to True) to a list of rich text objects (https://developers.notion.com/reference/rich-text) """ for obj in objs: if 'annotations' in ...
9f3f465cd88ebdfa6e5adbc909c0be9a77836bf7
637,525
from datetime import datetime def get_datetime_string(): """ Generate a datetime string. Useful for making output folders names that never conflict. """ now = datetime.now() now = [now.year, now.month, now.day, now.hour, now.minute, now.second, now.microsecond] datetime_string = "_".join(list(...
e32914ae947a14bf5d01e7f37ebc23781ba10110
637,526
def read_and_pre_process_xml(file_name): """ Read XML file with the name specified in the argument and pre process the xml so that it can be parsed. Pre Processing removes line retune characters (i.e. "\n"). Arguments: file_name (str): Name of the XML file. Returns: (str): Pre Pr...
e3dbfaf7320d74a58698a61c6e463c08d9bb0e03
637,527
def _normalize_header_name(name: str) -> str: """ According to rfc https://www.ietf.org/rfc/rfc2616.txt header names are case insensitive, thus they can be normalized to ease usage of Headers class. :param name: :return: """ name = name.lower() if name.startswith("http_"): name =...
694087c9af89bca5652bc43fcaeaaa4ccbe86ad0
637,528
import numpy as np import pandas as pd def ras(seed, goal): """ Pass the RAS algorithm for a given n x m seed matrix and n x m goal matrix""" # Initialise goal_get_total = np.array(goal.iloc[:, -1]) goal_getc_total = np.array(goal.iloc[-1, :]) goal_row_totals = np.delete(goal_get_total, len(goal_...
75968e8e47110eee36d256cc470bb7186964a975
637,529
def center_text(text, page_width, char_width): """Helper function for calcuating the start x value for centered text.""" text_width = len(text) * char_width return (page_width - text_width) // 2
fb545d39315467606ed08e4aa93ce3159870c68b
637,530
def _stripReverse(s): """Returns the string s, with reverse-video removed.""" return s.replace('\x16', '')
38e1c202b0e38b15caf677dba922ff1b669705c8
637,531