content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def anon_dim_name(size,**kws): """ Name given to on-demand dimensions. kws: unused, but might include the type? """ return 'd%d'%size
f817446ab07f2fd106d143e5f510fa4c5009fcec
660,957
def ui(): """UI Implementation with prints and inputs""" print("Insert the text to be encyphered") plaintext = input() print("Insert the cypher") cypher = input() return plaintext, cypher
4527106dc5b093246ba3d66d4c5585c46df20399
660,959
def _ds_times2s_times(ds_times): """ STIX time might be in ds (deci-seconds). Convert to seconds. Parameters ---------- ds_times : time bins A 2D array of time bins. Returns ------- A 2d array of the time bin edges. """ return ds_times
0565108fd5ff89ba5919b890e7a054588e8a406a
660,960
def abort_script(tmpdir): """ Pytest fixture to return a path to a script file """ script_path = tmpdir.join("abort.py") script_path.write( """ import time def main(queue, procedure): time.sleep(2) queue.put(procedure.pid) """ ) return f"file://{str(script_path)}"
dc092441689819122d6112f1f4606b2c6cb7a514
660,961
import json def get_json_rules_schema(rules_schema_file: str): """Get the rules schema by filename""" with open(rules_schema_file) as schema_file: return json.load(schema_file)
ce48b463d74cd1e79bb309f6880b527e968ddc26
660,962
import os def normalize_path(working_dir, filename): """Normalizes the path of a file name relative to a specific directory.""" if not os.path.isabs(filename): filename = os.path.join(working_dir, filename) return filename
8731f2ab7be854557e249b8685cc77c2a63f2aa5
660,963
def remove_invalid_attributes(obj, data): """ remove the attributes of a dictionary that do not belong in an object """ _data = {} for name, value in data.items(): if hasattr(obj, name): _data[name] = value return _data
89a401ba1f52bf155b74e03f00376a246641d946
660,964
import os def get_filenames(stem, check=False): """ Given a filename basename, return the associated shapefile paths. If `check` is True, ensure that the files exist.""" if stem.endswith(".shp"): stem = stem[:-4] shp = stem + '.shp' shx = stem + '.shx' dbf = stem + '.dbf' if check:...
414da4f1a230b8578d3249baced8603b48260a06
660,965
import csv def split_csv_size(csv_file, size, folder, keepheader=True): """[Split a large csv file into small csv files with certain rows in each small csv file] Arguments: csv_file {[Path]} -- [the Path object for the large csv file to split] size {[int]} -- [number of observations in ea...
2eea6c09325750b0da96b8267f9dea17ca6d8439
660,966
def get_key_paths(data_dict, keys_to_consider=None, keys_not_to_consider=None, root_path=None): """ Example: get_key_paths({ 'a' : { 'b': 1 }, 'c' : 2 }) returns: ['a.b', 'c'] :param data_dict: (Nest...
c3548b24aaf49e2e5f5632f503a5fd32d38eb00b
660,967
def loadrepr(reprstr): """Returns an instance of the object from the object's repr() string. It involves the dynamic specification of code. >>> obj = loadrepr('datetime/datetime.datetime.now()') >>> obj.__class__.__name__ 'datetime' """ module, evalstr = reprstr.split('/') mylocals = l...
c0eaa039c3575992702a2a76cca2e9756561c833
660,968
import re def spacing_digit(text): """ add space before and after digits """ re_tok = re.compile('([0-9])') return re_tok.sub(r' \1 ', text)
e7043c216c639209bdec37a406270df4ea460b46
660,969
import os import subprocess def upload_lib(lib_path): """ 打包lib,上传到本地maven仓库 :param lib_path: :return: 0-success, 1-fail """ os.chdir(lib_path) error = subprocess.call(['../gradlew', 'clean']) if error != 0: return error error = subprocess.call(['../gradlew', 'uploadArchi...
1f20beb6dfc233f0a9ee98f264932ee60d116068
660,970
def _get_axis_num(nrow, row, col): """ computes axis number Parameters ---------- nrow : int number of rows row : int row number col : int column number """ return (nrow * row + col) + 1
7ea99ef5960677e2b1769995080b598763e7a680
660,971
def create_namelist_lazy_greedy_pegasus_algorithm (cursor): """Список всех сочетаний имён и трипкодов.""" # А вот не нужно было делать циклы в циклах. 2 триллиона запросов, это не шутки! # Для начала загружаем имена и трипкоды в отдельные списки: names = cursor.execute("SELECT DISTINCT (post_name) FROM ...
5199dedaed3597d2128357c576809c83ff84afde
660,972
def usage(prtflag): """ Do something with the usage message. If the prtflag parameter is non-zero, we'll print and exit. If it is zero, we'll just return the string. """ # # Set up our usage string. # outstr = """hostxref [options] where [options] are: -find - base protocol for searching ...
58ff2564421adedb20712ba0b6eb800671d01cb4
660,973
import pytz from datetime import datetime def is_it_june() -> bool: """ determines if it is currently June in Madison, Wisconsin Returns: True if it is June, False otherwise """ tz = pytz.timezone("US/Central") the_now = datetime.now(tz) return datetime.date(the_now).month == 6
e1018f1ec92fd7fadf9b305d338dfdf234d3db46
660,974
def avp_from_rhmin_rhmax(svp_temperature_min, svp_temperature_max, relative_humidity_min, rh_max): """ Estimate actual vapour pressure (*ea*) from saturation vapour pressure and relative humidity. Based on FAO equation 17 in Allen et al (1998). :param svp_temperature_min: Saturation vapour pressur...
556669e20ab4f2e3562f45a151cc292f1cb3bbb5
660,975
import torch def safe_invert_gains(image, rgb_gain, red_gain, blue_gain): """Inverts gains while safely handling saturated pixels.""" image = image.permute(1, 2, 0) # Permute the image tensor to HxWxC format from CxHxW format gains = torch.stack((1.0 / red_gain, torch.tensor([1.0]), 1.0 / blue_gain)) / rgb_gain...
8b9bebc112d3a5598672b928bf2d61d7538c887a
660,976
from datetime import datetime def convert_to_begin_of_day(a_date): """ @return the naive datetime object of the beginning of day for the give date or datetime object """ if a_date is None: return None return datetime(a_date.year, a_date.month, a_date.day, 0, 0, 0)
892ac7b0ee2304f1471bb044e7178a809a81b013
660,977
def cut_and_paste_segment(seq, start, end, new_start): """Move a subsequence by "diff" nucleotides the left or the right.""" sub = seq[start:end] diff = new_start - start if diff > 0: return seq[:start] + seq[end : end + diff] + sub + seq[end + diff :] else: return seq[: start + diff...
03daaac096f26994ef52be3a0249660ea391f36e
660,978
def playfair_bigrams(text, padding_letter='x', padding_replaces_repeat=True): """Find all the bigrams in a method to be enciphered. If both letters are the same, the `padding_letter` is used instead of the second letter. If `padding_replaces_repeat` is `True`, the `padding_letter` replaces the second ...
bc4a49e2d71daf75ecb5a8b17bafe18eab72de83
660,979
def parse_block_scalar_indent(TokenClass): """Process indentation spaces in a block scalar.""" def callback(lexer, match, context): text = match.group() if context.block_scalar_indent is None: if len(text) <= max(context.indent, 0): context.stack.pop() ...
07f16f3d4eb25ba746ab68a36a18096342ebfbfd
660,980
def get_n_document_from_yaml(yaml_generator, index=0): """ Returns n document from yaml generator loaded by load_yaml with multi_document = True. Args: yaml_generator (generator): Generator from yaml.safe_load_all index (int): Index of document to return. (0 - 1st, 1 - 2nd document) ...
2eb44fc0521fbb2782c63fc317d9c0f2801bc4d3
660,982
import subprocess def shell(args): """Executes a shell command """ if isinstance(args, str): raise ValueError("Passed string to shell, it is safer to use array: %s" % args) proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = proc.communicate() ret ...
471ad86aacb6c9c9212fc8761a774564396d0a04
660,983
def typedvalue(value): """ Convert value to number whenever possible, return same value otherwise. >>> typedvalue('3') 3 >>> typedvalue('3.0') 3.0 >>> typedvalue('foobar') 'foobar' """ try: return int(value) except ValueError: pass try: retu...
96f4ae19004202ef2cf2d604e742693ebaebe2ed
660,984
import random def generate_hex_colour(ex_prop: float = 10.0) -> str: """ Generates a random hex color sampled from a partitioned color space Args: ex_prop (float): Head & tail-end proportions to exclude from sampling. This is to make sure that the generated colours are of a certain ...
a9e7fe7c3b537f82919fa678a5a6712d6c92b420
660,985
def reverseStringv2(a_string): """assumes a_string is a string returns a string, the reverse of a_string""" reverse_string_list = [] for i in range(1, len(a_string)+1): reverse_string_list.append(a_string[-i]) return "".join(reverse_string_list)
3978b3b0d6feb711642c6cb6128694b6a4eb38bc
660,986
def herfindahl_hirschman_index(distribution): """Herfindahl–Hirschman Index Args: distribution (list): wealth distribution in the market Returns: (float): Herfindahl–Hirschman Index (HHI), market concentration degree 0 <= HHI < 1, HHI = 0, perfectly competitive ...
2822951809946604635d43ab939639e5e4cb0fee
660,987
import gzip from io import BytesIO import sys from io import StringIO def decompress_gzip(in_str): """ Uncompresses a gzip string and returns it. :Parameters: in_str : string gzip compressed string :returns: uncompressed string """ if sys.version_info > (2, ): ...
92cd183e74fab55acfb5557aa75a78029de14503
660,988
import numpy def smoothing_by_kernel(y_from = None, n_from = None, n_to = None, duration = 10.0, h = 0.05): """ y_from : is the array with the input signal to be smoothed and embeeded into a new array with 'n_to' values n_from : number of points from 'y_from' to consider, if it...
f75d4570acb5e40f0ee5188e8e24b92948531c5c
660,989
def values_to_string(input_values): """Method that takes a list of values and converts them to a '|'-delimted string""" token_list = [] for value in input_values: token_list.append(str(value)) return '|'.join(token_list)
0ed4de389311caf25ac9d32a513f4a59e6efd05a
660,990
def listToItem2index(L): """converts list to dict of list item->list index This is lossy if there are duplicate list items""" d = {} for i, item in enumerate(L): d[item] = i return d
4e2cd493efb2dd8653b2c0d946744d6b9f4b2972
660,991
import os def get_label_names(directory): """ Get names of labels (artists) by finding the directory names Input: - directory: directory where subdirectories of artists are stored Returns: - label_names: list of names of subdirectories (corresponding to artists here) """ # Create e...
60a0b3493a1ae39cf4e9614ec3d8ad5837e19693
660,992
import types def iscode(object): """Return true if the object is a code object. Code objects provide these attributes: co_argcount number of arguments (not including * or ** args) co_code string of raw compiled bytecode co_consts tuple of constants used in the byteco...
8359c1789865fd206b00ac65603cf5f0d0e89d96
660,993
def null_fields_schema(): """ This fixture has null fields. https://json-schema.org/understanding-json-schema/reference/null.html """ return { "$id": "https://example.com/null.schema.json", "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "prope...
0aab99b61eb2a4fbcf812a193d27381ff00a8bba
660,994
def get_user_dict(profile_dict): """Collect parameters required for creating users.""" return {k: profile_dict[k] for k in ('email', 'first_name', 'last_name', 'institution')}
e100425c353df505d87c49302a21660094daa660
660,995
def pretty_list(the_list, conjunction = "and", none_string = "nothing"): """ Returns a grammatically correct string representing the given list. For example... >>> pretty_list(["John", "Bill", "Stacy"]) "John, Bill, and Stacy" >>> pretty_list(["Bill", "Jorgan"], "or") "Bill or Jorgan" >...
cd66fe33026a8548d3dc9916070b15524d189f79
660,996
def clear_sentences(data): """ Cleaning sentences, removing special characters and articles """ sentences = list() for record in data: sentence = record['reviewText'] sentence = sentence.lower() for char in "?.!/;:,": sentence = sentence.replace(char, '') ...
91afa65c70be9386a658d0c74f317f647110740b
660,997
def _engprop(l): # {{{1 """Return the engineering properties as a LaTeX table in the form of a list of lines.""" lines = [ " \\midrule", " \\multicolumn{6}{c}{\\small\\textbf{Engineering properties}}\\\\[0.1em]", " \\multicolumn{3}{c}{\\small\\textbf{In-plane}} & ", ...
39e5f4bb61d4eee6fee7523921a8674bd31d9704
660,998
import os def firstdir(pathname): """Gets the first directory of the path. For example, if pathname is '/home/johndoe', this function returns '/home'. """ head, tail = os.path.split(pathname) if not head or head is '/': return tail else: return firstdir(head)
861ba1f0793c3ac6c69675320eb8bb96e1fa0747
660,999
def printc(thing, level): """ Print in colour :) """ cols = {"HEADER": "\033[95m", "STD": "\033[96m"} col = cols[level] print(f"{col}{thing}\033[0m") return ()
27737715c8b0375ee8fc0f4b608418d8c0269367
661,000
def install_package(module, depot, name): """ Install package if not already installed """ cmd_install = '/usr/sbin/swinstall -x mount_all_filesystems=false' rc, stdout, stderr = module.run_command("%s -s %s %s" % (cmd_install, depot, name)) if rc == 0: return rc, stdout else: retur...
1b3be8654a39f5573fb99281e28f6e99d66f4e39
661,001
def space_tokenize_with_bow(sentence): """Add <w> markers to ensure word-boundary alignment.""" return ["<w>" + t for t in sentence.split()]
888587477d8474a2cfdd248b5bb7ea492e0e0986
661,002
import collections def _common_observations(physics): """Returns the observations common to all tasks.""" obs = collections.OrderedDict() obs['egocentric_state'] = physics.egocentric_state() obs['torso_velocity'] = physics.torso_velocity() obs['torso_upright'] = physics.torso_upright() obs['imu'] = physic...
d2ec73f268cac80acbf1e0eaac54eef261f39cd4
661,003
def chunk_generator(l, batch_size): """ Given any list and a batch size, returns a list of lists where each element is a list containing N (BATCH_SIZE) elements. ----------------------------------------------------------- :param l: a 1-D list batch_size: Batch size of a chunk ---...
bcbd128cb5bdc2efe0600f8a378d2b856a642028
661,004
def extract_literal_string(memory,address,ztext): """ Extract the literal string from the given memory/address and return the new address + string """ zchar_start_address = address text, next_address = ztext.to_ascii(memory,zchar_start_address,0) return next_address,text
67ab2340af180803231a2b9e9c7a6dd4fddc3ecc
661,005
def get_text_from_file(filepath): """Returns a message text for QR taken from a text file.""" with open(filepath, 'r') as f: return f.read()
c4bee3b74ef33bf1aaabd96403149626393fdb39
661,006
def wrap_image(img_path, trailing_br=False, **kwargs): """Return a <img> markup, linking to the image in a URL""" _width = kwargs.get('width', '') _style = kwargs.get('style', '') if _style != '': _style = ' style="' + _style + '"' if str(_width) != '' : _width = ' width='+str(_wid...
860fc64c29010d386a981a178001962d2fb851d7
661,007
def _generate_barcode_ids(info_iter): """Create unique barcode IDs assigned to sequences """ bc_type = "SampleSheet" barcodes = list(set([x[-1] for x in info_iter])) barcodes.sort() barcode_ids = {} for i, bc in enumerate(barcodes): barcode_ids[bc] = (bc_type, i+1) return barcode...
90974c46b4a553e389ef9a18895a4110542ac3e0
661,008
from typing import Dict from typing import Any from typing import Optional def find_namespace( namespace: str, discovery_map_data: Dict[str, Any], ) -> Optional[Dict[str, Any]]: """Find the service-colors list for the given namespace.""" for namespace_obj in discovery_map_data['namespaces']: ...
3192434d77e3bbd59fcb36bed98198105564cdaa
661,009
def find_test_index(test, selected_tests, find_last_index=False): """Find the index of the first or last occurrence of a given test/test module in the list of selected tests. This function is used to determine the indices when slicing the list of selected tests when ``options.first``(:attr:`find_last_index...
c09008bd13840a72e976420442a3c794bada8341
661,010
def add_mpos_2site(mpo1, mpo2): """Sum of two 2-site MPOs acting on the same pair of sites. """ return (mpo1[0] + mpo2[0], mpo1[1] + mpo2[1])
e27354ef2c2f642a60ded9768153d12912016c3f
661,011
def calc_J(df_clust): """Calculate the total angular momentum of the cluster:: N J = Σ r_i × m_i * v_i i=1 :param df_clust: cluster data - position, velocity, and mass :type df_clust: pyspark.sql.DataFrame, with schema schemas.clust :returns: J, broken into components ...
a51291633c009d833e80cdee5deafa3e61bcae42
661,012
def levi_civita(tup): """Compute an entry of the Levi-Civita tensor for the indices *tuple*.""" if len(tup) == 2: i, j = tup return j-i if len(tup) == 3: i, j, k = tup return (j-i)*(k-i)*(k-j)/2 else: raise NotImplementedError
006e3c6c23e0a230a0ca3b12684f653e595ece11
661,013
def triangleType(x, y, z): """ Determine if the triangle is valid given the length of each side x,y,z. :param x: First side of triangle :param y: Second side of triangle :param z: Third side of triangle :returns: Whether a triangle is an 'Equilateral Triangle', 'Isosceles Tria...
b2530e79cc693c00d829ad68bbb10fff96e89ab6
661,014
def moeda(preco=0, moeda='R$'): """ :param preco: Valor a ser calculado :param moeda: Valor a ser acrescentado 'R$' :return: Valor calculado Formatado para duas casas decimais """ return f"{moeda}{preco:.2f}".replace('.', ',')
40002ce2b646df66ad873d637e06d441649382c6
661,015
def recipes_key(): """ Key for the recipes list. """ return 'G:recipes'
f1f5caad58f4d82e66ffd3a0cb64db4b59a654f1
661,016
import re def parse_version(v): """ A version is in the form <major>.<minor>.<patch><tag><tagnumber> <minor> and <patch> can be omitted (in which case they count for 0) <tag> and <tagnumber> are optional """ undotted = v.split('.') if len(undotted) == 0: raise ValueError("Versio number cannot be empty") if ...
2b043912e5ca205f71165db44d2dc28aedcb4f0c
661,017
def to_bin_centers(x): """ Convert array edges to centers """ return 0.5 * (x[1:] + x[:-1])
1f0a88243fd2f4d77295e0ed88004a1a8d1cdba7
661,018
import re def nearIntegersPredicate(field): """return any integers N, N+1, and N-1""" ints = sorted([int(i) for i in re.findall("\d+", field)]) near_ints = set([]) [near_ints.update((i - 1, i, i + 1)) for i in ints] return tuple(near_ints)
54285bbe2b0277951a5ebb93606e6a5183491f4b
661,019
from typing import Any import json def json_pretty_print(parsed: Any) -> str: """ Pretty print a json object. :param parsed: a json object :return: a prettified json object """ if isinstance(parsed, str): parsed = json.loads(parsed) # `ret = pprint.pformat(parsed) ret = json.d...
25e9c2f8d5c168379c7da6b0e4c16a09d84503d7
661,020
import os def listdir_paths(p): """ Like os.listdir, but yield full paths """ return (os.path.join(p, sub_dir) for sub_dir in os.listdir(p))
6b67af3d1ea20b51f6659714a26855d1fb92b27b
661,021
def create_user_vector(user_rating, movies): """ Convert dict of user_ratings to a user_vector """ # generate the user vector print(user_rating) user_vector = None return user_vector
8d546464c89f9dfeaed9c59da1b0f9248ef02fe1
661,022
def isinteger(number): """ This method decides if a given floating point number is an integer or not -- so only 0s after the decimal point. For example 1.0 is an integer 1.0002 is not.""" return number % 1 == 0
75c8e1a86d069609c069b2c33b0eb0ca02adf458
661,023
def _int_to_bin_str(value): """ This function returns the integer value in binary string of length 16. :param value: integer value to be converted to binary string. :return: None if 0 > value > 2^16-1 """ if 0 < value < (2**16): bits = bin(value)[2:] return ('0'*16)[len(bits):] +...
11c0142a34315134f995442034d49b169e8c1f20
661,024
def assert_raise(exception): """Marks test to expect the specified exception. Call assertRaises internally""" def test_decorator(fn): def test_decorated(self, *args, **kwargs): self.assertRaises(exception, fn, self, *args, **kwargs) return test_decorated return test_decorator
0cc4b3e5e4ff8ce9994199b1abb5174c745c4657
661,025
def decision_making(agents, directions): """ Let make a decision Actions: Forward, Right, Left, Backward :param agents: All agents :param directions: ['Reach goal', 'Unknown', 'Lane follow', 'Left', 'Right', 'Forward'] :return: Action and Action type """ a = agents[0] a.make_decision...
9e125969d09e8c588eff7c8a49a70c4d22b8902f
661,026
import torch def pytorch_random_uint32(rstate, shape): """Implementation of random_uint32 for pytorch.""" shape = tuple(dim.item() for dim in shape) rng = torch.Generator() rng.set_state(rstate) output = torch.zeros(shape, dtype=torch.int64) output.random_(0, 2 ** 32, generator=rng) return...
ee5c220279bc1588b58f83e173100e392097c98f
661,027
def _median3(comparables, lo, mid, hi): """Sort the three elements of an array in ascending order in place and return the middle index Arguments: comparables -- an array of which the elements can be compared lo -- index 1 (inclusive) mid -- index 2 (inclusive) hi -- index 3 (inclus...
dba0a932b71e438ea3783556b1f28c6c9efb267e
661,028
def median(series): """ Returns the median value of a series. Args: series (pandas.Series): column to summarize. """ # if np.issubdtype(series.dtype, np.number): # return series.median() # else: # return np.nan return series.median()
91462ec9ac99828d377d627eaee5f27f6a782289
661,029
import numpy def sfr_from_mass(mass): """Use Labbe et al. (2009) relation between stellar mass and SFR. See arXiv:0911.1356v4 Parameters ---------- mass: stellar mass in units of M_Sun Returns ------- sfr: the star formation rate in M_Sun / year. """ r...
fa214fb2d4f6fba9e5d1d8f52c455221c8c4c06c
661,030
import pytz def _make_timezone_naive_utc(datetime_object): """ If a given datetime is timezone-aware, convert to UTC and make timezone=naive """ if (datetime_object.tzinfo is not None) and (datetime_object.tzinfo.utcoffset(datetime_object) is not None): # Convert to UTC utc_time = datetime_ob...
b5ec2498907ec0f20159a339094862a26e64be8f
661,031
import logging def aggregate_metrics(raw_metrics, default_strategies, metric_strategies=None): """Aggregate raw TensorBoard metrics according to collection config. Available aggregation strategies: `final`, `min`, `max`. Args: raw_metrics: dict mapping TensorBoard tags to list of MetricPoint. default_...
78961acd181866db556cf679a51b7e183030fbba
661,032
def isFirstSection(section): """ Checks whether a Section model is the first one in its board. The order is determined by ascending section id (i.e. the section with the lowest id is the first section). Parameters: section (board.models.Section): The section to check. Returns: ...
648236da952b85c5418b66db5d7fd4d93666d2f5
661,033
import os def existing(path, subdir=None): """Returns existing directories only""" realpath = os.path.realpath join = os.path.join exists = os.path.exists pathname = ( path and subdir and join(realpath(path), subdir) or path and realpath(path) ) if pathname and exists(...
362768321f3dfb90c4646e5767da267aea7a6086
661,034
import copy def compair_csv_details(erp_tx, crm_tx): """ compair two csv and append the status result structure result = { "domain_name": { "domain":val, "customer_name":val, "cpr_cr":val, "contact":val, "email":val, "package_id":val, "package_desc":val, "carriage_return":val...
aededa060915334d53ef2dfca5bb3adefed505ca
661,035
def strip_byte_order_prefix(string, prefix_chars='<>|='): """ >>> from comma.numpy import strip_byte_order_prefix >>> strip_byte_order_prefix('<f8') 'f8' """ return string[1:] if string.startswith(tuple(prefix_chars)) else string
ebac18cfa0f211d88ecb32ca2a7c538515c63a48
661,036
def create_n_ride_data(size): """Create n ride request and return as a list""" ride_data = [] for i in range(size): ride_data.append({ "start_location": "Start from here%d" % i, "end_location": "End here%d" % i, }) return ride_data
c2891052385fee2b93190ab3791bb9b87c44ba23
661,037
import numpy def mask_op(base_array, value, nodata, target_nodata): """Mask array by specific value.""" result = numpy.empty(base_array.shape, dtype=numpy.uint8) result[:] = target_nodata valid_mask = base_array != nodata result[(base_array == value) & valid_mask] = 1 result[(base_array != val...
696c2da19a0281d5c604e65b71b9c98d6421fb7a
661,038
def _get_rings_with_atom(scaffold, aix): """list: Get indexes of rings containing an atom.""" return [rix for rix, r in enumerate(scaffold.rings) if aix in r.aix]
cf8411bd65c49ee553a7e0cab0f543c289d375c2
661,039
import os import fnmatch def findfiles(filefilter='*', basedir='.'): """ Recursively find files according to filefilter ** ARGUMENTS ** filefilter : str Filter for finding files. ie, '*.jpg' or 'file.txt' basedir : str Base directory to search. Default is the current directory...
27845f3bcb513dd8f75db548011f8d530d4de83e
661,040
def hmsm_to_days(hour=0, min=0, sec=0, micro=0): """ Convert hours, minutes, seconds, and microseconds to fractional days. """ days = sec + (micro / 1.e6) days = min + (days / 60.) days = hour + (days / 60.) return days / 24.
127cc131b6a1ee31f411fc9493601dc6c09fe786
661,041
def remove_optimized_key_from_ai_list(key_list: list, optimized_dict: dict): """ :param key_list: :param optimized_dict: :return: """ for key, value in optimized_dict.items(): if value in key_list: ind = key_list.index(value) key_list.pop(ind) return key_list
9a9c8115d27384b8a8a899f2a262c41b2c3146f2
661,042
def get_probe_2(table_name='filtered_links_dated'): """Create SQL query to select repo_id, linked_repo_id, and created_at from table_name.""" inputs = (table_name,) qry = "SELECT repo_id, linked_repo_id, created_at FROM %s" return qry, inputs
1fe6172041d334a22b987e0b11fb2ed14a802e63
661,043
def init_bitstring_groundstate(occ_num: int) -> int: """Occupy the n lowest orbitals of a state in the bitstring representation Args: occ_num (integer): number of orbitals to occupy Returns: (integer): bitstring representation of the ground state """ return (1 << occ_num) - 1
dba19dc9fb3930d85dc47998e375de394d4c062d
661,044
def greatest_decrease_in_profits(csv_data): """ Return the lowest value of the "Profit/Losses" column and its month. This calculates the changes between the current month and last month, and saves the results into two lists: month_list change_list Then it will find the smallest value in...
d617e1d0c4fbe327a5ff07b92ec4fbad3f60c371
661,045
def is_name_private(name, public=None): """ Answers whether the name is considered private, by checking the leading underscore. A ist of public names can be provided which would override the normal check """ if public and name in public: return False return name.startswith('_')
879fbfadc43c45dc67c4199da12a7994349ef1da
661,046
def compareDfs(df1, df2): """ compares df1 to df2 shows col difference, index difference, nans & 0s differences """ nmissmatchCols = set(df1.columns)-set(df2.columns) omissmatchCols = set(df2.columns)-set(df1.columns) nmissmatchInds = set(df1.index)-set(df2.index) omissmatchInds = set(d...
18e79547503371bebde9b29a714c90f5dabae0fa
661,047
def get_str(db,name): """ Get a string from the redis database. """ data_unicode = db.get(name) return str(data_unicode)
53a1bd62bc6b5e23c5d265ff12e16a42ee9d01fd
661,048
def mask(arr,pixels,val=0): """Mask an array arr based on array pixels of (y,x) pixel coordinates of (Npix,2)""" arr[...,pixels[:,0],pixels[:,1]] = val return arr
3acc519fd7596b6be406723b54d021cf5f31de9b
661,049
import time def time_shift(func): """ This time shift function wrapper is used to modifiy the computing time which ns3 cannot simulate. We use the wall-clock time times 30 to denote the computing time for each task. """ def wrapper(*args, **kwargs): t_now = time.time() func(*args, **kwargs) return 10*(ti...
daa98bed7210a1f95684646adcfa3d79f7c687c4
661,051
import re def parse_help_text(helptxt: str) -> str: """Parse a help text""" # Remove // and tubs at the beginning of each line parsed = re.sub(r'^//\s*', '', helptxt, flags=re.M) # Make variable names bold and make types bold italic parsed = re.sub(r'^([a-zA-Z].*?:)\s*(.*)$', r'\n**\1** ***\2***...
0e338c42ad3415858e527b3655200263bba9a4fc
661,052
def check_chain(object_to_del, **kwargs): """Checks for View's object""" check = False check_list = [False] * 1 check_list[0] = not object_to_del.allocated_item_list if not check_list[0]: print(f"{object_to_del.name} has allocation relationship(s)") if all(check_list): check = ...
bc8969a21535136cb670914901531f3274835dd9
661,053
def get_user_data_list(): """Gets the list of the public datasets from GEE users. Returns: list: The list of public datasets from GEE users. """ extra_ids = [ "countries", "us_states", "us_cities", "chn_admin_line", "chn_admin_level0", "chn_admin_...
0ef4a5c9781b54c08a7ee2a69035670f05eea184
661,054
import logging def INFO(target): """A decorator to set the .loglevel attribute to logging.INFO. Can apply to either a TestCase or an individual test method.""" target.loglevel = logging.INFO return target
8bf2061b248a457131486687a32440ce68d173b5
661,055
def dict_apply_listfun(dict, function): """Applies a function that transforms one list to another with the same number of elements to the values in a dictionary, returning a new dictionary with the same keys as the input dictionary, but the values given by the results of the function acting on the input dictionary...
1d6fb556d566e01c1547a36b548de9d8ccd22976
661,056
def file_names(inp_fname): """Return the linkname and filename for dotfile based on user input. """ link = inp_fname if inp_fname.startswith('.') else ".{}".format(inp_fname) return link, "dot{}.symlink".format(link)
fe639780abf1537b79e6e71ddc08d44223c4ba00
661,057
def create_dict(key_list, val_list): """ The function creates dictionary from given key_list and value_list :param key_list: :param val_list: :return: Dictionary of type (key:val) """ temp_dict = {} for arg in range(len(key_list) - 1): temp_dict[key_list[arg]] = val_list[arg] ...
b590ff3ea0d168d7c9f1dc9a49c9d05428194d2e
661,058
import torch def krylov(L, A, b): """ Compute the Krylov matrix (b, Ab, A^2b, ...) using the squaring trick. """ x = b.unsqueeze(-1) # (..., N, 1) A_ = A done = L == 1 while not done: # Save memory on last iteration l = x.shape[-1] if L - l <= l: done = True ...
5850ca6415af7e03af178d956e8649c66a5046fd
661,059