content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def _get_last_cell(nb): """ Get last cell, ignores cells with empty source (unless the notebook only has one cell and it's empty) """ # iterate in reverse order for idx in range(-1, -len(nb.cells) - 1, -1): cell = nb.cells[idx] # only return it if it has some code if cel...
e99ab592a480c015f028e622dad587bd1bf5fdcb
672,609
def _lsmdc_to_list(lsmdc, lsmdc_window=20): """ :param lsmdc: Dataframe :param lmsdc_window: # We'll allow lsmdc_window seconds of a gap between chains :return: a list of annotations """ movie = '' t_end = 0 lsmdc_list = [] cur_chain = {'sentences': []} for (i, item) in lsmdc.ite...
b79c559ad1221802432418d22553701e565db314
672,610
def data_for_ray_slice(radar, ray_sl, fieldnames=None): """ Given a slice object ray_sl, return r,az,el,t,data corresponding to the fieldnames. If fieldname is None, no data will be returned. Fieldnames should be a sequence of field names. A data dictionary is returned with a key for each of...
d1c21d4964394df0494cff106d6ab857d9704132
672,611
def filter_out_unchanged(result, context={}, kind=None): """ Helper function to filter out unchanged results recursively based on their specified types. """ # Build qualified type string for the result kind = ".".join(filter(None, [kind, result.get("_type", None)])) # Loop through all keys in ...
b13027e9d99f89f70ab3819435a60fc65f91fc59
672,612
def Convert (call_lines, startAddr, endAddr): """Converts the call addresses to static offsets and removes invalid calls. Removes profiled calls not in shared library using start and end virtual addresses, converts strings to integer values, coverts virtual addresses to address in shared library. Returns: ...
f3e152be1fb8b3d8297a0e45d1f81a27110e6bf9
672,614
def should_sync(data, last_sync): """ Determine if a data collection needs to be synced. """ # definitely sync if we haven't synced before if not last_sync or not last_sync.date: return True # check if any items have been modified since last sync for data_item in data: # >=...
1a289af57af8119ee78586a32032227c7fa7c40d
672,615
def get_accuracy(y_bar, y_pred): """ Computes what percent of the total testing data the model classified correctly. :param y_bar: List of ground truth classes for each example. :param y_pred: List of model predicted class for each example. :return: Returns a real number between 0 and 1 for the model accura...
e5c9f54c214aa87fff9d5b98d6b60b73850b8ad6
672,616
import argparse def get_args(): """ Process property file and return various attribute :return: various attribute of runs """ #global properties_file # Assign description to the help doc parser = argparse.ArgumentParser( description='Populate various table with metadata for each datahub\ to be processed f...
d63bfdcf2509af8907b2c9c8a2f3e607790c6f9a
672,617
def shell_sort(arr): """ Fuction to sort using Shell Sort <https://en.wikipedia.org/wiki/Shellsort>. :param arr: A list of element to sort """ gap = int((len(arr)/2)) while gap > 0: for i in range(gap, len(arr)): temp = arr[i] j = i while j >=...
5a559b25f092c73371537cfc79123cf49498f0bc
672,618
def not_equals(x): """A functional !=. >>> not_equals(2)(2) False >>> not_equals("David")("Michael") True """ def not_equals(y): return x != y return not_equals
27ae5dda655e854abbaf126643d26eb1577449d9
672,619
from typing import Sequence from typing import KeysView def short_repr(obj, noneAsNA=False): """Return a short representation of obj for clarity.""" if obj is None: return "unspecified" if noneAsNA else "None" elif isinstance(obj, str) and len(obj) > 80: return "{}...{}".format( ...
9bd6537592188225533395422750baea73841609
672,620
from typing import List def wrap_text(string: str, max_chars: int) -> List[str]: """A helper that will return a list of lines with word-break wrapping. :param str string: The text to be wrapped. :param int max_chars: The maximum number of characters on a line before wrapping. :return: A list of strin...
a0e990ef50f0c54ff40a5962f4a052f3d9916563
672,622
import numpy import torch def sample_2d_latent_vectors(encoding_space, n_img_x, n_img_y): """ :param encoding_space: :param n_img_x: :param n_img_y: :return:""" vectors = numpy.rollaxis( numpy.mgrid[ encoding_space: -encoding_space: n_img_y * 1j, encoding_space: -encod...
d36c451c56ff7e5d9d33d070129c952ec4b00db3
672,623
import math def get_sqrt_shape(area): """ Returns a square shape, assuming the area provided can be square. """ height = int(math.sqrt(float(area))) width = height return width, height
89e3ae2d36bcbd501021a8a65b019d71741dfd53
672,624
import torch def extract(v, t, x_shape): """ Extract some coefficients at specified timesteps, then reshape to [batch_size, 1, 1, 1, 1, ...] for broadcasting purposes. """ out = torch.gather(v, index=t, dim=0).float() return out.view([t.shape[0]] + [1] * (len(x_shape) - 1))
002f87ffe1393ad838b6002929af09b9dfba6400
672,625
def interpret_origin(geom, origin, ndim): """Returns interpreted coordinate tuple for origin parameter. This is a helper function for other transform functions. The point of origin can be a keyword 'center' for the 2D bounding box center, 'centroid' for the geometry's 2D centroid, a Point object or a ...
f88fdc42bbe0fa319acefadb8be80b34dfa047e1
672,626
import torch def _clip_barycentric_coordinates(bary) -> torch.Tensor: """ Args: bary: barycentric coordinates of shape (...., 3) where `...` represents an arbitrary number of dimensions Returns: bary: Barycentric coordinates clipped (i.e any values < 0 are set to 0) an...
880f2c8ae3d6c07ac6f02d75e8d2c1e58f42586f
672,627
import ctypes import os def is_admin(): """ Check whether script is executed using root privileges. """ if os.name == 'nt': try: return ctypes.windll.shell32.IsUserAnAdmin() except ImportError: return False else: return os.geteuid() == 0
9e2a76e52f2bbdbf87e79f5107583c93adeb5b52
672,628
def normal_row_count(model_cls, db): """ Uses a normal .count() to retrieve the row count for a model. """ return model_cls.select().count()
0fc5840fbe8212e0d1a43f4b64b34ac01d08045c
672,629
def format_mac(syslog_mac=""): """ Given mac address is formatted as XX:XX:XX:XX:XX:XX """ syslog_mac = "%s:%s:%s:%s:%s:%s" % ( syslog_mac[0:2], syslog_mac[2:4], syslog_mac[4:6], syslog_mac[6:8], syslog_mac[8:10], syslog_mac[10:12]) return syslog_mac
e55848ca12e14c741fb767f77c4eb98d93f3cb52
672,630
def text_objects(text, font, color): """This function creates text objects in the pygame display. It takes a string, a font and a color for the text and it returns a variable with the details about the text. """ textSurface = font.render(text, True, color) return textSurface, textSurface.get_rect()
dd8f7f9af642921a99004eb443ad5a521e5b9d2d
672,633
import collections def create_dict(normalized_sentences): """ 创建字典及索引字典 """ # 计算词频 words = " ".join(normalized_sentences).split() count = collections.Counter(words).most_common() print("Word count top 5 ", count[:5]) # 构建字典 unique_words = [i[0] for i in count] dic = {w: i for ...
dad173dba7a26701f4ea01e875f25e671cb2b3bf
672,634
def get_us_gpa(average) -> float: """Return the GPA as calculated in the US.""" result = 0 if average >= 60: result = 0.7 if average >= 63: result = 1 if average >= 67: result = 1.3 if average >= 70: result = 1.7 if average >= 73: result = 2 if ave...
a26cbf727a268738895f8c64ca2c1194170eb96e
672,635
import pandas as pd def pandasFromCube(cube, dataColumnName="value", keepIndexOrder=False ): """ Return indexed Dataframe created from cubePy Cube """ multiIndexValues = [idx.values for idx in cube.axes] allIndexNames = [idx.name for idx in cube.axes] multiindex = pd.MultiIndex.from_product(m...
e8cdc5bed1c1869b91fb75d3dab7541c8601ecbd
672,636
def longestString(listOfStrings): """ return longest string from a non-empty list of strings, False otherwise By "longest", we mean a value that is no shorter than any other value in the list There may be more than one string that would qualify, For example in the list ["dog","bear","wolf","cat"...
14244a76c65fcffc255f203eb7d1f8aa098b9cd2
672,637
def summarize_children(queues: dict) -> dict: """ All parent queues have zeroed counters. So apply all the outer edges with metric values to the parent nodes """ averaged_nodes = set() edges = tuple(queue for name, queue in queues.items() if not queue.children) for node in edges: me...
4d0e8814d2f61ad818039b84407a226c70455d45
672,638
import os import fnmatch def find_files(directory, pattern): """ Method to find target files in one directory, including subdirectory Parameters: directory: path pattern: filter pattern Return: target file path list """ file_list = [] for root, _, files in os....
df2e85d6a4b3ba97677bdcf7d927f9870a1fd830
672,640
import re def make_scanner(regex): """ Make log scanner for scanning potential attack using regex rule. :param regex: regex rule for detecting attack in the log line :return: function that scan for the attack in log file using the regex """ def scanner(line): return True if re.search(...
f99264bb57febeb27999469107bd2ec92a7d5c84
672,641
def prepare_generators_df(df_all_generators): """ Prepare the dataframe for generators """ # reset index df_all_generators = df_all_generators.reset_index(drop=True) # rename columns df_all_generators = df_all_generators.rename( columns={"tags.generator:output:electricity": "power_...
0b7d17c5a8582e34918e56f00111637932a3b27d
672,642
import argparse def get_args(): """Parse any command line arguments""" parser = argparse.ArgumentParser() parser.add_argument( "pkg", nargs="+", help="Full path to the package(s) to upload", ) parser.add_argument( "--replace", help="overwrite an existing uploaded package (e...
e688412b0c7113229f81f0d868a8ff810d09ffd9
672,645
import numpy def container_copy(dst_obj, src_obj, dst_idx=0): """ Copy values to `dst` by iterating element by element in `input_obj` """ # zero dimensional arrays are not iterable # if issubclass(type(src_obj), (numpy.ndarray, dparray)) and (src_obj.ndim == 0): if issubclass(type(src_obj), (...
1f8f59d5afe57a9134da531f81812d2a63935164
672,646
import os def complete_path(path_type, incomplete, base_directory="."): """Helper method for implementing the completions() method for File and Path parameter types. """ # Try listing the files in the relative or absolute path # specified in `incomplete` minus the last path component, # other...
e66a1808aa008c6b1a738bcd6653a8ff7a0145e1
672,647
def has_duplicates(t): """Checks whether any element appears more than once in a sequence. Simple version using a for loop. t: sequence """ d = {} for x in t: if x in d: return True d[x] = True return False
cc84a39d88ef7b92e173c96e5f68813b71609297
672,648
def inference_alexnet(net, input_layer): """Sergey: http://ethereon.github.io/netscope/#/gist/5c94a074f4e4ac4b81ee28a796e04b5d Reference AlexNet with grouped convolutions removed. """ net.use_batch_norm = False x = net.input_layer(input_layer) # Note: VALID requires padding the imag...
62240bdaf1dab2d345113f77530ac5fc782e2214
672,649
def calculate_score(constellation, data): """ Function to calculate constellation score.""" score = 1 for v in constellation: score *= (1 - data['coverage'][str(v)]) score = 1 - score return score
ff94f0404a9fc8b74a35da2c9c4bbb4caabf9b2f
672,650
import collections def _get_output_map_from_op(varmap, op): """Returns a dict from op output name to the vars in varmap.""" iomap = collections.OrderedDict() for key in op.output_names: vars = [] for varname in op.output(key): vars.append(varmap[varname]) if len(vars) =...
33d32952c9077bf78c6e4c5672880786ed28075d
672,651
def to_datetime(val): """Used if *val* is an instance of datetime.""" # NOTE: see to_date # return val.strftime("%Y-%m-%d %H:%M:%S %Z") return val.isoformat()
5089b47c4128e698bfe561d5c929ca95a93f006a
672,652
def dollar_to_numeric(value): """$14,230 -> 14230""" if type(value) != str : return value else : return float(value.lstrip('$').replace(',', ''))
91a9ca1cb6553dd34edfa2e44d25c51145a0e16b
672,653
def validateDict(user_cfg={}, defaults={}):# dict """ validates a dictionary by comparing it to the default values from another given dict. """ validated = {} for each in defaults: try: validated[each] = user_cfg[each] except KeyError: validated[each] = d...
361ce3a804627540ab15a53a55af2b9f828541fe
672,654
def apply_sentiment_to_text(text, price_data): """ Labels text items according to price sentiment. """ text['sentiment'] = '' for text_time in list(text.index): nearest_index = price_data.index.get_loc(text_time, method='ffill') text['sentiment'][text_time] = price_data['sentime...
50fb7c97d888c145fe1ec3c5df4a0604bbadf322
672,656
def wrap_text_begin_end(title, body): """Wrap a block of text with BEGIN and END for PEM formatting.""" return ( "-----BEGIN %s-----\n" % (title,) + body + "\n-----END %s-----\n" % (title,) )
380ff08610cce2503d6a4dd04bfc35b5fe384175
672,658
def _is_bin_centers(container, var, dim): """ Is var considered to be bin_centers in dimension dim Considers all meta including non-dimensional meta :param container: scipp object defining all meta :param var: variable to determine if bin centers :param dim: dimension to consider :return: T...
93f0d5176de965ff7a9ffce674cf6f298dc4ff97
672,659
import re def extract_integers(string): """Extract all integers from the string into a list (used to parse the CMI gateway's cgi output).""" return [int(t) for t in re.findall(r'\d+', string)]
3313d79756f97d316dfb99c3b176d94f4e5d1df3
672,660
def full_name(family, style): """Build the full name of the font from ``family`` and ``style`` names. Names are separated by a space. If the ``style`` is Regular, use only the ``family`` name. """ if style == 'Regular': full_name = family else: full_name = family + ' ' + style ...
cdff8d6ae15170c5e9474874c9385dfd9b4999df
672,661
def try_parse_int(value): """Attempts to parse a string into an integer, returns 0 if unable to parse. No errors.""" try: return int(value) except: return 0
aa55a4764f6873337f1506b0c7b3e1e3b31f6671
672,662
def de_escape(s): """ example: 7e 40 09 00 be ef 05 7d 5d 06 7d 1e 03 04 05 7e becomes: 7e 40 09 00 be ef 05 7d 06 3e 03 04 05 7e """ r = [] next_byte_inverted = False for c in s: if ord(c) == 0x7d: next_byte_inverted = True else: if ...
7e128cc92dad08a6b0e593738a37e6d3c803b49c
672,663
import hashlib def get_signature(item): """ Returns the sha256 hash of a string """ hash_object = hashlib.sha256(item.encode()) return hash_object.hexdigest()
bbb35a9d5b06f42c76bea4f00c1763199f2bf609
672,664
def safe_pandas_length(o): """ Return the length of a pandas Series and DataFrame as expected for WL serialization. - The length of a Series is the only value of the tuple `shape`. - The length of a dataframe is the number of columns. It's the second value of `shape`. This function is safe, when the s...
ae2a27b2708350cfb7de210ecce265d91f54748b
672,665
def round_to_fraction(val, res, decimals=None): """ round to closest resolution """ if val is None: return 0.0 if decimals is None and "." in str(res): decimals = len(str(res).split('.')[1]) return round(round(val / res) * res, decimals)
7f07aeda855cb867d3ec8871b6a8e4a06b9fb47b
672,666
async def checktasktype(tasknumber: str) -> str: """check the type of task""" """if tasknumber[1] == 'd': tasktype = 'daily'""" if tasknumber[1] == 'w': tasktype = 'weekly' elif tasknumber[1] == 'm': tasktype = "monthly" elif tasknumber[1] == 'q': tasktype = "quarterl...
cdcf61802ea70c609e82e6b1519d7ceab77de43a
672,667
from typing import Any def is_int(value: Any) -> bool: """Checks if a value is an integer. The type of the value is not important, it might be an int or a float.""" # noinspection PyBroadException try: return value == int(value) except Exception: return False
f9b1c28f6c954376373a1d8ea8de533d2b4c8974
672,668
import pandas def mock_df(): """Sample pytest fixture. See more at: http://doc.pytest.org/en/latest/fixture.html """ with open("tests/mock_report.html", "r") as data: df = pandas.read_html(data)[0] return df
de08f16fd9cc39065431d7f306e6b2cacd9cdf78
672,669
import os import glob def _get_image_lists(data_dict, fits_type): """Add a list of JPEG and Thumbnail paths to the ``data_dict`` dictionary. Parameters ---------- data_dict : dict A dictionary containing data used to render a webpage. fits_type : str The FITS type. Can either...
3a9ed20ae5173cdcd087dca195c067f3f7566a55
672,670
def frhs(phi, tau): """ reaction ODE righthand side """ return 0.25*phi*(1.0 - phi)/tau
ff5775d71894f7c9c73e5d96858dd4fac6c62da0
672,671
import sqlite3 def Add_IP(myip,now_date): """ 在指定的数据库中加入myip这个IP地址 如果数据库中存在myip这个IP地址就不加入,并且函数返回 0 不存则加入这个IP地址到数据库,并且函数返回 1 """ conn = sqlite3.connect('/mnt/Black_16G/share_pi/project/get_ip/all_ip.db') c = conn.cursor() c.execute("CREATE TABLE if not exists out_IP (id integer primary...
cb29feca3da103975fbe30122d1d7dd55aa092e8
672,673
def _res_heur(data, *args, **kwargs): """ Returns, for the given data, the heuristic determining the resolution of the voxel grid and correspondingly, how many points get hashed to the same value. """ return 3 * len(data) ** 0.33333333
a14ed6ae638d65c9571a750478c9f8b7c7cd2909
672,675
import platform def get_platform() -> str: """ Get the string representing the platform running the code. :return: the system string to download files from Protobuf git """ system = platform.system() if system == "Linux": return "linux" elif system == "Darwin": return "osx...
08775c4a602e1110ef37bf45e5244c6fbd5adec2
672,676
def state_to_int(p, statelist): """ Converts array of fermion-configuration into integer Args: p - dictionary that contains the relevant system parameters statelist - fermion configuration Returns: out - integer corresponding to state """ # construct unique integer for th...
c07cba94e669e12fd82e6f6f46163661405f99ca
672,677
def _test_model_name(func, param_num, param): """ expects the first param to be the model number""" return f'{func.__name__}_model_v{param.args[0]}'
35c263366a798ddf904dfaa71eccb8e3c3d38612
672,678
import os import click def is_project_initialised(folder_location): """Check a folder does not exist and can be created""" cfg = os.path.join(folder_location, "made.config") # Folder exists and config exists if not os.path.isdir(cfg): click.echo(click.style("This project folder has not been i...
96107e80915513eaa66f5e650f9ba577ec5fbde7
672,679
import re def is_latlong(instr): """check whether a string is a valid lat-long.""" return (re.match(r'^\s*[0-9.+-]+\s*,\s*[0-9.+-]+\s*$', instr) != None)
611181fa0f6b95b735a5df7629c01985b54b5f21
672,680
def get_drive(): """ ask user which drive of the controller should be used return its index """ drive_input = input("Which drive: 1 or 2? ") while (drive_input != "1") and (drive_input != '2'): drive_input = input("This drive does not exist. Pick drive 1 or 2: ") drive = int(drive_in...
d932ca07cf885045aae9159851c0c1119af6990b
672,681
def member_joined_organization_message(payload): """ Build a Slack message informing about a new member. """ member_name = payload['user']['name'] member_url = payload['user']['url'] org_name = payload['organization']['name'] org_url = payload['organization']['url'] message = 'Say hi! ...
f57dfdbf1cf1e305be9c67366093849493e63c6d
672,682
def filter_errors(e, select=None, ignore=None, **params): """ Filter a erros by select and ignore options. :return bool: """ if select: for s in select: if e['text'].startswith(s): return True if ignore: for s in ignore: if e['text'].starts...
b7de16f06238604281b870cf2e787de9ff68d9f1
672,683
import torch def p_relu(x, weight): """Parametric Rectified Linear Unit. It follows: ``` f(x) = alpha * x for x < 0 f(x) = x for x >= 0 ``` where `alpha` is a learned parameters , it's a 1-D array, the length equal 1 or input_filters. Args: x (Tensor): input te...
3df9d04da7ba484f82bbeaf7ecb31463a0f317b1
672,684
import yaml def parse_file(path): """Super simple utility to parse a yaml file given a path""" with open(path, 'r') as cfile: text = cfile.read() conf = yaml.load(text, Loader=yaml.CLoader) return conf
899ab670a69d4faa4c008848c4cfb979e3f29c51
672,685
import codecs def rot13(text): """ ROT13 transforms given text. """ return codecs.encode(text, "rot_13")
5fcaa83a548b6e746781d48d03f9d9782eeda7bf
672,686
def load_dataset(filepath): """Loads a file on the CoNLL dataset. :param filepath: Path to a text file on the CoNLL format. :return (X, Y) lists of sentences and labels. """ X = list() x = list() Y = list() y = list() for line in open(filepath): # blank lines sepa...
b06d853abb5a616b64ae765875ef3954522fcdfe
672,687
def compare_dicts(d1,d2): """Function that reads in two dictionaries of sets (i.e. a graph partition) and assess how similar they are. Needs to be updated so that it can adjust this measure to include partitions that are pretty close.""" if len(d1)>len(d2): longest_dict=len(d1) else: ...
4947557825743e2dab61eedd454d8e2a94ad80ac
672,688
def _func_overhead(q, p, n): """ Model function to calculate the overhead. :param q: Actual overhead parameters values :param p: Numbers of cores used on model data :param n: Problems size used on model data :return: calculated overhead value """ return q[0]+(q[1]*p)/pow(q[2], n)
7c6e41fdb829bb3c653887df0a565c3b406afdd8
672,689
def _f1(precision: float, recall: float) -> float: """ Compute f1. :param float precision :param float recall :return: f1 :rtype: float """ if precision == recall == 0: return 0 return 2 * precision * recall / (precision + recall)
f1e19ef9ed614355166989a18d556d4afd11af16
672,690
def CleanIndent(text, prefix=''): """Remove extra indentation from comments or code. This allows code to be written as triple-quoted strings with natural indentation in the python file, and that indentation will be removed and replaced with the provided prefix. Args: text: Input code prefix: will be...
b980dae9f18dac6681fe3955d94cc27d95f4fabb
672,691
def escape(v): """ Escapes values so they can be used as query parameters :param v: The raw value. May be None. :return: The escaped value. """ if v is None: return None elif isinstance(v, bool): return str(v).lower() else: return str(v)
304079292532ef905099f1fd047ddb95df231076
672,692
import os def get_test_data_folder() -> str: """Return absolute path to test data folder.""" return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
5953cc079fd44da73446de9e641755c69128b8e2
672,693
def _css_select(soup, css_selector): """ Returns the content of the element pointed by the CSS selector, or an empty string if not found """ selection = soup.select(css_selector) if len(selection) > 0: if hasattr(selection[0], 'text'): retour = selection[0].te...
5b9dc2c2a26957e32aab1ac86dde85a8efd39bcf
672,695
import re def is_compatible(source_version, compat_versions): """ Compare a source version string to a set of target version string specifications. Supports semantic versioning comparison via setuptools version comparison logic (http://setuptools.readthedocs.io/en/latest/setuptools.html#id7). :param ...
05c2df2282685e44c482afb9cbbfc7646b806fe7
672,696
from typing import List def set_symmetric_difference_sort(arr_1: List[str], arr_2: List[str]) -> List[int]: """ >>> set_symmetric_difference_sort(['2', '4', '5', '9',], ... ['2', '4', '11', '12']) [5, 9, 11, 12] """ return sorted(map(int, set(arr_1) ^ set(arr_...
2c10e4e454f7b2dedaa51a8e26dae127cfae08c9
672,697
def get_idx_exceeding_specified_acti_performance(log, transition_performance, activity, lower_bound): """ Get indexes of the cases exceeding the specified activity performance threshold Parameters ------------ log Event log transition_performance Dictionary where each transition...
461518923eab1f64a8544de1939abf0894058bf4
672,698
import re def _validate_timedelta_unit(arg): """ provide validation / translation for timedelta short units """ if re.search("Y|W|D",arg,re.IGNORECASE) or arg == 'M': return arg.upper() elif re.search("h|m|s|ms|us|ns",arg,re.IGNORECASE): return arg.lower() raise ValueError("invalid ti...
8d8dae58653f51e636df133e419ffefc849b434b
672,700
def _get_gallery_filters(children_data): """ Used in aurore tmpl-0001 """ filters = {} for child in children_data: for fltr in child["template_data"]: if fltr not in filters: filters.update({fltr: [child["template_data"][fltr]]}) elif child["template_d...
9d3fe95990b4dd79f053f8762b0c3dc5f375cb5f
672,701
import os def _public_key_file_path() -> str: """path to a file containing the public half of a test key""" # this was generated with: # openssl ec -in oidc_test_key.p8 -pubout -out oidc_test_key.pub.pem # # See above about where oidc_test_key.p8 came from return os.path.join(os.path.dirnam...
da7b90e314c5a1f7f21099f944d8de06dcdef4ad
672,702
def consolidate_users(duplicates): """Given an array of duplicate user objects `duplicates`, return a single (consolidated) user and an array of warnings, if applicable. """ return_user = {'username': duplicates[0]['username']} user_warnings = [] for attr in duplicates[0]: if attr != '...
5e1434c0f4e77b54304e955b32ff2349f5623120
672,703
def edge_color_weight(G,edgelist=None): """Automatically calculate a normalized reasonable color for a weighted graph Parameters: ----------- G: A networkx Graph edgelist: A list Edges to calculate the weights for if None, uses all edges Returns: -------- weight_dict: A dictio...
1d408538df26ad937e3c8964539833d95aed1081
672,704
from datetime import datetime def utc_now_str(): """ Method for get string with datetime now in utc format :return: datetime now in utc format as string :rtype: str """ return str(datetime.utcnow())
6c344731d6cfc91c805d84b104a12ba2d669af8e
672,706
def comp_radius_mid_yoke(self): """Compute the Lamination middle of the yoke radius Parameters ---------- self : Lamination A Lamination object Returns ------- Ry: float middle of the yoke radius [m] """ Hyoke = self.comp_height_yoke() if self.is_internal: ...
125b27770485c2eeb82a26fd31e54e14ad6e4829
672,707
def _VariableDeclaration(language, variable_name, variable_expression): """" Returns the variable declaration, without indentation nor suffix. The expression must have been turned into code already. """ return { "c" : "const double {name} = {expr}", "python": "{name} = {expr}" ...
c17143228dc6c255030ce318dd4f4437d7d126ac
672,708
import json def get_task_result_status(task_result): """Returns custom category of task result status""" task_result_status = 'Error' if task_result.status == 'SUCCESS': task_result_status = 'Idle' if json.loads(task_result.result).get('count', 0) > 0: task_result_status = 'Suc...
f827c3d29281c774c9f8c7f898863386ae97024a
672,709
import torch def inference(model, data, criterion, device, average_batch=True): """Run inference with full Transformer. Used to determine actual validation loss that will be seen in practice since full Transformers use teacher forcing. Args: model (nn.Module): model to run inference with ...
19bf303d1689fc025c978f60feb2c8e5258ce0b4
672,711
import csv def env_reader(infile: str) -> list: """ Read environment list from infile. Parameters ---------- infile : str Name of the file containing the environment list. Returns ------- list Nested (2D) list of the environment. """ with open(infile, 'r') as ...
3923df8630b5f2dcbc9ba14ab29af88ab07a8316
672,712
def _text_transpose_ ( text ) : """Transpose the line >>> = ROOT.TText ( ... ) >>> aT1 = a.transpose () >>> aT2 = a.T() ## ditto """ TEXT = type ( text ) na = TEXT ( text ) ## na.SetX ( text.GetY () ) na.SetY ( text.GetX () ) na.SetTextAngle ( 90 - text.GetTextAngle () ...
65da91c380d9b2bbee9cd9ed6d2ea56aed073639
672,713
import argparse def read_in_args(args): """Read in user specified parameters.""" # Set up user-specified optional arguments parser = argparse.ArgumentParser() parser.add_argument("-g", "--graph", default='partition', choices=['partition', 'internet', 'rand-reg', 'ER', 'SF'], help='Graph to partition ...
836fd1d37a2792e5bd7ac0205fe1e83d9ed4d629
672,714
def generate_data(): """Generate the data for our studie.""" return {"male": [[182, 81.6, 30], [180, 86.2, 28], [170, 77.1, 30], [180, 74.8, 25]], "female": [[152, 45.4, 15], [168, 68.0, 20], ...
44531ac39553401511bfa295f2e8000119177232
672,715
def axis_list(n_axes: int, reverse=False) -> str: """Returns a comma-separated list of axis TypeVar short names. Args: n_axes: Maximum number of axes to include in the list. n_axes=1 -> 'A1', n_axes=2 -> 'A1, A2', etc. reverse: If False, the returned list starts from A1 and counts up to An. ...
d86752bc637b3ce9a6e9440449319dac4b18e9a5
672,716
def mult_saturate(a, b, upper_bound, lower_bound): """ Returns the saturated result of a multiplication of two values a and b Parameters ---------- a : Integer Multiplier b : Integer Multiplicand upper_bound : Integer Upper bound f...
fa6b379860f18aa2e09b91086e6cfe129588f4cc
672,717
import sys def platform_is_64bit(): """Checks whether the Python interpreter is 64-bit. Returns: bool: True if running on 64-bit Python, otherwise False. """ return sys.maxsize > 2 ** 32
d6f8446eeda1082472c7e73e7a16882aeaeaf7bd
672,718
def _GetReleaseTracks(release_tracks): """Returns a string representation of release tracks. Args: release_tracks: API versions to generate release tracks for. """ release_tracks_normalized = '[{}]'.format(', '.join( [track.upper() for track in sorted(release_tracks)])) return release_tracks_normal...
2d4a66996844fe27144eb22d8eb7832d4ed9dd7f
672,719
def get_wsgi_header(header): """Returns a WSGI compliant HTTP header. See https://www.python.org/dev/peps/pep-3333/#environ-variables for information from the spec. """ return 'HTTP_{}'.format(header.upper().replace('-', '_'))
c4a41a07b53f4b2b63c7e9c197a7995a3993d20d
672,720
def proportion_of_traffic_from_top_users(tweets, users_with_freq, n): """ Return the percentage of the traffic that comes from the n most active accounts in a list of tweets. :param tweets: the list of tweets, represented as dictionaries. :param users_with_freq: a Counter of usernames with the num...
7f8226c8e7dce4fccd74a7b2ac375d8fb86213ce
672,721
def is_valid_lindblad_paramtype(typ): """ Whether `typ` is a recognized Lindblad-gate parameterization type. A *Lindblad type* is comprised of a parameter specification followed optionally by an evolution-type suffix. The parameter spec can be "GLND" (general unconstrained Lindbladian), "CPTP" (cp...
9b82f2ffabde8eeb1fe6275b592e7db46f691e3e
672,722
def make_GeoJson(geoms, attrs): """ Creates GeoJson structure with given geom and attribute lists; throws exception if both lists have different length :param geoms: list of geometries (needs to be encoded as geojson features) :param attrs: list of attributes :return: dict in GeoJson structure "...
87ad4e7a883cf192f74f96410a723eaec91af7c8
672,723