content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import json def format_search_log(json_string): """ usage example {{ model_object|format_search_log }} """ query_json = json.loads(json_string) attributes_selected = sorted(query_json.get('_source')) context = {} context['attributes_selected'] = attributes_selected return attributes...
eb5aa21590474acaee7b2b94a1cfdc52c080d017
706,011
def test_get_earth_imperative_solution(solar_system): """ ## Imperative Solution The first example uses flow control statements to define a [Imperative Solution]( https://en.wikipedia.org/wiki/Imperative_programming). This is a very common approach to solving problems. """ def get_planet...
f966886e3384547803106c404a21e2bb7ecd8fa9
706,012
def radialBeamProfile_flatTop(x,y,a): """Top hat beam profile \param[in] x x-position for profile computation \param[in] y y-position for profile computation \param[in] a radial extension of flat-top component \param[in] R 1/e-width of beam profile \param[ou...
699d214c499d8cbcf1c0ed26a5d0d00cf2813f3f
706,013
import platform def get_machine_name(): """ Portable way of calling hostname shell-command. Regarding docker containers: NOTE: If we are running from inside the docker-dev environment, then $(hostname) will return the container-id by default. For now we leave that behaviour. We ...
ae5a7090846164a97cafd07af4701dcfcc25070e
706,014
def pass_through_formatter(value): """No op update function.""" return value
202ea761db9e1fa858718c61df3a7fd18f02826c
706,015
def check_branch(payload, branch): """ Check if a push was on configured branch. :param payload: Payload from web hook. :param branch: Name of branch to trigger action on. :return: True if push was on configured branch, False otherwise. """ if "ref" in payload: if payload["ref"] == b...
88bd0ebae330ee169e97a40aee208b2f92ee4a32
706,016
import re def nice(name): """Generate a nice name based on the given string. Examples: >>> names = [ ... "simple_command", ... "simpleCommand", ... "SimpleCommand", ... "Simple command", ... ] >>> for name in names: ... nice(...
ab96675423812a85744bb76e7f62d08bbbac2eea
706,018
def findwskeyword(keyword, sol): """Find and return a value for a keyword in the list of the wavelength solution""" i = sol.index(keyword) j = sol[i:].index('\n') return sol[i:i + j].split('=')[1].strip()
b3cc028415d74ecfd7ec3868ae591d7b4d3b8860
706,020
def format_time(time): """ Converts datetimes to the format expected in SAML2 XMLs. """ return time.strftime("%Y-%m-%dT%H:%M:%SZ")
03651b72aa0b177ac1ac3f1ccafdba6fe967a11a
706,021
def get_delivery_voucher_discount(voucher, total_price, delivery_price): """Calculate discount value for a voucher of delivery type.""" voucher.validate_min_amount_spent(total_price) return voucher.get_discount_amount_for(delivery_price)
8ede095730c1d29d01949dff47b4a2893d29720c
706,022
def process_results(unprocessed, P, R, G): """Process the results returned by the worker pool, sorting them by policy and run e.g. results[i][j][k] are the results from policy i on run j on graph k. Parameters: - unprocessed: Unprocessed results (as returned by the worker pool) - P: number of po...
24c2854723b3fc33c3fee58595f84d789e861fbc
706,025
def check_hashtarget(bible_hash, target): """ tests if the biblepay hash is valid for the hashtarget, means that is it lower. True = is lower and all is fine """ rs = False try: rs = int(bible_hash, 16) < int(target, 16) except: pass return rs
a0041d8834b2a0af0a08c2562ffed599925ed5a8
706,026
def gen_spacer(spacer_char="-", nl=2): """ Returns a spacer string with 60 of designated character, "-" is default It will generate two lines of 60 characters """ spacer = "" for i in range(nl): spacer += spacer_char * 60 spacer += "\n" return spacer
7434f191dafdf500c2fc3e67373afc664e543ce0
706,027
def __check_interface_state(duthost, interface, state='up'): """ Check interface status Args: duthost: DUT host object interface: Interface of DUT state: state of DUT's interface Returns: Bool value which confirm port state """ ports_down = duthost.interface_fac...
bc17d489064e9a81ec77dad5ab3682c9a96fa88d
706,029
import torch def get_number_of_voxels_per_class(labels: torch.Tensor) -> torch.Tensor: """ Computes the number of voxels for each class in a one-hot label map. :param labels: one-hot label map in shape Batches x Classes x Z x Y x X or Classes x Z x Y x X :return: A tensor of shape [Batches x Classes] ...
568a91639a42cf3cd3debe365c5a963512d95dfc
706,030
import pydoc def read_docstring(object_): """ Returns object docstring without the FILE information. """ fmt = "```\n{}\n```\n" docs = pydoc.plain(pydoc.render_doc(object_)).split("FILE")[0].rstrip() return fmt.format(docs)
5c21f6eadf400ac9316e3f44d98464536b9b7536
706,031
def parse_scales_line(line): """ Args: - line: Returns: - scales_dict """ def advance_past_token(str, token): return str[str.find(token) + len(token):] scales_dict = {} line = advance_past_token(line, 'Scales:') pair_str = line.split(',') for pair_str in pair_str: dname, scale = pair_str.split(':')...
b16e1f431b878aa6418beaed3f141fe928a229e1
706,032
import collections def parse_remove_configuration(configuration): """ Turns the configuration line of splitting into a name and a set of params. """ if configuration is None: return "None", None print('conf', configuration) conf_dict = collections.OrderedDict(configuration) name ...
40bf749c2e142cef534f945179b987fd3c7ba6d8
706,033
def focused_evaluate(board): """ Given a board, return a numeric rating of how good that board is for the current player. A return value >= 1000 means that the current player has won; a return value <= -1000 means that the current player has lost """ score = board.longest_chain(board.ge...
b2cbb91cdb048ef41a13532e400173daa05af4b8
706,034
def uploadResourceFileUsingSession(url, session, resourceName, fileName, fullPath, scannerId): """ upload a file for the resource - e.g. a custom lineage csv file works with either csv for zip files (.csv|.zip) returns rc=200 (valid) & other rc's from the post """ print( "uploading fi...
8a4a8c21563f1467db284f2e98dd1b48dbb65a3c
706,035
import platform import os def _clear_screen(): """ http://stackoverflow.com/questions/18937058/python-clear-screen-in-shell """ if platform.system() == "Windows": tmp = os.system('cls') #for window else: tmp = os.system('clear') #for Linux return True
2958ef538e95d717d60c577c631ddd91240c48f9
706,036
def numeric_to_string(year): """ Convert numeric year to string """ if year < 0 : yearstring = "{}BC".format(year*-1) elif year >= 0: yearstring = "{}AD".format(year) else: raise return yearstring
3469e2dd5e05c49b4861782da2dd88bac781c61d
706,039
def _get_num_ve_sve_and_max_num_cells(cell_fracs): """ Calculate the num_ve, num_sve and max_num_cells Parameters ---------- cell_fracs : structured array, optional A sorted, one dimensional array, each entry containing the following fields: :idx: int Th...
c0d154898bbfeafd66d89a2741dda8c2aa885a9a
706,040
def flip_nums(text): """ flips numbers on string to the end (so 2019_est --> est_2019)""" if not text: return '' i = 0 s = text + '_' while text[i].isnumeric(): s += text[i] i += 1 if text[i] == '_': i += 1 return s[i:]
e0534e25e95b72e1d6516111413e32a6dae207ef
706,041
def extent2(texture): """ Returns the extent of the image data (0.0-1.0, 0.0-1.0) inside its texture owner. Textures have a size power of 2 (512, 1024, ...), but the actual image can be smaller. For example: a 400x250 image will be loaded in a 512x256 texture. Its extent is (0.78, 0.98), the...
16c6d220ad48201fd133ed11c97452bf0831c0d8
706,042
def calculate_handlen(hand): """ Returns the length (number of letters) in the current hand. hand: dictionary (string-> int) returns: integer """ # Store the total length of the hand hand_len = 0 # For every letter in the hand for key in hand.keys(): # Add the number of...
297f8af5943bf87bb7999a1212d54430857de12b
706,043
def _server_allow_run_on_save() -> bool: """Allows users to automatically rerun when app is updated. Default: true """ return True
3a895abd8201ce97c8f2f928b841eb86bf6327d1
706,044
def Law_f(text): """ :param text: The "text" of this Law """ return '\\begin{block}{Law}\n' + text + '\n\\end{block}\n'
594b279c5971a9d379666179c4d0633fc02a8bd9
706,045
import torch def valid_from_done(done): """Returns a float mask which is zero for all time-steps after a `done=True` is signaled. This function operates on the leading dimension of `done`, assumed to correspond to time [T,...], other dimensions are preserved.""" done = done.type(torch.float) ...
0ca2bd0f9e23605091b2f8d1bc15e67e1632b82b
706,046
def rescale_list_to_range(original, limits): """ Linearly rescale values in original list to limits (minimum and maximum). :example: >>> rescale_list_to_range([1, 2, 3], (0, 10)) [0.0, 5.0, 10.0] >>> rescale_list_to_range([1, 2, 3], (-10, 0)) [-10.0, -5.0, 0.0] >>> rescale_list_to_rang...
bdd38bb24b597648e4ca9045ed133dfe93ad4bd8
706,047
def get_ratings(labeled_df): """Returns list of possible ratings.""" return labeled_df.RATING.unique()
2b88b1703ad5b5b0a074ed7bc4591f0e88d97f92
706,048
from math import cos,pi from numpy import zeros def gauss_legendre(ordergl,tol=10e-14): """ Returns nodal abscissas {x} and weights {A} of Gauss-Legendre m-point quadrature. """ m = ordergl + 1 def legendre(t,m): p0 = 1.0; p1 = t for k in range(1,m): p = ((2.0*k + ...
5353373ee59cd559817a737271b4ff89cc031709
706,049
import re def irccat_targets(bot, targets): """ Go through our potential targets and place them in an array so we can easily loop through them when sending messages. """ result = [] for s in targets.split(','): if re.search('^@', s): result.append(re.sub('^@', '', s)) ...
b7dce597fc301930aae665c338a9e9ada5f2be7e
706,050
def cli(ctx, path, max_depth=1): """List files available from a remote repository for a local path as a tree Output: None """ return ctx.gi.file.tree(path, max_depth=max_depth)
4be4fdffce7862332aa27a40ee684aae31fd67b5
706,051
def merge(d, **kwargs): """Recursively merges given kwargs int to a dict - only if the values are not None. """ for key, value in kwargs.items(): if isinstance(value, dict): d[key] = merge(d.get(key, {}), **value) elif value is not None: d[key] = value return ...
168cc66cce0a04b086a17089ebcadc16fbb4c1d0
706,053
import os def get_db_path(): """Return the path to Dropbox's info.json file with user-settings.""" if os.name == 'posix': # OSX-specific home_path = os.path.expanduser('~') dbox_db_path = os.path.join(home_path, '.dropbox', 'info.json') elif os.name == 'nt': # Windows-specific h...
04ee901faea224dde382a11b433f913557c7cb21
706,054
import math def convert_table_value(fuel_usage_value): """ The graph is a little skewed, so this prepares the data for that. 0 = 0 1 = 25% 2 = 50% 3 = 100% 4 = 200% 5 = 400% 6 = 800% 7 = 1600% (not shown) Intermediate values scale between those values. (5.5 is 600%) "...
15e4deedb4809eddd830f7d586b63075b71568ef
706,055
import requests from datetime import datetime def fetch_status(): """ 解析サイト<https://redive.estertion.win> からクラバト情報を取ってくる return ---- ``` { "cb_start": datetime, "cb_end": datetime, "cb_days": int } ``` """ # クラバト開催情報取得 r = requests.get( "htt...
683c9fe84bf346a1cce703063da8683d3469ccc2
706,056
def A004086(i: int) -> int: """Digit reversal of i.""" result = 0 while i > 0: unit = i % 10 result = result * 10 + unit i = i // 10 return result
b0a65b7e203b7a92f7d6a1846888798c369ac869
706,057
def should_raise_sequencingerror(wait, nrep, jump_to, goto, num_elms): """ Function to tell us whether a SequencingError should be raised """ if wait not in [0, 1]: return True if nrep not in range(0, 16384): return True if jump_to not in range(-1, num_elms+1): return Tru...
fc7c4bdb29cd5b90faec59a4f6705b920304aae0
706,058
def add_volume (activity_cluster_df, activity_counts): """Scales log of session counts of each activity and merges into activities dataframe Parameters ---------- activity_cluster_df : dataframe Pandas dataframe of activities, skipgrams features, and cluster la...
1ea67909e2c48500ca2f022a3ae5ebcbe28da6c8
706,059
def prefetched_iterator(query, chunk_size=2000): """ This is a prefetch_related-safe version of what iterator() should do. It will sort and batch on the default django primary key Args: query (QuerySet): the django queryset to iterate chunk_size (int): the size of each chunk to fetch ...
e8a8feeea8073161283018f19de742c9425e2f94
706,060
import os def get_dir(foldername, path): """ Get directory relative to current file - if it doesn't exist create it. """ file_dir = os.path.join(path, foldername) if not os.path.isdir(file_dir): os.mkdir(os.path.join(path, foldername)) return file_dir
8574dfc0503c8cc6410dc013a23689ac2b77f5d6
706,061
def dicom_strfname( names: tuple) -> str: """ doe john s -> dicome name (DOE^JOHN^S) """ return "^".join(names)
864ad0d4c70c9bb4acbc65c92bf83a97415b9d35
706,062
def skip(line): """Returns true if line is all whitespace or shebang.""" stripped = line.lstrip() return stripped == '' or stripped.startswith('#!')
4ecfb9c0f2d497d52cc9d9e772e75d042cc0bcce
706,063
def draw_box(image, box, color): """Draw 3-pixel width bounding boxes on the given image array. color: list of 3 int values for RGB. """ y1, x1, y2, x2 = box image[y1:y1 + 1, x1:x2] = color image[y2:y2 + 1, x1:(x2+1)] = color image[y1:y2, x1:x1 + 1] = color image[y1:y2, x2:x2 + 1] = colo...
4d1e713c6cb6a3297b4f7d8ab9682205947770da
706,064
def get_statuses_one_page(weibo_client, max_id=None): """获取一页发布的微博 """ if max_id: statuses = weibo_client.statuses.user_timeline.get(max_id=max_id) else: statuses = weibo_client.statuses.user_timeline.get() return statuses
4a214489aa5696c9683c9cfa96d79ee169135eb5
706,065
def do_nothing(ax): """Do not add any watermark.""" return ax
6fbe32dc45ca1a945e1c45bf0319770c4d683397
706,066
def _scan_real_end_loop(bytecode, setuploop_inst): """Find the end of loop. Return the instruction offset. """ start = setuploop_inst.next end = start + setuploop_inst.arg offset = start depth = 0 while offset < end: inst = bytecode[offset] depth += inst.block_effect ...
9cff8ab77563a871b86cdbb14236603ec58e04b6
706,067
def IndividualsInAlphabeticOrder(filename): """Checks if the names are in alphabetic order""" with open(filename, 'r') as f: lines = f.readlines() individual_header = '# Individuals:\n' if individual_header in lines: individual_authors = lines[lines.index(individual_header) + 1:] sorted_auth...
4753bbf41498373695f921555c8f01183dbb58dc
706,068
from pathlib import Path def add_filename_suffix(file_path: str, suffix: str) -> str: """ Append a suffix at the filename (before the extension). Args: path: pathlib.Path The actual path object we would like to add a suffix suffix: The suffix to add Returns: path with suffix appended a...
546bb95f694ee5d5cb26873428fcac8453df6a54
706,069
def list_dropdownTS(dic_df): """ input a dictionary containing what variables to use, and how to clean the variables It outputs a list with the possible pair solutions. This function will populate a dropdown menu in the eventHandler function """ l_choice = [] for key_cat, value_cat in d...
fcd0474fa6941438cb39c63aa7605f1b776fd538
706,070
def recostruct(encoded, weights, bias): """ Reconstructor : Encoded -> Original Not Functional """ weights.reverse() for i,item in enumerate(weights): encoded = encoded @ item.eval() + bias[i].eval() return encoded
e17aeb6a819a6eec745c5dd811460049fa4a92cd
706,071
import math def get_file_dataset_from_trixel_id(CatName,index,NfilesinHDF,Verbose=True):#get_file_var_from_htmid in Eran's library """Description: given a catalog basename and the index of a trixel and the number of trixels in an HDF5 file, create the trixel dataset name Input :- ...
b9d0482780ae2a191175f1549513f46c047bb1cf
706,072
def find_correspondance_date(index, csv_file): """ The method returns the dates reported in the csv_file for the i-subject :param index: index corresponding to the subject analysed :param csv_file: csv file where all the information are listed :return date """ return csv_f...
915b9a493247f04fc1f62e614bc26b6c342783c8
706,074
import unicodedata def normalize_to_ascii(char): """Strip a character from its accent and encode it to ASCII""" return unicodedata.normalize("NFKD", char).encode("ascii", "ignore").lower()
592e59ae10bb8f9a04dffc55bcc2a1a3cefb5e7e
706,075
import functools def pass_none(func): """ Wrap func so it's not called if its first param is None >>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) """ @functools.wraps(func) def wrapper(param, *args, **kwargs): if param is not None: return func(param, *args, **kwargs) ...
2264ca5978485d8fc13377d17eb84ee522a040b9
706,077
def arcmin_to_deg(arcmin: float) -> float: """ Convert arcmin to degree """ return arcmin / 60
9ef01181a319c0c48542ac57602bd7c17a7c1ced
706,078
def is_hex_value(val): """ Helper function that returns True if the provided value is an integer in hexadecimal format. """ try: int(val, 16) except ValueError: return False return True
6ba5ac1cfa9b8a4f8397cc52a41694cca33a4b8d
706,079
def list_to_str(input_list, delimiter=","): """ Concatenates list elements, joining them by the separator specified by the parameter "delimiter". Parameters ---------- input_list : list List with elements to be joined. delimiter : String, optional, default ','. The separato...
4decfbd5a9d637f27473ec4a917998137af5ffe0
706,080
import warnings def _url_from_string(url): """ Generate actual tile url from tile provider definition or template url. """ if "tileX" in url and "tileY" in url: warnings.warn( "The url format using 'tileX', 'tileY', 'tileZ' as placeholders " "is deprecated. Please use '...
f3d4393163e48a7949f3229c55ea8951411dcd63
706,081
import socket def get_reverse_dns(ip_address: str) -> str: """Does a reverse DNS lookup and returns the first IP""" try: rev = socket.gethostbyaddr(ip_address) if rev: return rev[0] return "" # noqa except (socket.herror, socket.gaierror, TypeError, IndexError): ...
58a27e25f7a9b11ab7dcddebeea743b7864f80f1
706,082
import inspect def get_current_func_name(): """for python version greater than equal to 2.7""" return inspect.stack()[1][3]
002d318bcab98639cab6c38317322f247a1ad0e0
706,083
def getParmNames(parmsDef): """Return a list of parm names in a model parm definition parmsDef: list of tuples, each tuple is a list of parms and a time constraint. Call with modelDict[modelname]['Parms]. Returns: List of string parameter names Here's an example of how to remove unused parms f...
785661200c388f23c5f38ae67e773a43fd8f57b3
706,084
import zlib import marshal def serialize(object): """ Serialize the data into bytes using marshal and zlib Args: object: a value Returns: Returns a bytes object containing compressed with zlib data. """ return zlib.compress(marshal.dumps(object, 2))
650cbc8937df5eae79960f744b69b8b12b623195
706,085
def str_to_dtype(s): """Convert dtype string to numpy dtype.""" return eval('np.' + s)
e0ff793404af5a8022d260fde5878329abbac483
706,086
from typing import Any from typing import get_origin def istype(obj: Any, annotation: type) -> bool: """Check if object is consistent with the annotation""" if get_origin(annotation) is None: if annotation is None: return obj is None return isinstance(obj, annotation) else: ...
c1903ea2ec6c0b6b9006a38f7c0720c88987b706
706,087
def get_file_info(repo, path): """we need change_count, last_change, nbr_committers.""" committers = [] last_change = None nbr_changes = 0 for commit in repo.iter_commits(paths=path): #print(dir(commit)) committers.append(commit.committer) last_change = commit.committed_date...
6ff99df399d35b79d0e2a5635b1e76e1f65fe0bd
706,088
import requests def __ping_url(url: str) -> bool: """Check a link for rotting.""" try: r = requests.head(url) return r.status_code in ( requests.codes.ok, requests.codes.created, requests.codes.no_content, requests.codes.not_modified, ) ...
e680cec006127bbe889dcab0291be3149f30d10e
706,089
def duo_username(user): """ Return the Duo username for user. """ return user.username
92b2bfd5f6f3027787db493880139a8564597946
706,090
def parse_line(line,): """Return a list of 2-tuples of the possible atomic valences for a given line from the APS defining sheet.""" possap = [] for valence, entry in enumerate(line[4:]): if entry != "*": possap.append((valence, int(entry))) return possap
d27ed66cb35084c9927cae8658d7ea8a421c69a4
706,091
def decode(tokenizer, token): """decodes the tokens to the answer with a given tokenizer""" answer_tokens = tokenizer.convert_ids_to_tokens( token, skip_special_tokens=True) return tokenizer.convert_tokens_to_string(answer_tokens)
4bbb58a6a0ed0d33411f9beee35ad0f2fb43698f
706,092
def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True): """ Pads a rectangle by the specified values on each individual side, ensuring the padded rectangle falls within the specified bounds. The input rectangle, bounds, and return value are all a tuple of (x,y,w,h). """ # Unpack th...
032cafd373b59b725b8e2e28ba91e263ccae6e12
706,093
def extract(x, *keys): """ Args: x (dict or list): dict or list of dicts Returns: (tuple): tuple with the elements of the dict or the dicts of the list """ if isinstance(x, dict): return tuple(x[k] for k in keys) elif isinstance(x, list): return tuple([xi[k] for ...
c0730556786586011b0b22ae5003c2fe9ccb2894
706,095
import os import json def is_gcloud_oauth2_token_cached(): """Returns false if 'gcloud auth login' needs to be run.""" p = os.path.join(os.path.expanduser('~'), '.config', 'gcloud', 'credentials') try: with open(p) as f: return len(json.load(f)['data']) != 0 except (KeyError, IOError, OSError, Value...
8d02c1b41399d7f5c8550e4c0364108c251c3791
706,096
def _gen_off_list(sindx): """ Given a starting index and size, return a list of numbered links in that range. """ def _gen_link_olist(osize): return list(range(sindx, sindx + osize)) return _gen_link_olist
863ccdc08f6a7cadccc3c5ccfd0cb92a223aadda
706,097
def rationalize_quotes_from_table(table, rationalizeBase=10000): """ Retrieve the data from the given table of the SQLite database It takes parameters: table (this is one of the Quote table models: Open, High, Low, or Close) It returns a tuple of lists """ first_row = table.select().limit(...
ee1c8310c12e7e53e9ca2677dd61d7d2525603fd
706,098
def k(func): """定义一个装饰器函数""" def m(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return m
3cc958033fd66547e523882435494f27ae81b096
706,099
import requests def get_playlist_object(playlist_url, access_token): """ playlist_url : url of spotify playlist access_token : access token gotten from client credentials authorization return object containing playlist tracks """ playlist_id = playlist_url.split("/")[-1] playlist_endp...
8c7ed1a1b9574e2e0870d3091452accf5909f982
706,100
import numpy as np def f_of_sigma(sigma,A=0.186,a=1.47,b=2.57,c=1.19): """ The prefactor in the mass function parametrized as in Tinker et al 2008. The default values of the optional parameters correspond to a mean halo density of 200 times the background. The values can be found in table 2 of...
89abe82df8a4384e74eb556172c9d46193b731da
706,101
def value(iterable, key=None, position=1): """Generic value getter. Returns containing value.""" if key is None: if hasattr(iterable, '__iter__'): return iterable[position] else: return iterable else: return iterable[key]
df49496ab8fa4108d0c3d04035ffa318a9c6a035
706,102
def compact_interval_string(value_list): """Compact a list of integers into a comma-separated string of intervals. Args: value_list: A list of sortable integers such as a list of numbers Returns: A compact string representation, such as "1-5,8,12-15" """ if not value_list: return '' value_li...
b479b45dc68a0bce9628a19be17185437f3edca6
706,103
def is_prime(num): """ Assumes num > 3 """ if num % 2 == 0: return False for p in range(3, int(num**0.5)+1, 2): # Jumps of 2 to skip odd numbers if num % p == 0: return False return True
e898026d0362967400cfee4e70a74ac02a64b6f1
706,104
def is_valid_orcid_id(orcid_id: str): """adapted from stdnum.iso7064.mod_11_2.checksum()""" check = 0 for n in orcid_id: check = (2 * check + int(10 if n == "X" else n)) % 11 return check == 1
5866e4465a24f46aa4c7015902eac53684da7b04
706,105
def calc_minimum_angular_variance_1d(var_r, phi_c, var_q): """Calculate minimum possible angular variance of a beam achievable with a correction lens. Args: var_r (scalar): real space variance. phi_c (scalar): real-space curvature - see above. var_q (scalar): angular variance of the bea...
c5e2144f44b532acbf8eb9dfb83c991af3756abf
706,106
def calc_qpos(x, bit = 16): """ 引数の数値を表現できる最大のQ位置を返す。 :param x: float :return: int """ for q in range(bit): maxv = (2 ** (q - 1)) - 1 if x > maxv: continue return bit - q return bit
b85b458989425bc5698547cae93d8729bd452e76
706,107
def _follow_word_from_node(node, word): """Follows the link with given word label from given node. If there is a link from ``node`` with the label ``word``, returns the end node and the log probabilities and transition IDs of the link. If there are null links in between, returns the sum of the log prob...
a21a20ee4ad2d2e90420e30572d41647b3938f4b
706,108
def rm_words(user_input, stop_words): """Sanitize using intersection and list.remove()""" # Downsides: # - Looping over list while removing from it? # http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python stop_words = set(stop_words) for sw in stop_...
aead9c1cd5586bb20611ea8fbf57aa66aa3f5ede
706,110
def convert_xrandr_to_index(xrandr_val: float): """ :param xrandr_val: usually comes from the config value directly, as a string (it's just the nature of directly retrieving information from a .ini file) :return: an index representation of the current brightness level, useful for switch...
eed5f7a6c79f7dcb29c627521d31dc59e5cd430b
706,111
def get_message(name, value): """Provides the message for a standard Python exception""" if hasattr(value, "msg"): return f"{name}: {value.msg}\n" return f"{name}: {value}\n"
7755c63cc9a16e70ad9b0196d662ef603d82b5f6
706,112
import os def find_files(topdirs, py = False): """Lists all python files under any topdir from the topdirs lists. Returns an appropriate list for data_files, with source and destination directories the same""" ret = [] for topdir in topdirs: for r, _ds, fs in os.walk(topdir): ...
b273d067bb6237a8c7bb9950aa7c764854f1124b
706,113
def merge_dict_recursive(base, other): """Merges the *other* dict into the *base* dict. If any value in other is itself a dict and the base also has a dict for the same key, merge these sub-dicts (and so on, recursively). >>> base = {'a': 1, 'b': {'c': 3}} >>> other = {'x': 4, 'b': {'y': 5}} >>> want =...
10ea2bbcf7d2ee330c784efff684974339d48b5d
706,114
def url_path_join(*items): """ Make it easier to build url path by joining every arguments with a '/' character. Args: items (list): Path elements """ return "/".join([item.lstrip("/").rstrip("/") for item in items])
d864c870f9d52bad1268c843098a9f7e1fa69158
706,115
def utf8_german_fix( uglystring ): """ If your string contains ugly characters (like ü, ö, ä or ß) in your source file, run this string through here. This adds the German "Umlaute" to your string, making (ÄÖÜäöü߀) compatible for processing. \tprint( utf8_german_fix("ü߀") ) == ü߀ """ ...
7ed12d819b384e3bb5cb019ce7b7afe3d6bb8b86
706,116
import os import sys def get_pcgr_bin(): """Return abs path to e.g. conda/env/pcgr/bin """ return os.path.dirname(os.path.realpath(sys.executable))
abd85ffc2ad348e2c5dee260561e1da2b18efca4
706,117
def _test(value, *args, **keywargs): """ A function that exists for test purposes. >>> checks = [ ... '3, 6, min=1, max=3, test=list(a, b, c)', ... '3', ... '3, 6', ... '3,', ... 'min=1, test="a b c"', ... 'min=5, test="a, b, c"', ... 'min=1, max=...
c011c9386392c4b8dc8034fee33bfcfdec9845ed
706,119
def format_sample_case(s: str) -> str: """format_sample_case convert a string s to a good form as a sample case. A good form means that, it use LR instead of CRLF, it has the trailing newline, and it has no superfluous whitespaces. """ if not s.strip(): return '' lines = s.strip().splitlin...
cd691f2bfc8cc56db85f2a55ff3bf4b5afd5f30e
706,120
def load_room(name): """ There is a potential security problem here. Who gets to set name? Can that expose a variable? """ return globals().get(name)
14034adf76b8fd086b798cd312977930d42b6e07
706,121
def find_node_name(node_id, g): """Go through the attributes and find the node with the given name""" return g.node[node_id]["label"]
a4656659aeef0427a74822991c2594064b1a9411
706,122
def basic_pyxll_function_3(x): """docstrings appear as help text in Excel""" return x
3709d1bce92456b1456ed90d81002f71b7d9e754
706,123