content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def has(prop, object_or_dct): """ Implementation of ramda has :param prop: :param object_or_dct: :return: """ return prop in object_or_dct if isinstance(dict, object_or_dct) else hasattr(object_or_dct, prop)
598b0249062d65a28decc240e5542d925040a4ab
637,532
import platform def is_on_macos_14_or_higher(): """ Return True if the current OS is macOS 14 or higher. It uses APFS by default and has a different behavior wrt. unicode and filesystem encodings. """ macos_ver = platform.mac_ver() macos_ver = macos_ver[0] macos_ver = macos_ver.split('...
9cf7fc20371a294657bd9f79427ab4e59761c167
637,533
def fix_arm_math(source_file, source): """ Add conditional for ARM_MATH_CM definition. It is already defined by the Cortex definitions of RIOT-OS. """ return source.replace( "#define ARM_MATH_CM0PLUS", "#ifndef ARM_MATH_CM0PLUS\n#define ARM_MATH_CM0PLUS\n#endif")
20e61d598c8a4cd2d803b58eb9026c12bb7b37a7
637,534
def grep_elements(elements, grep): """ Filter elements. Only keep the ones that match grep """ res = [] for e in elements: keep_it = True for g in grep: s = ' '.join(str(v) for v in e.values()) if s.find(g) == -1: keep_it = False if ke...
e27c8beba937c2b3febd38d191312f87d96b6c81
637,536
def savePlot(fig_plot, fig_name, path = ".//figures//"): """saves a seaborn figure """ try: fig = fig_plot.get_figure() print(fig, fig_plot) file_path = path + fig_name + ".png" print(file_path) fig.savefig(file_path) return file_path except: ...
e092b28b2f732d549f53acbae2f372980042a5e8
637,537
import os def find_guilds(): """Returns a list of every guilds.""" try: return os.listdir('data/servers/') except FileNotFoundError: return []
b63daac80d9ebf7118ccfc0ea85810bf16a8cb23
637,538
import logging def GetLogger(name: str) -> logging.Logger: """Return a logger. This is a wrapper around logging.getLogger that is intended to be used by the other modules so that they don't have to import the logging module + this module. Args: name (str); The name for the logger. Returns: logg...
d0991494a1b49cc302f110af233878288d424d22
637,539
import difflib def diffmatch(search, string): """ Use difflib and a loop to check if search_pattern can be 'almost' found INSIDE a string. 'almost' being defined by difflib """ if len(search) > len(string): return False l = len(search) ratio = 0.7 for i in range(len(string)...
224d73d0de1c1514715a029a5ff03a88e94fbac5
637,540
def secondsToHms(seconds): """Convert seconds to hours, mins, secs seconds - seconds to be converted, >= 0 return hours, mins, secs """ assert seconds >= 0, 'seconds validation failed' hours = int(seconds / 3600) mins = int((seconds - hours * 3600) / 60) secs = seconds - hours * 3600 - mins * 60 return hour...
baf1618e0bd4f72619328ed1bb412dbc039e6438
637,541
def coord_map(dimensions, coordinate, mode): """ Wrap a coordinate, according to a given mode. :param dimensions: int, maximum coordinate. :param coordinate: int, coordinate provided by user. May be < 0 or > dimensions :param mode: {'W', 'S', 'R', 'E'}, Whether to wrap, symmetric reflect, reflect o...
0b4fdc5b4c1578c0b34e6ac9cde25078c55ffb0f
637,543
import subprocess def get_uniq_gen_size(gen_sites_bed): """ Get unique genomic space size, which the genomic sites inside gen_sites_bed cover. >>> gen_sites_bed = "test_data/test_gen_size.bed" >>> get_uniq_gen_size(gen_sites_bed) 2500 """ params_str = '-s -c 4 -o distinct -delim ";"...
fa5390bfd18ed1e40fb8ababc5964c30f8344efd
637,544
def selected_box(img_array, x0, y0, x1, y1): """Return the selected area on image.""" x = abs(x0 - x1) y = abs(y0 - y1) x_start = min(x0, x1) y_start = min(y0, y1) return img_array[y_start: y_start + y, x_start: x_start + x, :]
29653bf70f4c931c088450877b399d27af699e63
637,545
def palindromic(s: str) -> bool: """ Checks whether a string is a palindrome. """ size = len(s) for i in range(size // 2): if s[i] != s[size - 1 - i]: return False return True
9695821733b4b6042916a884eb8416eeca9f4483
637,546
import numpy def lonlatdistance(pt1lon, pt1lat, pt2lon, pt2lat): """ Compute the great circle distance between two points on a sphere using the haversine formula. Arguments: pt1lon - longitude(s) of the first point pt1lat - latitude(s) of the first point pt2lon - longitude(s) ...
5c117b9c7993a8c59a4587b9793ca7b7d37093f6
637,547
def _compute_ANN_row(tree, x): """ For a given survival tree and a feature vector, traverse down the tree to find the feature vector's adaptive nearest neighbors. Parameters ---------- tree : dictionary Tree node of a decision tree. We traverse down the tree taking branches that...
75970eb70c8088b5c021ae9bc60f4efc5175265c
637,548
def slim_aggregates(aggregates): """"slim version of the region aggregates, minimizing NoData and verbose naming""" slimmed_aggregates = [] for aggregate in aggregates: verbose_keys = list(aggregate.keys()) for verbose_key in verbose_keys: slim_key = verbose_key.split("_")[0] ...
cee039718e463acd5f85960f5b5b1f0a4d216bcf
637,549
def check_poa(poa: str) -> bool: """Checks valid poa Args: poa (str) Returns: bool """ return len(poa.strip()) >= 30
c32031233b5b2d9404e8005d6ebf0f2694d6af29
637,550
def text_mention(text_content): """ 处理微博正文中的用户@ :param text_content: 处理对象文本 :return: 是否含有@(1:有,0:无),@数量 """ mention_nums = text_content.count("@") if(mention_nums > 0): return 1,mention_nums else: return 0,0
42506ed5cc438327a71176505efd629895d830b8
637,551
def flatten_grad_input(x_input, grad_output): """Calculate partial derivative of the loss with respect to the input # Arguments x_input: partial derivative of the loss with respect to the output np.array of size `(K, L*M*N)` # Output output: partial derivative of the ...
ca5874d182df82d00dd64a5b8ea2372a0211913e
637,552
def classname(cls): """Return the full qualified name of a class""" mod = cls.__module__ return cls.__name__ if mod is None else f"{mod}.{cls.__name__}"
2883e5cdb0f3d307cd18c9ce17ac5c9396aba226
637,553
def overlap(a1, a2): """ Check if the given arrays have common elements """ return len(set(a1).intersection(set(a2))) > 0
75d40ab32b56db942c4ba84d3bac852a7619df07
637,556
from pathlib import Path import os def normalized_path(path='.'): """ 默认支持 ~ 符号 返回的是字符串 which default support the `~` """ if isinstance(path, Path): return str(path.expanduser()) elif isinstance(path, str): if path.startswith('~'): path = os.path.expanduser(path...
edf06aab468429c7ba2e88b14afffa24117041b2
637,557
def transpose(matrix): """return the transpose of a matrix stored as a 9-element tuple""" return (matrix[0], matrix[3], matrix[6], matrix[1], matrix[4], matrix[7], matrix[2], matrix[5], matrix[8])
25c6f6ac09ff1d0305102721963d53282e9b80f3
637,558
def propagate_taxids(res, ranks): """ Transfer taxonomy ids to unassigned ranks based on best known taxonomy Example: {'species': -1, 'family': -171549, 'genus': -171549, 'order': 171549, 'phylum': 976, 'class': 200643, 'superkingdom': 2} should become {'species': -171549, 'family': -171549, '...
4f6495e1c9d19f86b1d3eceffa9eb4c748717d2d
637,560
from typing import OrderedDict def to_conllu(j: OrderedDict) -> str: """Converts JSON-NLP to CONLLU""" c = "" for d in j['documents']: par_id = None c = f"{c}\n# newdoc id = {d['id']}" for t in d['tokenList']: pass return c
dfd5909b6883d5ec1cc45e3f1b03b62e965b74a5
637,563
def flat_clfs(params) -> dict: """Flatten the classifiers for easier access.""" flat = {} for clfs in params["classifiers"].values(): flat.update(clfs) return flat
bb3fbad8f9866848648f6e8a323553534727b9e3
637,564
def getStringForVariables(variables, wordsize): """ Takes as input the variable name, number of variables and the wordsize and constructs for instance a string of the form: x00, x01, ..., x30: BITVECTOR(wordsize); """ command = "" for var in variables: command += var + "," comma...
1710ec9d8f71a48849df2548d4ff936ff909a43c
637,565
def pyimpl_array_getitem(data, begin, end, strides): """Implement `getitem`.""" idx = tuple(slice(b, e, s) for b, e, s in zip(begin, end, strides)) return data[idx]
979180afc66d38cd2945d7dd1913b77826358588
637,566
import json def get_predictions(file): """ Returns prediction_list (class probabilities) and predicted_final_classes :param file: file produced by save_json() :return: prediction_list (class probabilities) and predicted_final_classes """ with open(file) as json_file: data = json.load(j...
05c10e27eb1537ed045e76d9beb6d060e202f525
637,567
import inspect def get_num_args(f): """ Find the number of arguments a function or method takes (excluding ``self``). """ if inspect.ismethod(f): return f.__func__.__code__.co_argcount - 1 elif inspect.isfunction(f): return f.__code__.co_argcount else: raise TypeError("...
b5620d3fa8501f452e3c520888725f09a131c799
637,568
def getBiggestArea(freePlaceValues, place=1): """ Returns the biggest requested area from the freeMap. If place is 1, the biggest will be returned If place is 2, the second biggest will be returned Etc :param freePlaceValues: Whole map with free places :param place: x biggest area (1./2./3./...
943b4462b33d70bcdda4a0c2d818c17505eaec3b
637,569
def preprocess(ds): """Remove double grid cell row/column at margins """ return ds.isel(lon=slice(0, 3600), lat=slice(0, 3600))
c3dbe2cbcb667cbbe68c68887b4f64da1c8a1fc9
637,570
import pwd import os def get_username() -> str: """ Returns the username of the user that is running the Berrymon process. :returns: The username of the current user. :rtype: str """ return pwd.getpwuid(os.getuid())[0]
1847ef27d92b031b41b49f995965479192953ab3
637,572
import json def add_group_to_json(args): """ Add a new group entry to the auth JSON file :param args: Namespace object containing all arguments given from command line, if any :returns: 0 if success, non-zero if not """ sanitised_group = args.group.replace('/', '-') new_group = { ...
d79c34f53a2df0c321ecaa7395cf749a34240602
637,573
def red(x): """Format a string red. Returns: The string `x` made red by terminal escape sequence. """ return f"\033[31m{x}\033[0m"
a48cd1be565e7361c80e9cc7b35298248c2a5af2
637,574
def raster_ds_shape(raster_ds): """Return the number of rows and columns in an opened raster dataset Args: raster_ds: opened raster dataset Returns: tuple of raster rows and columns """ return raster_ds.RasterYSize, raster_ds.RasterXSize
6069c50be27361b4fa896027d022a82b87440de2
637,575
def get_ethertype_value(ethertype): """Convert string representation of ethertype to the numerical.""" if ethertype is None: return None mapping = { 'ipv4': 0x0800, 'ipv6': 0x86DD, 'arp': 0x806 } return mapping.get(ethertype.lower())
8cc3861ed94dc640521a8378905b3e05d749b6f3
637,577
def ElementHasAttributeWithValue(element, attribute, value): """Returns true if the element has an attriibute with the given value. """ rValue = False try: rValue = element.attributes[attribute].value == value except: pass return rValue
c59fa7c72abfd7d36e6db04693e44e333d12ca05
637,578
def data_context_notification_context_get(): # noqa: E501 """data_context_notification_context_get returns tapi.notification.NotificationContext # noqa: E501 :rtype: TapiNotificationNotificationContext """ return 'do some magic!'
ac5c11c4f9975c83fd6daffdc5fb136e1dbe443f
637,579
import random def rand_suffix(length=7): """Generate a random suffix of `length` chars""" charset = '0123456789abcdefghijklmnopqrstuvwxyz' return ''.join(random.choice(charset) for i in range(length))
7af309ccb9e2ba477d491209e441208f9dd8bcc8
637,580
def fix_maze(maze): """Fix uneven row lengths caused by the IDE's removal of trailing spaces.""" max_width = max(len(row) for row in maze) for y, row in enumerate(maze): maze[y] = row.ljust(max_width, " ") return maze
f44bf04c004cf62db8a7333226348642fec37a2d
637,581
def rename_columns_with_data_schema(dfx, data_schema): """ Renaming columns based on a specified data schema :param dfx (dataframe): df with the columns that will be cleaned :param data_schema (dictionary): data schema containing the clean column names :return dfx (dataframe): df after renaming the...
1ec1790b72763736372413a227d8389b61333d06
637,582
import itertools def grouper(iterable, n): """ Turn an iterable into an iterable of iterables 'None' should not be a member of the input iterable as it is removed to handle the fillvalues Args: iterable (iterable): an iterable n (int): sie of chunks fillvalue Returns...
8bee92a6b2d0d7c7d80344e6a1294bcb380851f8
637,583
import sys def setup(): """Function to import data from the given .txt file""" generated_list = [] with open("QuickSort.txt") as f: # Exclude the newline character, '\n' generated_list = [int(line.rstrip('\n')) for line in f] # Update the recursion limit due to how pivots are ch...
416a0aa15d25120391aca0b129420669667a594a
637,584
import os import glob def check_fastq(fastq_data_dir, laneId): """Check if fastq data available for library """ fastq_list = (os.path.join(fastq_data_dir, "*fastq.gz")) fastq_data = glob.glob(fastq_list) fq1 = fq2 = None if len(fastq_data) > 0: for file in fastq_data: base ...
92e230e03aec29dfc8edd9061a0755b09e8e785e
637,585
def _get_struct_endian_str(endian): """ DM4 header encodes little endian as byte value 1 in the header. However when that convention is followed the wrong values are read. So this implementation is reversed. :return: '>' or '<' for use with python's struct.unpack function """ if isinstance(end...
db7abdbb1667f20e0edb29b782133970f26c2e07
637,586
def _info_dict_to_string(info): """ Flatten the VCF info-field OrderedDict into a string, including all arrays for allelic-level info. """ if info is not None: return ';'.join(['%s=%s' % (key, value) if not isinstance(value, list) \ else '%s=%s' % (key, ','.join([str(...
8827ca288efae3a48c3cbb55ae9fed58ae4a0ba9
637,587
def pic24_decompact(data): """ Decompacts (expands) a 6-byte PIC24 frame into a raw 8-byte block :param data: compact data :return: raw data """ while len(data) % 6: data.append(0) output = [] for i in range(0, len(data), 6): output.append(data[i]) output.append(d...
3750cf3088e4449d845241d0398d85032b485769
637,588
def default_wd_filter(x): """default weight decay filter.""" parameter_name = x.name if parameter_name.endswith('.bias'): # all bias not using weight decay return False if parameter_name.endswith('.gamma'): # bn weight bias not using weight decay, be carefully for now x not inclu...
defd970e4bcb589f48011dfb23a4af10fc9c0b50
637,590
def get_row_coords(horiz_line_coords): """Get top-left and bottom-right coordinates for each row from a list of horizontal lines""" row_coords = [] for i in range(1, len(horiz_line_coords)): if horiz_line_coords[i][1] - horiz_line_coords[i-1][3] > 1: row_coords.append((horiz_line_coords[...
7a4949a4fe713c9eb9c2c3079fea09186c05a258
637,591
def triArea(coord): """Input: coord=array([[x1,y1],[x2,y2],[x3,y3]]).""" area=(coord[1,0]*coord[2,1]-coord[2,0]*coord[1,1]-coord[0,0]*\ (coord[2,1]-coord[1,1])+coord[0,1]*(coord[2,0]-coord[1,0]))/2 return area
064a050538f5af3f98ba54bb7b705081bedec103
637,592
from typing import Any from typing import List def ensure_list(item: Any) -> List: """Ensure string is converted to a Path. Args: item (Any): Anything. Returns: The item inside a list if it is not already a list. """ if not isinstance(item, list): item = [item] return...
c7895c87121f0265080cac42ab9b3ca1c23cca23
637,593
def reverse_linked_list(linked_list): """Reverse a Linked List and return it.""" node1 = linked_list.head node2 = linked_list.head.next while node2.next: node2.next, node2, node1 = node1, node2.next, node2 return node2
85b41497b06fc69cb67031ec34c90173682a5248
637,594
def get_twister2_cluster(cluster_role_env): """Get the cluster to which topology is submitted""" return cluster_role_env.split('/')[0]
ea121425bc23a54365abd18e64bc3a08b7409d3d
637,595
from pathlib import Path def join_analysis_path(data_path: Path, analysis_id: str, sample_id: str) -> Path: """ Returns the path to an analysis JSON output file. :param data_path: the application data path :param analysis_id: the id of the NuVs analysis :param sample_id: the id of the parent samp...
f698239fa576082a8af2ff2b98d1571abdf59526
637,596
def get_value(deep_dict, path): """Return deep_dict[path[0]][path[1]...""" value = deep_dict for key in path: value = value[key] return value
8d99b28917c028a31199c0411f59ed19900f11f5
637,597
def index_move(step, session) -> list: """ :param step: the step (forward or rewind) that we want to take :return: cytoscape Graph """ _ = session['index'] + step if _ > len(session['graphs_list']) - 1 or _ < 0: try: return session['graphs_list'][session['index']] exc...
ebd7d09b842bdd68644691d6770a680e5c008723
637,599
import sys def get_environment_setup(framework): """ Get environment setup such as Python version, TensorFlow version :param framework: framework name :return: a dictionary of environment variables """ env_setup = dict() python_version = "{}.{}.{}".format(sys.version_info.major, ...
fed0e26c6f4f27e6dbd0bffd16b4349b94ba58c1
637,600
def is_draft(catalog_record): """ Is the catalog record a draft or not. Args: catalog_record (dict): A catalog record Returns: bool: True if record is a draft """ if catalog_record.get('state') == 'draft': return True return False
aa61fccf2678582394632ce8fb0e52e28d527ba3
637,602
def fixture_channel(pika): """Create a mock channel.""" channel = pika.BlockingConnection().channel() return channel
e9c2ff420964d5eabc6d950205700fc59285da68
637,603
def full_rb_decay(A, B, C, lambda_1, lambda_2, m): """Eq. (15) of Wood Gambetta 2018.""" return A + B * lambda_1 ** m + C * lambda_2 ** m
602f425025add047ee3502e73f7a5487be4da425
637,604
from pathlib import Path def get_classes(all_lsR_files, ctanDict): """ Get all the .cls files from the ls-R database and extract the corresponding details from ctanDict if the entry exists :param all_lsR_files: The list of all files listed in ls-R :param ctanDict: A dictionnary built from the CTAN pa...
8f163fb5dd1961dfe81499cf764f7c4801675bf4
637,605
def translate_list(dictionary, list_to_be_translated): """For a given list with entries and a dictionary, it return a new list with the translated entries""" translated = [] for i in list_to_be_translated: translated.append(dictionary[i]) return translated
20874aba3b03e11d9386d8fd425f2751c19163d2
637,606
import re def strsplit(string, substrings): """Splits up the specified string at each occurrence of any of the specified substrings, removing the substrings. Returns a list of strings and a list of matching substrings. If no match is found, return the empty list. """ assert(type(string) == str) ...
21c5a0dada0344c69ef6cab7ff28262a9dac5d40
637,607
def get_message_id(timestamp, topic): """Unify the way to get a unique identifier for the given message""" return '{}{}'.format(timestamp, topic.replace('/', '_'))
072d03347ce44d30ebbe28ad6ff2559c021784db
637,608
def local_env(_, node): """get local environment""" return node.parent.local_env.symbols
a1bb7fc910c31d49d88a9cc854940bc2ed4b5554
637,609
def zero_pad_list_func(l): """ Make a function from a list of positive numbers to pad this list on the left with zeros according to length of the maximum number. """ max_len = len(str(max(l))) return lambda i: str(i).zfill(max_len)
124d8015594688f77e13f96f0588b985a9eb2cca
637,610
def group_by(l, col=None): """Example: >>> l = [{"a":1},{"a":2}] >>> utils.group_by(l,"a") {1: [{'a': 1}], 2: [{'a': 2}]} """ out_dict = {} for i in l: if col != None: out_dict.setdefault(i[col],[]).append(i) else: out_dict.setdefault(i,[]).append(i) ...
3f579165eb3602664b6d0a40c775e22da2446e83
637,611
def _services_around_node(node_geometry, services_gdf, services_gdf_sindex, radius): """ It supports the weight_nodes function. Parameters ---------- node_geometry: Point geometry the street services_gdf: Point GeoDataFrame services_gdf_sindex: Rtree Spatial Index radius: f...
7782734c56f1dc8c24427543765f5a5e3ab61868
637,612
import math def estimate_cost(path_length, frequency, cost_by_dist, antenna_height): """ Estimate the link cost. """ output = [] cost_dict = {} for key, value in cost_by_dist.items(): lower = int(key.split('_')[0]) * 1e3 upper = int(key.split('_')[1]) * 1e3 if int(lo...
405950296cdd5e7708cc699602db9e2e182c846e
637,613
def norm_path(path): """Returns a path with '/' and remove the trailing slash.""" path = path.replace("\\", "/") if path[-1] == "/": path = path[:-1] path_elms = [] for path_elm in path.split("/"): if path_elm == "..": if len(path_elms) > 0: path_elms.pop(...
ded1105a5ecd4a6a58ac8c20a9822cb5bbe57b9e
637,615
def is_affirmative(value): """ Attempt to convert different type of values to a meaningful boolean """ # try string cast if isinstance(value, str): return value.lower() in {'yes', 'true', '1', 'y', 'on'} # use object's implementation of `__nonzero__`, it's faster than cast. # None -...
64b497f792f20f047622043436a97beb1dfd7413
637,616
import networkx as nx import pickle import codecs def plot_aces_conversion_graph(graph, filename, prog="dot", args=""): """ Plot given *aces-dev* conversion graph using `Graphviz <https://www.graphviz.org/>`__ and `pyraphviz <https://pygraphviz.github.io>`__. Parameters ---------- graph :...
7039de32067874f131dbedd8ae11f11c64c3a47a
637,617
def perform_group_by(h2oFrame, na): """ Given a H2OFrame h2oFrame, and the na treatment, perform chained group by aggregation and return the results of aggregations in an H2OFrame. :param h2oFrame: :param na: :return: """ grouped = h2oFrame.group_by("class") grouped.count(na=na).min...
440c61e437785a04147bc5afd9f252d6ce72c0eb
637,618
import string import random import secrets def create_product_reference(): """Creates a product reference number: AC4565ZE4TEZD """ # Create two first letters ex. AC capital_letters = string.ascii_uppercase first = ''.join(random.choice(capital_letters) for _ in range(0, 2)) # Get a number bet...
b1b93d90712388423446158c0f614adc353e158e
637,619
def getWarningHeader(): """ Returns the 'warning' part in output file """ str = "" str += "-------------------------------------------------------------------------------------------------------\n" str += " WARNING !\n" str += "\n" str += " Propka3.0 is not identical to propka2.0 and...
44c1dc51f0448e15882f1fdfc84188bfd9469614
637,620
def get_requirements(path): """ Import user's requirement file and save as a variable """ user_requirements_list = [] with open(path, 'r') as filehandler: user_requirements_list = [package_name.rstrip() for package_name in filehandler.readlines()] return user_requirements_list
b0eb1738cd26da9a83177c430297f83dc7e17e17
637,621
from typing import Optional from typing import Union def conv_ee_anteil(input_value: Optional[Union[str, float, int]]) -> Optional[float]: """ Converts the number of the percentage column to the correct percentage if possible. Numbers will be forced to be between 0% and 100% """ if input_value is ...
9d60cb16d747bc84c2064cc085cc5d64956e7ba9
637,622
def _CreateExceptionRetryHandler(exception): """Returns a retry handler for given exception(s). Please see WithRetry class document for details. """ if not (isinstance(exception, type) and issubclass(exception, Exception) or (isinstance(exception, tuple) and all(issubclass(e, Exception) fo...
a7d3c5d095de3ac65eb1ad22fe92b86cde00c4e3
637,623
def land(*fns): """ Functionally logical ands the given functions. >>> lor(starts_with('123'), ends_with('asd'))('123asd') True >>> land(starts_with('123'), ends_with('asd'))('asd') False >>> land(starts_with('123'), ends_with('asd'))('123') False :param fns: Functions to and :...
8b48e5862704548515593d8183aa88b82392da51
637,624
def p_w_from_rh_p_and_ws(rh, p_ws): """ Calculate water vapor pressure from relative humidity and water vapor saturation pressure Eq(6) in "CHAPTER 6 - PSYCHROMETRICS" in "2001 ASHRAE Fundamentals Handbook (SI)" :param rh: relative humidity [-] :type rh: double :param p_ws: water vapor saturati...
62ba0ab8ced023899e58817a31a3a08d434d94bb
637,625
def getUser(ctx, *arg): """ returns a user id from either the arguments or if None is passed the sender """ if arg == (): # if no argument is passed go with sender return(ctx.author.id) else: return(arg[0].strip('<!@> '))
61bd3b47d9b3553349530d5292804d703f1dc5ed
637,626
def entuple(x,n=2): """ Make sure given value is a tuple. It is useful, for example, when you want to provide dimentions of an image either as a tuple, or as an int - in which case you can use `(w,h) = entuple(x)`. :param x: Either atomic value or a tuple. If the value is atomic, it is converted to a tu...
c5e8ca94d552b746b45342b803dd267cd7c481f3
637,628
def get_func_code_details(my_F): """Extract co_code, co_consts, co_argcount, func_defaults """ bytecode = my_F.__code__.co_code consts = my_F.__code__.co_consts argcount = my_F.__code__.co_argcount defaults = my_F.__defaults__ return bytecode, consts, argcount, defaults
3ce4ed957d142eb79ec5c65ac101c636324103fa
637,629
def _build_time_predicates( from_date=None, to_date=None, ): """ Build time range predicates """ must = [] if from_date: must.append("start={}".format(from_date)) if to_date: must.append("end={}".format(to_date)) return "&".join(must)
1c4153c6026aab7e42e4ccadf7b6f8fe436aa219
637,630
import math def turn_easting_northing_into_six_fig(easting, northing): """Turn OS easting and northing values into the six figure OS grid refecence. See http://www.jstott.me.uk/jscoord/""" first_letter = "" second_letter = "" #@UnusedVariable easting = int(easting) northing = int(northing) # Get the 100 km pa...
457125289e2ec4c85e83b36b65d7cfe966e085ab
637,631
def one(seq, too_short=None, too_long=None): """ one([]) -> exception one([1]) -> 1 one([1, 2]) -> exception :param seq: :param too_short: exc_val :param too_long: exc_val :return: """ it = iter(seq) try: value = next(it) except StopIteration: raise too_s...
713604ef13109d84256544620c1c40896090a71a
637,632
def _parse_or(t): """Evaluate OR t.""" try: return t[0]["lhs"] except KeyError: try: return t[0]["rhs"] except KeyError: return False
89b224f94aed659fd9e29766479496a3d3689daa
637,633
def connection_table_to_matrix(conn_df, group_cols='bodyId', weight_col='weight', sort_by=None): """ Given a weighted connection table, produce a weighted adjacency matrix. Args: conn_df: A DataFrame with columns for pre- and post- identifiers (e.g. bodyId, type or instance)...
a12819057e6d9c9d7d2df94485a211babaf20989
637,634
import re def Q_022(): """ 22. カテゴリ名の抽出 記事のカテゴリ名を(行単位ではなく名前で)抽出せよ. """ regex = re.compile(r'(?<=^\[\[Category:)(.+)(?=\]\]$)') category_list = [] with open('data/Britain.txt', 'r') as f: for line in f: matchObj = regex.search(line) if matchObj: ...
1bc10a353a7a577a30cbfaf89e1f6df4cf1261f6
637,635
import yaml from typing import OrderedDict def yaml_dump(data, stream=None, dumper=yaml.Dumper): """Special dumper wrapper to modify the yaml dumper.""" class Dumper(dumper): """Custom dumper.""" # Handle Ordered Dict Dumper.add_representer( OrderedDict, lambda self, data: se...
3798f80c193a0446ffc7523a2617a9380462f033
637,636
def _SkipTreeCheck(input_api, output_api): """Check the env var whether we want to skip tree check. Only skip if include/v8-version.h has been updated.""" src_version = 'include/v8-version.h' if not input_api.AffectedSourceFiles( lambda file: file.LocalPath() == src_version): return False return ...
b3d577e6b72f22208af22f174f2479afbb1e4570
637,637
def translate_to_slack(datum, casa): """ For a single entry in the query results, create a dict with the relevant information. """ if datum['ementa'] == 'None': resumo_tipo0 = 'Excerto' resumo0 = datum['resumo'] else: resumo_tipo0 = 'Ementa' resumo0 = datum['emen...
aaaa028779da41d6d436f04b0a9796632f12d1e6
637,638
def _clip(value, lower, upper): """ Helper function to clip a given value based on a lower/upper bound. """ return lower if value < lower else upper if value > upper else value
a84395414ca4fd6739ecebc6c2e0c1ee4716f506
637,639
def parse_relative_year_value(relative_year: str) -> int: """ Parses a relative year value such as "去年" :param relative_year: The year to parse :return: An integer representing the relative value of the year, for example -1 """ if relative_year == "去年": return -1 if relative_year == ...
c530ec09a57753c08db0e121228fdf64554a18e9
637,640
def findPeerFromCache(network, version, testHeaderLength): """Finds an active peer from a (file) cached list of peers; NOT IMPLEMENTED""" return False
cfd4665ff145e4ab99ed712c8be7d6f73a1286e5
637,641
import pkg_resources def package_version(name=''): """ Get version of arbitrary package. The function relies on introspection using :mod:`pkg_resources`. Parameters ---------- name : :class:`str` Name of package the version should be obtained for Returns ------- version ...
27d787cd3ed51f9105dce4d8eb1915579883bbdf
637,642
import numpy def pansharpening_brovey( rgb: numpy.ndarray, pan: numpy.ndarray, weight: float, pan_dtype: str ) -> numpy.ndarray: """Apply Brovey pansharpening method. Brovey Method: Each resampled, multispectral pixel is multiplied by the ratio of the corresponding panchromatic pixel intensity to...
4d346e7b6d57cf53e545fc6549023dccab7d1583
637,643
def get_std_error_from_channel(channel): """Get std Error from an existing channel""" stderr = "" # Make sure we read everything off the error buffer if channel.recv_stderr_ready(): error_buff = channel.recv_stderr(1024) while error_buff: stderr += error_buff erro...
c19be3f5d513067e89b853dc532e7b376305c43c
637,644
import argparse def parse_args(): """Self-explanatory.""" parser = argparse.ArgumentParser( prog='paranestamol', description="Paranestamol, graphical nested sampling visualisation.", usage='python3 -m %(prog)s [options]') parser.add_argument('file_roots', me...
6d4f4dc6468aa6f05b06faac1aa273dcfc350ce6
637,645