content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import re def findVars(expression): """Finds and extracts the variables in an expression using regex pattern matching. Returns a list of matches in the given string.""" variableRegex = re.compile('[a-zA-Z][a-zA-Z0-9]*') variables = re.findall(variableRegex, str(expression)) return variables
c794ec2f5e49d0c5cf006d8bbc5718bd28161e49
637,646
import os import re def sanitize_lib_name(library_path): """ Get a fully-qualified library name, like /usr/lib/libgfortran.so.3.0, and returns the lib name needed to be passed to the linker in the -l option (for example gfortran) :param library_path: :return: """ lib_name = os.path.basen...
da7245e6780dfcfbc9c1694a6968b747ee0870c7
637,648
def cif2float(cifnum): """ Convert a cif-floating point number that may include an uncertainty indication to a proper floating point number. In a .cif file the value "0.4254(4)" is a floating point number where the digit in brackets gives the uncertainty. To convert this number to a regular Pyt...
ecac9f0aeff17da6b38355cf87c9fcc35a6a025f
637,649
import re def splitCIGAR(CIGAR): """ Takes CIGAR string from SAM and splits it into two lists: one with capital letters (match operators), and one with the number of bases """ matchTypes = re.sub('[0-9]', " ", CIGAR).split() matchCounts = re.sub('[A-Z]', " ", CIGAR).split() matchCounts = [in...
e579bb6254ff1edf9378a0fbddd61975f38456d9
637,650
def set_queued_batch(db, list_url_hash): """Try to set batch of urls to queued""" result = db['Urls'].update_many({'_id': {'$in': list_url_hash}}, {'$set': {'queued': True}}) return result is not None
e9b068219afc619cc2cac0564e364041dc572c9f
637,651
def extend_padding(ls_of_ls, padding=''): """ Takes in a lists of lists, returns a new list of lists where each list is padded up to the length of the longest list by [padding] (defaults to the empty string) """ maxlen = max(map(len, ls_of_ls)) newls = [] for ls in ls_of_ls: if l...
f9316ae9853f5ced56cf9dbb80abd00b18a72fe3
637,652
def _crawl(name, mapping): """ ``name`` of ``'a.b.c'`` => ``mapping['a']['b']['c']`` """ key, _, rest = name.partition('.') value = mapping[key] if not rest: return value return _crawl(rest, value)
ac82ab46cce5187ae50c3943b24aa42657f1ffc4
637,653
def get_enum(key_list, enum_dict): """Returns the mcf format of enum dcid list that represents a given value(s). Used to convert a list of values which map to enums to their appropriate enum dcid, as given by the enum_dict. For this import, enum_dict is either ASSOCIATION_ENUM_DICT or EVIDENCE_ENUM_DIC...
defacb5a052459e4d085a3d4c5ec2922fb042542
637,654
def verileriAl(dosyaAdresi): """ dosyaAdresi parametresindeki dosyanın her bir satırını bir listenin elemanı olacak şekilde geri döner. :param dosyaAdresi: Okunacak dosyanın bilgisayardaki adresi """ return [float(i) for i in (open(dosyaAdresi,"r+",encoding="UTF8",errors="ignore"))]
25d0752519a64cfbd16faa2c162a7909ba08cdb2
637,655
import re def loxi_name(ident): """ Return the LOXI name of an openflow.h identifier """ # Order at the outer level matters as super strings are listed first rules = [ # The following are for #define macros and have highest precedence dict(OFP_MAX_TABLE_NAME_LEN = "OF_MAX_TABLE_NAME_LEN")...
3c9a0e369a6368b105fefc04869ebe7d730866bd
637,656
def rotate_list(alist): """Pop the last element of list out then put it into the first of list. :param alist: A list that want to rotated. :return alist: A rotated list. """ assert type(alist) == list last = alist.pop() alist.insert(0, last) return alist
d3fefe92870aea63e51fff82c274990a0d9151f6
637,657
def _compile_drop_table(element, compiler, **kwargs): """ Drop table cascade with foreignkeys https://stackoverflow.com/questions/38678336/sqlalchemy-how-to-implement-drop-table-cascade# """ return compiler.visit_drop_table(element) + " CASCADE"
afa6364275a2dd4baaab6e45f1ac18a662298179
637,658
def additive_hash(key): """Hash string by adding up the values of the characters.""" if not isinstance(key, str): raise TypeError("Key must be a string.") hv = sum(ord(letter) for letter in key) return hv
3ab2ec14fb69b634602dab14d6c8042709c27b11
637,659
def downgrade_sample_rate_of_labels(labels, original_sample_rate, needed_sample_rate): """This function downgrades sample rate of provided labels to needed_sample_rate It is worked through calculating ratio between original_sample_rate and needed_sample_rate and then thinning provided labels :par...
658d97557ae11c9d3b7514f03c309a3cbfe9e18a
637,660
def union(left, right): """:yaql:union Returns union of two sets. :signature: left.union(right) :receiverArg left: input set :argType left: set :arg right: input set :argType right: set :returnType: set .. code:: yaql> set(0, 1).union(set(1, 2)) [0, 1, 2] """ ...
f917cca8511b5731c84b48da0cc856fc6fedddb8
637,661
import os import shutil def _MoveAndReplaceFile(src_file, target_parent_dir): """Moves the file under target directory and replace it if it exists.""" new_file_path = os.path.join( target_parent_dir, os.path.basename(src_file)) if os.path.exists(new_file_path): shutil.rmtree(new_file_path) shutil.mo...
47577773c681a58be5017dd62464dd40fcd88d5f
637,662
import json def read_params(): """ Reading the parameters from the JSON file.""" with open("params.json", "r") as f: data = f.read() params = json.loads(data) return params
99f1e73ce519450e6201d56c792bb522b32d3548
637,664
def fullname(o): """ Gives a full name (package_name.class_name) for a class / object in Python. Will be used to load the correct classes from JSON files """ module = o.__class__.__module__ if module is None or module == str.__class__.__module__: return o.__class__.__name__ # Avoid reporting __built...
134d50e292967c89e03b5e8708b6015dba2485a6
637,665
def Status2Int(protect_status): """ returns the int-value related to the input-str Read / Write := 0 Write protect := 1 """ rtn_value = 0 if 'yes' in protect_status.lower(): rtn_value = 1 return rtn_value
827736cf11981d7fc239cab59444b3b21dc246a5
637,666
def compute_normalized_rho_pars(u, b): """Compute normalized rho_0, rho_min given b, u=rho_min/rho_0 Parameters ---------- u : `float` u = rho_min/rho_0 parameter. b : `float` b parameter Returns ------- rho_0, rho_min : (`float`, `float`) """ rho_0 = ((b + 2)/(...
186aa4c62812d216edbe2bd2ca309cfbd2c668cd
637,667
def get_Theta_tnk_ss(): """ソーラーシステムのタンク内温度 (℃) Args: Returns: float: ソーラーシステムのタンク内温度 (℃) """ return 65.0
c41711a24db3876b3d7f4a98bddad53a22c8bc29
637,669
def authInsert(user, role, group, site): """ Authorization function for general insert """ if not role: return True for k, v in user['roles'].iteritems(): for g in v['group']: if k in role.get(g, '').split(':'): return True return False
e30ab7f7210cf270387aa517218db47e4a828fd3
637,670
def return_success(data=None): """ Generates JSON for a successful API request """ if data is None: return {"success": True} return {"success": True, **data}
f780a1e2d9c1c6e3b2be20db3b97717d3836adee
637,671
import re from typing import Counter def text_entities(text, nlp): """Extract entities: Person, Org, Product, Gpe""" try: symbol_reg = r'[|,\/,(,),/\n,/:]' text = re.sub(symbol_reg, ' ', text) doc = nlp(text) entities = [] for ent in doc.ents: entities.appe...
a4b04f104b792d2f20c9e1ea64966d4744a1d445
637,672
def get_dir_and_name(abs_path_pdf): """ Return the abs path of pdf directory AND the name of the PDF (without .pdf). Example of returned dir path: C:/this/is/an/abs/path """ if not abs_path_pdf == '': abs_path_dir = abs_path_pdf[:-4] # remove '.pdf' extension name = '' while ab...
3cde86681095e82212904d44c5f272f679ed4c94
637,673
def writeInstance(sheet): """ 写入表头和实例 :param sheet: :return: True|False 是否写入成功 """ sheet.write(0, 0, '学号') sheet.write(0, 1, '姓名') sheet.write(0, 2, '年龄') sheet.write(0, 3, '性别') sheet.write(0, 4, '班级') # 写入第一行的实例内容 sheet.write(1, 0, '导入数据时,学号必须为空') sheet.write(1, 1, ...
74555d82512fcd131be119277c63f7423d66bafa
637,674
import re def split_by_punc(segment): """ splits str segement by """ return [s for s in re.split("r\+W", segment) if s and not s.isspace()]
e77da848a0698f245f046611d431fa5987511c90
637,675
def on_whitespace(s): """ Returns tokens taking whitespace as word boundaries >>> on_whitespace('This is not a test.') ['This', 'is', 'not', 'a', 'test.'] Args: s: a string Returns: list: a list of strings """ return s.split()
25960ed620d77dcc0b4eb723f585a2d4a5d5734e
637,676
def get_user_id(user_id: str) -> str: """ Formats the user_id to a plain format removing any <, < or @ :param user_id: slack id format :type user_id: str :return: plain user id :rtype: str """ return user_id.strip("<>@")
7e69ecf3e67607aba947a7980703f50f23d10c5f
637,677
import time def timer(f, *args): """ call f with args :param f: :param arg: :return: """ start = time.time() f(*args) end = time.time() return end - start
9764cd08f3e56e62613a4bd7f752d65e255e6cac
637,678
def converter(temperatures, convert): """Returns a sequence that converts each Celsius temperature to Fahrenheit >>> def convert(x): ... return 9.0*x/5.0 + 32 >>> temperatures = [10, 20, 30, 40, 50] >>> converter(temperatures, convert) [50.0, 68.0, 86.0, 104.0, 122.0] """ return [co...
09ca4bff8999b6721e4f9c28767db01016bf0974
637,679
def _modify_instance_state_response(response_type, previous_state, new_state): """ Generates a response for a Start, Stop, Terminate requests. @param response_type: Cloudstack response. @param previous_state: The previous state of the instance. @param new_state: The new state of the instance. @...
cfb4c84f5cbeaa076f6d7d5ebd384cd1e8f98e99
637,680
def firmVolumeFrac(volume, shares, sharesUnit=1000): """ Fraction of shares turned over Returns FLOAT """ # SHROUT in thousands shares_out = shares * sharesUnit return volume / shares_out
e1c4c27d41ee2f13fd68a0451a1d07b24c67b139
637,681
def clean_specie_name(specie_str: str) -> str: """ Clean up the species name from '<element>\xa0<roman number for oxidation state>' to '<element>' """ return specie_str.split("\xa0")[0]
fd5f435982fca9471b08cf02b217fd849c38fee6
637,682
def is_integer(value, cast=False): """Indicates whether the given value is an integer. Saves a little typing. :param value: The value to be checked. :param cast: Indicates whether the value (when given as a string) should be cast to an integer. :type cast: bool :rtype: bool .. code-block:: p...
c2fd05d572be8cd799480e953b0282c59b24c649
637,683
def _GetPropertyValue(dtb, node, prop_name): """Low-level function to get the property value based on its offset This looks directly in the device tree at the property's offset to find its value. It is useful as a check that the property is in the correct place. Args: node: Node to look in...
9903ae4da8cab3e7bb2aa5c7ffa1869ef928084e
637,684
def ConvertPrivateIpv6GoogleAccess(choice): """Return PrivateIpv6GoogleAccess enum defined in mixer. Args: choice: Enum value of PrivateIpv6GoogleAccess defined in gcloud. """ choices_to_enum = { 'DISABLE': 'DISABLE_GOOGLE_ACCESS', 'ENABLE_BIDIRECTIONAL_ACCESS': 'ENABLE_BIDI...
fa7520e364d7b489c04015acc88637c1c92571cd
637,685
def _bitcmp(bit, bit_ref, wildcard='x'): """ Compares the string representation of a binary number ignoring any bits on the reference string 'bit_ref' marked with a wildcard. """ bit = bit.replace('0b', '') bit, bit_ref = list(bit), list(bit_ref) bit.reverse(); bit_ref.reverse() # Start comp...
0f14022f369e5bf4dd9dbb292c95082a795c894f
637,686
import random def random_saturation(im, lower=0.5, upper=1.5): """Random change saturation Args: im(numpy.array): one H,W,3 image lower(float): change lower limit upper(float): change upper limit """ if random.random() < 0.5: im[:, :, 1] *= random.uniform(lower, u...
f81fe55559afc28a727622426f90475fea5d0fa5
637,687
import inspect def in_main_process(): """Whether current process is worker process or main process. """ for frameinfo in inspect.stack(): if "spawn_main" == frameinfo.function: return False return True
f87c7a54baf154620b26af76015d9d40c74cc2fb
637,688
def make_complex_matrix(m): """ Transforms a block 2x2 matrix of real and imaginary part into a complex matrix :param m: block 2x2 real matrix as numpy/scipy array :return: complex matrix as numpy/scipy array """ return m[:m.shape[0]/2, :m.shape[1]/2] + 1j * m[m.shape[0]/2:, :m.shape[1]/2]
143db8755d2cf5258bc7bae4786bc6c4edd9230d
637,689
from datetime import datetime def fmt_timestamp(ts=None): """ Jinja filter to format date/time from timestamp. """ if ts is None: return 'no-timestamp' dt = datetime.fromtimestamp(int(ts)) pretty_time = dt.strftime('%m/%d/%y %I:%M %p') return pretty_time
ccd30f229532ff1f26d35a79a44526e606c87e13
637,690
def get_coverage(method, method_dict, coverage=None, chain=None): """Recursively chase down coverage for a method, returning a list of what is covered""" # recursion safety if not chain: chain = [] elif method in chain: return method_dict[method].get("covers") else: chain.app...
38905c18d9f0739265c754b7c4fac8db4af00b2e
637,691
def calculateHammingSyndrom(byte): """Calculates hamming syndrom""" #S0 = C1 xor C3 xor C5 xor C7 xor C9 xor C11 S0 = str( int(byte[1]) ^ int(byte[3]) ^ int(byte[5]) ^ int(byte[7]) ^ int(byte[9]) ^ int(byte[11]) ) #S1 = C2 xor C3 xor C6 xor C7 xor ...
2c4eae1dbba90eb58647ff6dc152907b25b99a05
637,692
import os def set_file_names(project, version): """ Infer input tsv and scp_bq_inputs.json file locations from project, version info If input tsv doesn't exist, exit If scp_bq_inputs.json doesn't exist, exit If metadata convention file already exists, exit """ inputname = f'../schema/{proj...
86dead4c22407d2966a151499136fdbc2e125882
637,693
import codecs def load_utf8(filename): """Load UTF8 file.""" with codecs.open(filename, 'r', encoding='utf-8') as f: return f.read()
9ce0f51879b2bc4b83690fb06a0353c3c73235cb
637,694
def build_info(file_name, meta_features): """Builds the info of a dataset in a presentable manner""" info = {'dataset': int(file_name[:-5])} for feat_name, value in meta_features.items(): new_name = feat_name.replace("_", " ") info[new_name] = value return info
8e8291fb17034afe14274e4955e48a630c03dfe7
637,695
def formset_model_name(value): """ Return the model verbose name of a formset """ try: return value.model._meta.verbose_name except AttributeError: return str(value.__class__.__name__)
8222cd9eeb2bf2e5b01ce570e7e0937a87bd4a3f
637,696
import os import subprocess def submit_given_jobs(shfile, logger, mt, mm, cores, env=""): """ for a given sh file, submit to cluster, return job id """ sample_name = shfile.split(".")[0].split("_")[-1] sh_dir = os.path.dirname(shfile) log_f = os.path.join(sh_dir, f"Mut_count_{sample_name}.log"...
60183a716bf25097390583c1b6836c7200e0b76d
637,697
import time def utc_local_time_shift(): """ Return the expected time shift in seconds assuming the server uses UTC in its listings and the client uses local time. This is needed because Pure-FTPd meanwhile seems to insist that the displayed time for files is in UTC. """ utc_tuple = time.g...
35fdbb2f7b905b2b1b897162969f91b8f2d411f5
637,698
def switch_block(LIB) -> str: """Returns hash of most next switch. """ return LIB.get_switch_block()
1206d4625d2039a95dc7cfac916cf82008790e56
637,699
def train_test_split(features, target, split_ts): """ Splits all provided TimeSeries instances into train and test sets according to the provided timestamp. Parameters ---------- features : TimeSeries Feature TimeSeries instances to be split. target : TimeSeries Target TimeSerie...
0d803476cc53f35f9b1171e1835366e408741442
637,700
def password(request): """The password to use for fetching.""" return request.config.getoption("--password")
05acf2e56fc2fd5f8b8382ff12d5f670a7f1c379
637,701
import colorsys def hs_to_hex(hue: float, saturation: float) -> str: """Convert hue and saturation to a string hex color.""" rgb = colorsys.hsv_to_rgb(hue / 100, saturation / 100, 100) return "#{:02x}{:02x}{:02x}".format( round(rgb[0]), round(rgb[1]), round(rgb[2]) ).upper()
ad47cb84c4d656584b2051a66281aeb858bc7b80
637,702
def phi(x, y, ck, i): """ The linear basis functions Parameters ---------- x : np.array x-values. y : np.array y-values. ck : np.array basis function coef. matrix. i : int which basis function to use. Returns ------- numpy.array basis...
0277396c935ca9af555d9f253808227cf295c647
637,703
def convert_to_binary(decimal) -> str: """ Converts Decimal numbers into Binanry Digits """ binary = bin(decimal).replace("0b", "") return binary
604ce5b785d6f655da86cf3f55882b8a79d6bfd2
637,704
def performance_measure(y_true, y_pred): """ Compute the performance metrics: TP, FP, FN, TN Args: y_true : 2d array. Ground truth (correct) target values. y_pred : 2d array. Estimated targets as returned by a tagger. Returns: performance_dict : dict Example: >>> f...
83d2382cc35836275ebfc4badfbc023bb9a9340c
637,707
import torch def prep_images(images): """ preprocess images Args: images: pytorch tensor """ images = images.div(255.0) images = torch.sub(images,0.5) images = torch.mul(images,2.0) return images
5faa9cc5f5fe33b56719437329fd213b5325fab5
637,708
def source_type_normalize(source_type): """ Make it easier to ignore small inconsistencies in these key word arguments. >>> source_type_normalize("journals") 'journal' >>> source_type_normalize("Journal") 'journal' """ ret_val = None normal = {"journals": "journal", "...
e4aa0a5e59eca8498f318f8f7204da9cb864475a
637,709
def is_valid_team(team: str) -> bool: """Filters out players who played for multiple teams, were primarly on the practice squad, or were free agents. Args: team_col (str): Name of the column indicating the player's team """ invalid_team_values = ["", "2TM", "3TM", "4TM"] if team in i...
1c8dac199c0161db1fd91558388c2e4a4f2d2e94
637,710
from unittest.mock import Mock def sqs_client_mock(): """ :rtype: Mock """ client = Mock(spec=['delete_message', 'get_queue_url', 'receive_message']) client.get_queue_url.return_value = {'QueueUrl': '__dummy_url__'} return client
a0264c491c3c2139b36b754397126bba05fe9d11
637,711
import os def is_running_on_actions(): # type: () -> bool """Returns True when running on GitHub Actions""" # See the following document on which environ to use for this purpose. # https://docs.github.com/en/free-pro-team@latest/actions/reference/environment-variables#default-environment-variables ...
4280873ef41c097335d75b64ad06e29078839233
637,712
import configparser def get_defaults(): """This reads the config file to return two lists of values, which will be the default values for the fields. Since we are zipping the defaults and the controls, you *must* add a default value for any new control. Otherwise, the control won't be created.""" conf...
2a6e6f3f3d480acb03f85b1daf67896b48decc11
637,713
def fmt_build_map_unpack_with_call(vm, arg, repr=repr): """returns string of the repr() for the first element of the evaluation stack """ # See corresponding comment in BUILD_MAP_UNPACK_WITH_CALL if vm.version == 3.5: fn_pos, count = divmod(arg, 256) fn_pos = count + fn_pos else:...
9afeef38df69a1b5a9a7ec40f079f0f3a5d92981
637,714
def csdele(self, kcn1="", kcn2="", kcinc="", **kwargs): """Deletes local coordinate systems. APDL Command: CSDELE Parameters ---------- kcn1, kcn2, kcinc Delete coordinate systems from KCN1 (must be greater than 10) to KCN2 (defaults to KCN1) in steps of KCINC (defaults to 1). If ...
6a6847079506af51cd7fa3e5c1c17ab59f6c93df
637,715
import logging def get_new_parameter_list_for_update(stack, expected_value, new_value, parameter_to_change, force=False): """ Given a list of possible parameter names, generate a new parameter list with existing_value changed to new_value :param stack: the stack to mine the parameter list from :pa...
49dc28b884ec77e7920b9c04cb3789dc813aa130
637,716
import itertools def nth(iterable, n, default=None): """ Returns the nth item or a default value. This code is mildly adapted from the documentation. N.B. This returns the *base-0* nth item in the iterator. For example, nth(range(10), 1) returns 1. """ return next(itertools.islice(iterable,...
c55431eaaee29c323e5f05d3049572b65813b029
637,717
def _num_to_list(num, length): """ 258, 2 -> [1,2] :param int num: :param int length: :rtype: list """ output = [] for l in range(length): output = [int((num >> 8*l) & 0xff)]+output return output
d48d257052d99370761ef19390ed67184bef6a43
637,718
def SEAIR_D(t, population, initial_conditions, Ro, start_intervention=10, intervention_duration=50): """ Esta parte de código es la que implementa las ecuaciones diferenciales. Se resuelven por medio de integración númerica de Euler """ initial_cases = initial_conditions['initial_cases'] expo...
36907df5d04bdf605ce64f83041b1de8e85c185c
637,719
def _get_prep_params(data): """Retrieve configuration parameters with defaults for preparing BAM files. """ algorithm = data["config"]["algorithm"] dup_param = algorithm.get("mark_duplicates", True) dup_param = "picard" if dup_param is True else dup_param recal_param = algorithm.get("recalibrate...
9c6e63525618778644173c1bcd0fff13322b8890
637,721
import asyncio async def compute_fancy_greeting(name: str, seen: int): """ Compute a personalized greeting, based on the number of times this @name had been seen before. """ templates = ["", "Welcome %s", "Nice to see you again %s", "Third time is a charm %s"] if seen < len(templates): gre...
45c9159e4ac724c6df4c4e86807c3fd8d2397eee
637,722
def transform(data, median, var_25_75): """Scale data using robust estimators. Scale the data by subtracting the median and dividing by the variance, i.e. the difference between the 75th and 25th percentiles. Parameters ---------- data : pandas DataFrame, shape (n_spectra, n_freq_point...
91b74ec87ec9cf65e4accb7a3ebd02d3ab7a7e5e
637,723
def extract_trigram_from_doc(doc): """ The function receives a (parsed) spaCy document and is expected to return a tuple of tokens representing the first three tokens from the question. The function returns None if a trigram cannot be extracted (e.g. the question is too short. Some questions have m...
4ee353cc04cf3c85975a62d1746a6946301f0d40
637,724
def get_tags(entities): """ Args: entities (Iterable[Entity]): the entities in a sentence Returns: Set[str]: a set of their tags, excluding 'O' """ return {entity.tag for entity in entities} - {'O'}
21cbdeca18d9c8a3dc367db33b41e47c7e6905c6
637,725
def super_overridden(cls): """ This decorator just serves as a reminder that the super function behaves differently. It doesn't actually do anything, that happens inside ``classhook.hook_class``. """ cls.__rootpy_have_super_overridden = True return cls
0a453370cb5342b4bb8ddd4259ad62db04580862
637,727
def g(x, y): """ A multivariate function for testing on. """ return -x**2 + y
a134054e8731bd81c2f91980e71ede051dfc305f
637,728
def verb_check(tag): """ :param tag: a string representing a POS-TAG :return: boolean if the given tag belongs to the verb class """ return tag in ['VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ']
3aeafc50f854c8a630c0702d2221d87315e6bc40
637,729
import os def enc_zip(rootdir): """Returns an EncryptedZipFile instance with a test zip""" test_zip = os.path.join(rootdir, "cats.zip") return test_zip
cd686f967404a76e4a26d8d5d6cf062390e51f01
637,730
from pathlib import Path import os def load_noimage_group(): """グループのNoImage画像を取得します""" noimage_group_path = ( Path(os.path.dirname(__file__)) / "app/static/noimage_group.png" ) with open(noimage_group_path, "rb") as f: noimage_group = f.read() return noimage_group
1bd16a25d6c76d0bd48935b2a2025246a3e2215d
637,731
def parse_connector_version(version): """Parse a connector version string into a tuple (hadoop version, major version, minor version, patch version, release candidate).""" hadoop_version, version = version.split("-", maxsplit=1) hadoop_version = int(hadoop_version[6:]) release_candidate = None if "...
60a8c817e7d725d9b07201e2e4276c52e2932d39
637,732
def supports(codec): """ Return a list of strings indicating supported operations. """ if hasattr(codec, 'encode') and hasattr(codec, 'decode'): return ['encoding', 'decoding'] elif hasattr(codec, 'encode'): return ['encoding'] elif hasattr(codec, 'decode'): return ['deco...
98b66790b51d054ee030acb95d787478270a2061
637,733
import torch def gauss_interp(pc1, pc2, pc1_value, sigma, conservation=True): """ :param pc1: (batch, 3, num_points) :param pc2: (batch, 3, num_nodes) :param pc1_value: (batch, channel, num_points) :param sigma: float :return: (batch, channel, num_nodes) """ weight = torch.exp(-(pc2.un...
047904b43476588fbf6e9c9b9c468ae2944811ee
637,734
def simple_compare_dict(dict1, dict2): """ accepts multi-level dictionaries compares values as strings, will not report type mismatch """ if sorted(dict1.keys()) != sorted(dict2.keys()): return False for key, value in list(dict1.items()): if isinstance(value, dict): ...
b8301aa9553b1080a4489b814495e0ee0514b46f
637,735
def vertices_generation(number_of_vertices): """ Generate the vertices list :param number_of_vertices: :return: vertices list in format [0, 1, 2, 3...] """ # here, the list is much more efficient than set return [s for s in range(1, number_of_vertices + 1)]
3b05d7711092bb094bf214d94c4237b0a8c12ccc
637,736
def norm2d_cx(cx, in_c, trainable=True): """Accumulates complexity of norm2d into cx = (h, w, flops, params, acts).""" c, params = cx["c"], cx["params"] assert c == in_c cx["params"] += 4 * c cx["freeze"] += 2 * c # moving_mean, variance if trainable is False: cx["freeze"] += 2 * c # b...
437ea738f87fd74765aaf25cb351a8008a06d1ec
637,738
def compute_parity_log(x): """use the property of p(00110101) = p(0011^0101) to cut the input size into half each time until you get to 1 bit, or the smallest size and use cache to get the result directly. half the input size each time, so O(log n) where n is the word size """ # assuming on 64 bit m...
e3f836662fa112b1982f4061d379ad1c1ac0d457
637,739
def parse_ids_names(ids__names): """Parse ids__models list.""" ids = [int(i) for i in ids__names if i.isdigit()] return ids, ids__names
41879c27e011d03818861fe83bbdde8847dcb191
637,740
def get_E_pump_hs_d_t(E_pump_SW_d_t, E_pump_gsRW_d_t): """日付dの時刻tにおける1時間当たりのポンプの消費電力量 (8) Args: E_pump_SW_d_t(ndarray): 日付dの時刻tにおける1時間当たりの送水ポンプの消費電力量(kWh/h) E_pump_gsRW_d_t(ndarray): 日付dの時刻tにおける1時間当たりの熱源水ポンプの消費電力量(kWh/h) Returns: ndarray: 日付dの時刻tにおける1時間当たりのポンプの消費電力量(kWh/h) """ ...
d99d537afed9e06ba5fa87f41340301d2f9d9900
637,741
def txt_category_to_dict(category_str): """ Parameters ---------- category_str: str of nominal values from dataset meta information Returns ------- dict of the nominal values and their one letter encoding Example ------- "bell=b, convex=x" -> {"bell": "b", "convex": "x"} ""...
d7a4e6c0e3e08fcc3af56d3408b722f99e522a07
637,743
def decode(val): """Try to decode a string, and don't stop code execution if it fails. Args: val (str): Should be a string. Returns: str: Should also be a string. """ if val is None or str(val) == str(''): return None if str(str(val).strip()) == str('NULL'): re...
19c1ac546bf6ca4f227393874c827e59d77a3c66
637,744
import logging def get_logger(name): """Returns a customized logging object. Multiple calls to with the same name will always return a reference to the same Logger object. Args: name (str): Dot-separated hierarchical name for the logger. Returns: Logger: An instance of :any:`logging...
44996c138119696ec0f9ae5a3f659bfee4efa168
637,745
def derive_http_method(method, data): """Derives the HTTP method from Data, etc :param method: Method to check :type method: `str` :param data: Data to check :type data: `str` :return: Method found :rtype: `str` """ d_method = method # Method not provided: Determine method from ...
9fd1941c2de86fdf3a06eb05a6e7046705cb4cd3
637,746
def get_pending_active_nodes(**output_dict): """ Get the pending active node information, no deadnet info is available """ out_dict = {} node_count = 0 response_json = output_dict['ListPendingActiveNodes'] for node in response_json['result']['pendingActiveNodes']: node_id = str(node[...
5deca4cb47a354d1eb15f4c62f4cdc58b92b43c1
637,747
def headers_to_json(headers) -> list[dict]: """ For getting a usable header array for the ui :param headers: Headers as a tuple array :return: Headers as a json object array with attributes for key and value """ res = [] for header in headers: value = '<unsupported encoding>' ...
b28391c5fa642fc119f62c974ba950e00c42a36f
637,748
import time def encode_tag(prefix, time_tuple, time_format): """ Create a [prefix:time] playlist tag using specified time formatting. Args: prefix ::: (str) unique identifier for playlist series time_tuple ::: (`time.struct_time` instance) time to encode in tag time_format ::: (str) f...
66dbf81bc424bdb2f8abed47c8cab527c034c6ee
637,750
def drop_dupes(sequence): """Drop duplicate elements from a list or other sequence. C.f. https://stackoverflow.com/a/7961390 """ orig_type = type(sequence) return orig_type(list(dict.fromkeys(sequence)))
ff8380212264eb2fa4aa3f3fbc747c9e41f22984
637,752
def wmlfindin(element, scopeElement, wmlItor): """Find an element inside a particular type of scope element""" for itor in wmlItor.copy(): if element == itor.element: if itor.scopes: if scopeElement == itor.scopes[-1].element: return itor elif ...
e82282c0d78934b06fedecbcbe624d990e9ad8dc
637,753
def solution(n: int) -> int: """[summary] 자연수 n이 주어질 때, 다음 큰 수를 구하시오 다음 큰 수: 1) n보다 큰 자연수 2) n과 다음 큰 수는 2진수 변환시 1의 갯수가 같다 3) 1)2)를 만족하는 가장 작은 자연수 Args: n (int): 10^6 이하의 자연수 Returns: int: n의 다음 큰 수 """ target = sum(map(int, format(n, "b"))) i = n + 1 ...
2b795ef9b87fc837353146d98b86d56d3e0b9afe
637,754
def kcalc(self, kplan="", mat="", kcsym="", klocpr="", **kwargs): """Calculates stress intensity factors in fracture mechanics analyses. APDL Command: KCALC Parameters ---------- kplan Key to indicate stress state for calculation of stress intensity factors: 0 - Plane stra...
7c8b1cd90c756878590ffadad397f5bd760c560d
637,755
import logging def get_logger(cls): """ Generate a logger object by the given class. The logger name will be the full qualified class name. @param cls: A class to generate the logger. @type cls: C{class} @return: A logger by the given class. @rtype: U{Logger<http://docs.python.org/2/library/lo...
c601cdd61614774dd3b8ac2b6d4676b0bef14d01
637,757