content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import math def max_crossing_subarray(given_array, start_index, mid_index, end_index): """Function To Calculate The Mid Crossing Sub Array Sum""" max_left_sum = - math.inf # Used For Sentinel Value max_right_sum = - math.inf # Used For Sentinel Value cross_start = None # Just used for variable pr...
1106b063b652e0d0d475f5b0979a138f4c48113b
47,118
def ignore_warnings(obj=None, category=Warning): """Context manager and decorator to ignore warnings. Note. Using this (in both variants) will clear all warnings from all python modules loaded. In case you need to test cross-module-warning-logging this is not your tool of choice. Parameters ----...
093fdbbc0728c3f98840c6fa54be2930cf2b9e6c
47,119
def css_classes(): """return settings or default""" return getattr(project_settings, 'DJALOHA_CSS_CLASSES', ())
21fd26e50044cd6de06000b9eb38e9b6eca6a487
47,121
import array def load_position(dir_path: str, label_file: str) -> array: """Loads position of an object from a file. Parameters ---------- dir_path : str Folder of the file. label_file : str File name. Returns ------- array Position of an object defined by a b...
cc655dc0172aff3cb8571c733e37c30e696c888c
47,122
import re def camel_2_snake_case(word): """ >>> camel_2_snake_case("HTTPResponseCodeXYZ") 'http_response_code_xyz' From https://stackoverflow.com/a/1176023/548792 """ return re.sub(r"((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))", r"_\1", word).lower()
dc20c832a212f89d51bb05302c9e1677e8f2cb83
47,123
def copy_to_device(target_device, source_device="/cpu:0"): """A transformation that copies dataset elements to the given `target_device`. Args: target_device: The name of a device to which elements will be copied. source_device: The original device on which `input_dataset` will be placed. Returns: A...
4b77ea7a13c6cbef5aa31daa3db88b79124cb786
47,124
def get_run_info(): """ get run base info """ return _global_dict["run_info"]
3c329e55c970310cbf19967eeee2f77a3eb2ae9e
47,125
def generate_configs(experiment_config): """Generate parameter configurations based on an input configuration. Input is a nested configuration where on each level there can be 'fixed', 'grid', and 'random' parameters. In essence, we take the cartesian product of all the `grid` parameters and take random s...
42b380ce9dad365efed0cba0d0bd38abde4ebd37
47,126
from datetime import datetime def now_str(time=False): """Return string to be used as time-stamp.""" now = datetime.now() return now.strftime(f"%Y-%m-%d{('_%H:%M:%S' if time else '')}")
02b73bda5f27e7c25120d50d50244bd103661c90
47,127
def set_ai_character(controller, character, gamestate, port, opponent_port): """Set the given controller to the STANDARD state playing as the given character. This is to be called repeatedly each frame while in the character selection menu. Returns true once it is complete.""" if ga...
1eaeb2baea4f6977541ae7db3ab696158e8be456
47,128
def camino_minimo(inicio, fin, rutas, ciudades, grafo): """Devuelve una lista con el camino mas corto y de menor coste entre inicio y fin (ambas ciudades de nuestro grafo) Pre: inicio, fin son las IDs de las ciudades; rutas es un diccionario con objetos Ruta (rutas[id_ciudad1][id_ciudad2]), y ciudades es un dic...
7076c291a9dec9c2de7c7765ceccfa5a3d7a4f5f
47,129
def get_custom_refinfo(*args): """ get_custom_refinfo(crid) -> custom_refinfo_handler_t const * Get definition of a registered custom refinfo type. @param crid (C++: int) """ return _ida_nalt.get_custom_refinfo(*args)
031cce0572fed275c29df37f7e928236896b37f9
47,130
import re def re_tester(regex, flags=0): """Creates a predicate testing passed string with regex.""" if not isinstance(regex, _re_type): regex = re.compile(regex, flags) return lambda s: bool(regex.search(s))
39a55bc0e9a30b8295a2550f086e4352af6631ab
47,131
def objective_function(n_splits, PopFrenetPath, curv_smoother, tors_smoother, hyperparam, smoothing, alignment, lam, parallel): """ Objective function that do the cross validation. ... """ print(hyperparam) # kf = KFold(n_splits=n_splits, shuffle=True, random_state=1) kf = KFold(n_splits=n_s...
018a0dd7c2994b9576ba39c310a7f3e36b29033b
47,132
def from_file(path: str) -> set: """ Read conditions from a file. Each line contains a separate condition. :param path: Path to file. :return: Read conditions. """ conditions = set() with open(path) as f: for line in f: conditions.add(line) return conditions
3780d540d6f300fe0a97d354ed33fa0aab803d56
47,133
def from_gca_point(gca_obj, name_header, folder_name, folder_description='', altitude_mode="ctg", style_to_use=None, pt_hidden=False, folder_collapsed=True): """ Save features from GCA object into a kml folder Parameters ---------- gca_obj : GCA name_header : str The ...
37f1748a8c17e3c380ed5599fabf2ce1f4045abc
47,134
def join_positions(pos1,pos2): """ Merge two positions and return as a list of strings pos1: iterable object containing the first positions data pos2: iterable object containing the second positions data Example: >>> join_positions('ABCD','1234') ['A1', 'B2', 'C...
cf5525a9d246501976bcb9ed74b12a13034c7525
47,135
def get_corrcal_gainsol(data,ant1,ant2,gain_int,noise,sky_cov_vecs,src_vecs,block_edges,gain_fac,maxiter=1000): """ This fuction solve for antenna gain per frequency. Method : Conjugate-gradient Method Software : python scipy.optimize --- fmin_cg Parameters ---------- data : array; sh...
84d47654c0ff0b832260cbf8f42a39ed3acc0703
47,136
def writePQR(filename, atoms): """Write *atoms* in PQR format to a file with name *filename*. Only current coordinate set is written. Returns *filename* upon success. If *filename* ends with :file:`.gz`, a compressed file will be written.""" if not isinstance(atoms, Atomic): raise TypeError(...
d1044594d5231b9fbc36e0091c0eb1aa31f9daf6
47,137
def read_intersections(fname1, fname2, band1=None, band2=None): """Read in the intersection of 2 files as an array""" bounds = get_intersection_bounds(fname1, fname2) print(f"bounds: {bounds}") im1 = copy_vrt(fname1, out_fname="", bbox=bounds) im2 = copy_vrt(fname2, out_fname="", bbox=bounds) re...
cb6bee733a078bf47acddf6922ec1334b758af58
47,139
def transformer(vocab_size, num_layers, units, d_model, num_heads, dropout, name="transformer"): """ transformer的粗粒度的结构实现,在忽略细节的情况下,看作是 encoder和decoder的实现,这里需要注意的是,因为是使用self_attention, 所以在输入的时候,这里需要进行mask,防止暴露句子中带预测的信息,影响 模型的效果 :param vocab_size:token大小 :param num_layers:编码解码...
3b68ed04cde51f1672414d124b2b74d0aeb0b06d
47,140
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): """Reusable code for making a simple neural net layer. It does a matrix multiply, bias add, and then uses ReLU to nonlinearize. It also sets up name scoping so that the resultant graph is easy to read, and adds a number of s...
f42afcf25113dd92a0692a411edbc346960d0209
47,141
def divide(data: tuple, domain='freq'): """Divide pyfar audio objects, array likes, and scalars. Pyfar audio objects are: :py:func:`Signal`, :py:func:`TimeData`, and :py:func:`FrequencyData`. Parameters ---------- data : tuple of the form (data_1, data_2, ..., data_N) Data to be divide...
1c5c89cba61230b3fcddfc3512be39c04c84f8fd
47,143
import array def norm_D_sum(D_sum): """Normalize a D_sum by the elements for each feature by smallest absolute size (that element becomes 1 in norm). For unweighted feature sensitivities, or else it unweights weighted ones.""" D_n = {} for feat, pD in D_sum.items(): pD_min_abs = min(ab...
26eda448ec7db143bc89b5319bbbc18597a88349
47,144
import torch def collate_fn(data): """Creates mini-batch tensors from the list of tuples (image, caption). We should build custom collate_fn rather than using default collate_fn, because merging caption (including padding) is not supported in default. Args: data: list of tuple (image, captio...
c60edfb028d9405d76cabded30e5fb74fd1e821e
47,145
def getLeastReplaggedCommons(): """ Returns the name of the least replagged Commons replica among s1, s2 and s3 """ return "commonswiki-p.rrdb.toolserver.org" # broken: #return urllib.urlopen("http://toolserver.org/~eusebius/leastreplag").readline()
5726416f7a1cbb09f51de81d967009005a06af1b
47,146
import json def parse_line(header, line): """Parse one line of data from the message file. Each line is expected to contain chunk key - comma - tile key (CSV style). Args: header (dict): Data to join with contents of line to construct a full message. line (string): Contents of the line. ...
452dd80f84a35f6e3532330155bade7f424c102a
47,147
def filequote(text): """Transform text to file name.""" trans = str.maketrans(' /()', '____') return text.translate(trans)
dd6237fe6c66f60c00c8a569636adf17d45d66cc
47,149
def characteristic(text, ontology=None): """ Making a ENA Biosamples characteristic """ if ontology: return [{"text": text, "ontologyTerms": [ontology]}] else: return [{"text": text}]
e7f175a1ef8137b4c0e19a28a5d74055d9363c66
47,150
from . import eds from . import epf def import_od(source, node_id=None): """Parse an EDS, DCF, or EPF file. :param source: Path to object dictionary file or a file like object or an EPF XML tree. :return: An Object Dictionary instance. :rtype: canopen.ObjectDictionary """ if ...
5c6ef6056df075c4f0918473e6a3851032bdf27a
47,152
def _strip_trailing_ffs(binary_table): """ Strip all FFs down to the last 32 bytes (terminating entry) """ while binary_table.endswith("\xFF"*64): binary_table = binary_table[0:len(binary_table)-32] return binary_table
43c14297da709f78316e460180c6c4515650f34d
47,153
def params_schedule_fn_constant_09_01(outside_information): """ In this preliminary version, the outside information is ignored """ mdp_default_gen_params = { "inner_shape": (7, 5), "prop_empty": 0.9, "prop_feats": 0.1, "start_all_orders": [ {"ingredients": ["...
4fa999ee03a8d1fb3178ad6267c5d48a23026855
47,154
def is_same_day(t1, t2, refresh_time=None): """check two times in same day""" return get_day_time(t1, refresh_time) == get_day_time(t2, refresh_time)
b8fa216f79f14b419add6b6e96c6923ba791c88e
47,156
from datetime import datetime def benchmark(synthesizers, datasets=DEFAULT_DATASETS, iterations=3, add_leaderboard=True, leaderboard_path=LEADERBOARD_PATH, replace_existing=True): """Compute the benchmark scores for the synthesizers and return a leaderboard. The ``synthesizers`` object can eith...
9168c94921c93765d68d15a32a826622c59bd6ff
47,157
def detec_data_space(): """判断是否有free分区磁盘""" diskLists = commands.getoutput(""" fdisk -l | grep -iw "^Disk" | grep "/dev/" | grep -vi "\/mapper\/" | awk -F ":" '{print $1}' | awk '{print $2}' | sort """) diskLists = diskLists.split('\n') return diskLists
fdcd3016d38c7036cef7a83d2b15c901af8ea9b7
47,159
def arctand(x): """Trigonometric inverse tangent using :func:`np.arctan <numpy.arctan>`, element-wise with an output in degree. Parameters ---------- x : array_like Input array. Returns ------- y : array_like The corresponding tangent values. This is a scalar if x is a scal...
3e10dd7bc3a65b3615e330041891a8aff2f81d5c
47,160
import struct def byte_to_float(b1, b2, b3, b4): """ A function to get a 32 bit float from 4 bytes read in order [b1, b2, b3, b4] :param b1: first byte :param b2: second byte :param b3: third byte :param b4: fourth byte :return: the byte array from b1, b2, b3, b4 unpacked as a float using ...
962480d1b9d2c50e3196b5480e9c62bf696a8f0d
47,161
def interpolate_and_average(xs, ys, interp_points=None): """ Average bunch of repetitions (xs, ys) into one curve. This is done by linearly interpolating y values to same basis (same xs). Maximum x of returned curve is smallest x of repetitions. If interp_points is None, use maximum number of p...
35e7a0deec29710df4bc868d1c50845e6fc533f9
47,162
from .PlanheatMappingPlugin import PlanheatMappingPlugin def classFactory(iface): # pylint: disable=invalid-name """Load PlanheatMappingPlugin class from file PlanheatMappingPlugin. :param iface: A QGIS interface instance. :type iface: QgsInterface """ # return PlanheatMappingPlugin(iface)
c048ea0cc82c4571dbe9459a237fe8733b666da7
47,163
def plot_marker_3d(x, y, z, max_size=0.75, min_size=0.05, marker_type='scatter', num_lines=8, ax=None, **kwargs): """Pseudo-3D scatter plot using marker size to indicate height. This plots markers at given ``(x, y)`` positions, with marker size determined by *z* values. This is an alternative to :func:`mat...
895aa1a78ba0229d33bf65deac35102bf5f75d81
47,164
def is_record(obj): """Check whether ``obj`` is a "record" -- that is, a (text, metadata) 2-tuple.""" if ( isinstance(obj, (tuple, list)) and len(obj) == 2 and isinstance(obj[0], compat.unicode_) and isinstance(obj[1], dict) ): return True else: return Fal...
e95b7e885afb3594b688c90d1d46fc4ce1e326c8
47,165
import re def get_used_by_from_comments(lines: "list[str]") -> "tuple[int, list[str]]": """Read the module-used-by block comment from a module file. Args: lines (list[str]): The content of the module file as a list of strings. Returns: tuple[int, list[str]]: The integer indicates the las...
6ac30266524373d0de7cf7bb9ad9fd8dcd1933a2
47,166
def text_to_layer(block, unit, return_sequences=False): """Build tensorflow layer, easily.""" layer = None if block == "CNN": layer = tf.keras.layers.Conv1D(unit, kernel_size=1, strides=1, padding='same', activation='relu') elif block == "LCNN": layer = tf.keras.layers.LocallyConnected1D...
6ad7fb22ce222c6011e05beb9b6120ba43bd2abf
47,167
from pathlib import Path def construct_target_path(participant_name, model_name, roi): """Construct path to save results to.""" project_root = Path(__file__).parents[1] return project_root / "results" / participant_name / f"model_{model_name}"\ / f"roi_{roi}"
072681647a3362563829c25d4890aa13425cff2c
47,168
import codecs def txidFromBroadcast (hexStr): """Extracts the hex txid from a broadcast in hex.""" # The prevout txid is the first part of the broadcast data # in serialised form. But we need to reverse the bytes. hexRev = hexStr[:64] bytesRev = codecs.decode (hexRev, "hex") return bytesRev[::-1].hex ...
96690f4fdef5f0cff857188045696e427914b887
47,169
def _tm_range_from_secs(start, dur, rate=25.0): """ Return a TimeRange for the given timestamp and duration (in seconds). """ return otio.opentime.TimeRange( _rat_tm_from_secs(start), _rat_tm_from_secs(dur))
9c68f34f5456252d4062c5bccfb82b3fc6f17537
47,170
def is_known_scalar(value): """ Return True if value is a type we expect in a dataframe """ def _is_datetime_or_timedelta(value): # Using pandas.Series helps catch python, numpy and pandas # versions of these types return pd.Series(value).dtype.kind in ('M', 'm') return not ...
231035c6c8282a4b2c632112e74fee6194660a78
47,171
def get_model_results(ldamodel, corpus, dictionary): """ Create doc-topic probabilities table and visualization for the LDA model """ vis = pyLDAvis.gensim.prepare(ldamodel, corpus, dictionary, sort_topics=False) transformed = ldamodel.get_document_topics(corpus) df = pd.DataFrame.from_records([{...
db622cdefa51337985c0b3dba9987d0be3b6f704
47,172
from django.conf import settings def i18n(request): """ Set client language preference, lasts for one month """ next = request.META.get('HTTP_REFERER', settings.SITE_ROOT) lang = request.GET.get('lang', settings.LANGUAGE_CODE) if lang not in [e[0] for e in settings.LANGUAGES]: # lang...
e9f2e1cc69a81e1766abfaae7efc4463e1103273
47,173
from typing import Optional def repr_errors(res, estimator=None, method: Optional[str] = None) -> str: """Pretty print original docstring and the obtained errors Parameters ---------- res : dict result of numpydoc.validate.validate estimator : {estimator, None} estimator object or...
fd24899717b209ee1419a7c46f006587a0b8323e
47,174
from hstore_flattenfields.db import fields def get_modelfield(typo): """ >>> get_modelfield('Input') <class 'hstore_flattenfields.db.fields.HstoreCharField'> >>> get_modelfield('Integer') <class 'hstore_flattenfields.db.fields.HstoreIntegerField'> >>> get_modelfield('Random') <class 'hstor...
a41e79d6f297f5da4d21e1e0645713afeff9415f
47,175
def thread_get_messages(service, thread): """Get the list of messages in a given thread. Args: service: gmail api service object. thread: thread from which to get the messages. Returns: list of messages objects (minimal format: only id and label). """ _Context.set('Thread {}: retrieving l...
da356d3e4b5dcfe9330002eb54b32b57b62e1990
47,176
from typing import Tuple def cc_cyclic(amp: Tuple[int, int] = (10, 15), freq: Tuple[int, int] = (10, 15)) -> DeltaGenerator: """ Creates a cyclic shape control chart sequence Parameters ---------- amp: Tuple. Defaults to (10,15) Chooses randomly a number between the tuple values as am...
d53062923ab9a7231dfc5fbec64df08104588618
47,177
def predict(X, y, parameters): """ This function is used to predict the results of a L-layer neural network. Arguments: X -- data set of examples you would like to label parameters -- parameters of the trained model Returns: p -- predictions for the given dataset X """ ...
e4d374577c2fe0499bc5233a843290e59512dad9
47,179
def build_log_src_prior(prior_type, xs, ys): """ Construct a log-probability distribution from a prior type specifier. Units are probability per area. """ shape = (len(xs), len(ys)) dx = np.mean(np.diff(xs)) dy = np.mean(np.diff(ys)) if prior_type == 'uniform': log_p_unnormaliz...
394b700779f1936d92189a2c9d39c0805043c079
47,180
def query_lat_long_with_fallback(address): """ Make a query for latlong from address with fallback mechanism. The method will first attempt to query latlong from Google geocoding service for it's higher precision. If the server cannot connect to the Google service or a timeout happens, the server tries to ...
5caa21c13fb3061c36aab7171eb88acbeee4d64e
47,181
def GEV_mean(mu, sigma, xi): """Calculate the mean of a GEV distribution. The arguments mu, sigma, and xi are the location, scale, and shape parameter of the GEV distribution, respectively. """ if xi >= 1: return np.inf elif xi == 0: return mu + sigma * np.euler_gamma else: ...
82b7e9137bb3365a1c661059b4de3356fb05f97b
47,182
import tqdm def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng, aa_features, do_hydro, do_charge, do_pks, do_solubility, ...
3980b1aafb550ee0d4999e9f968fbbbff29c981e
47,183
import re def delete_dup_greater_than(text): """Processes html text deleting duplicated '>' generated after previous processing steps. Args: text (string): html text that is going to be processed. Returns: string: text once it's processed. """ p1 = re.compile(r'(<br>)(>)(</)', re.UNICODE) processed_text...
dd4383047c17addd9d32dd8d3e6d5f9d35911dd2
47,184
def svc_model_adjustment_optimization_score(X_train,X_test,y_train,y_test): """ 支持向量机 Support Vector Machine """ svc_params = {'C': [0.5, 0.7, 0.9, 1], 'kernel': ['rbf', 'poly', 'sigmoid', 'linear']} return model_adjustment_optimization(SVC(),'Support Vector Machine',svc_params,X_train,X_test,y_trai...
188a76d35452f765a158479768f9ba23ea221577
47,185
def msg_handle_KOR(string)->list: """Sort for data, double check with isit_covid""" isit_covid = False day = 0 #(0: default, 1: 오늘, 2:어제, 3:그저께) my_list = split_string(string) print(string) #0 기본 언어 : 코로나, 확진자, 몇, 명 if check_item(my_list, '코로나'): if check_item(my_list, '명') or check_...
f2e5bf3f579203d115e1e571d82a980e7912b1f1
47,186
import difflib import re from typing import Any import json def activity_diff(context: Context, data_dict: DataDict) -> dict[str, Any]: """Returns a diff of the activity, compared to the previous version of the object :param id: the id of the activity :type id: string :param object_type: 'package...
286bcd88b8adbd2ab2ec2d44e3e524f97aa8cd71
47,187
def property_graph(graph='g1'): """ Define the properties of the graph to generate :graph : type of desired graph. Options : ['g1','g2', 'g3', 'g4', 'g5'] """ if graph == 'g1': method = 'partition' sizes = [75, 75] probs = [[0.10, 0.005], [0.005, 0.10]] number_class =...
57aa301801213f4b88e9b2c77b3bf44c372b09ee
47,188
import re def readxtalkcoeff(xtalkfile): """read crosstalk coefficent file""" xdict = {} try: xfile = open(xtalkfile,'r') for line in xfile: if (len(line.strip()) > 0 and line[0] != '#'): line = line.rstrip('\r\n') line = line.rstrip() ...
759e9264b605256580bf4c3dd59859d50524f195
47,189
import copy import warnings from re import U def radec2altaz(radec, location, obstime=None, epoch_RA=2000.0, time_type=None): """ ---------------------------------------------------------------------------- Convert RA-Dec to Alt-Az with accurate ephemeris Inputs: radec [numpy array] Altitude ...
b4e1dff708e78adf90937d0c886cd7347f7b71ae
47,190
def filter_properties(person, PERSON_PROPERTIES): """ Extract specific properties of the given person into a new dictionary. Parameters: person (dict): the dictionary containing properties of a person. PERSON_PROPERTIES (tupl): a tuple containing the characteristics of a person Returns...
2a3ec4ab32c5d99d475ebffaefe0d8c40ce137af
47,192
def landsat8_spectral_indices(img): """ Function that computes several spectral indices for Landsat 8 sensor. The indices specifically focus in detecting vegetation phenology, and water and salt content in the soil. The indices are added to the input image as bands. The function can be used either w...
2392382e6c6f1bbb222c2a7e42c77d1a654ea9b5
47,195
def rphiz_to_xyz(values): """Converts axis values from cylindrical coordinates into cartesian coordinates Parameters ---------- values: array Values of the axis to convert (Nx3) Returns ------- ndarray of the axis (Nx3) """ r = values[:, 0] phi = values[:, 1] if len...
1b9c7ff031bec97b588844da9a7498f2dd79a85c
47,196
def invert(image): """Invert the given image. :param image: image :returns: inverted image """ assert np.amin(image) >= -1e-6 assert np.amax(image) <= 1+1e-6 return 1.0 - np.clip(image, 0, 1.0)
4b9237fb1e2c76eaab08a4b7632165ede5951a7f
47,199
def PublicObject_IsRegistrationEnabled(): """PublicObject_IsRegistrationEnabled() -> bool""" return _DataModel.PublicObject_IsRegistrationEnabled()
c493cd141375938a5c78f9ff780a46ac7dd0ba16
47,200
def element_triple_cross(A, B, C): """Return element-wise triple cross product of three 3D arr in Cartesian""" return ( B * (element_dot(A, C))[:, :, np.newaxis] - C * (element_dot(A, B))[:, :, np.newaxis] )
a66d2a264bf6e6d5035096ada8d745ca1a983a82
47,201
import random def dict_sample(d, cutoff=-1): """ Sample a key from a dictionary using the values as probabilities (unnormalized) """ if cutoff==-1: cutoff = random() normalizer = float(sum(d.values())) current = 0 for i in d: assert(d[i] > 0) current += float(d[i])...
7d209b8c9ed35c3bccde5cbfdd6e2720e7e8fc78
47,203
def new_options(lights: list[int], exclude: list[int]) -> dict: """Create a standard options object.""" return {CONF_LIGHTS: lights, CONF_EXCLUDE: exclude}
e42c90463e3f3bf66034b32e64056ab8ec066ffa
47,204
from typing import List from typing import Optional def from_list(leaves: List[hash.Hash]) -> Optional[MerkleTree]: """Create Merkle tree from one or more nodes.""" if not leaves: return None head, tail = leaves[0], leaves[1:] t = from_singleton(head) for leaf in tail: t.insert(le...
874071d7d578e4de74e24402cc90e1791469f0ef
47,206
def get_instance_availability_zone(context, instance): """Return availability zone of specified instance.""" host = instance.host if 'host' in instance else None if not host: # Likely hasn't reached a viable compute node yet so give back the # desired availability_zone in the instance record...
82c194a192b899dfd0c20067539a83b894cd0519
47,207
import json from datetime import datetime def start_collector(): """Endpoint for starting the collector. Route command to CollectorHandler object.""" run_id = None try: data = request.get_json() start_delta = data['start'] stop_delta = data['stop'] interval = data['interva...
363e9e0b5577909a773732b1b48536240198b247
47,208
from typing import Sequence def _distribute_conversion_values( data_consent: pd.DataFrame, conversion_column: str, non_consent_conversion_values: Sequence[float], weighted_conversion_values: Sequence[np.ndarray], neighbors_index: Sequence[np.ndarray], neighbors_distance: Sequence[np.ndarray], ...
27422ae951c88a0f9d60a1e6ba389d74eeb289ca
47,209
def _get_default_frame(instance, shared_tags): """Extracts a metadata from volumetric enhanced instance, drops heavy tags.""" delete_tags(instance, EXCLUDE_TAGS.keys()) for tag in shared_tags: instance.add(tag) return instance
55a4cf9b81fffe46577862af9f4db17fce6b177e
47,210
import stat def download_sst(path, url): """" Download from `url` the zip file corresponding to the Stanford Sentiment Treebank and expand the resulting files into the directory `path` (Note: if the files are already present, the download is not actually run). Arguments --------- ...
7378136402cbb2219f718f8aeeafcd3dc086a139
47,211
def load_csv_to_numpy(dir: str): """ Module to load csv files. Args: dir: """ csv = np.genfromtxt(dir, delimiter=',') csv = csv[1:len(csv), 2:5].astype('uint16') return csv
9b2053066f5d311dd6a8a51b867326d922025fdf
47,212
def comp_cc(x1, x2, maxTimeLag, binSize, numBin): """Compute cross- or auto-correlation from binned data (without normalization). Uses matrix computations to speed up, preferred when multiple processors are available. Parameters ----------- x1, x2 : nd array time-series from binned data (nu...
eb6a6c709270eb628a02ab4f3fea8d4563fa7954
47,213
import tqdm def export_to_obj_file3D(polys, fname=None, scale=1, single_mesh=True, uv_map=False, name="poly"): """ exports 3D mesh result to obj file format """ try: dist = polys["dist"] points = polys["points"] rays_vertices = polys["rays_vertices"] rays_faces = polys["rays_f...
b639353624a677674b367392358ed0db3e73fefb
47,214
def get_objects_from_canvas_by_type(canvas, typename): """ Read objects in canvas and filter by typename :param canvas: canvas :type canvas: TCanvas :param typename: type of object to be filtered :type typename: str :return: objects of type typename in canvas :rtype: list[typename] "...
f0c0ae8813299ce7c337e9fab30adda2b360aa85
47,215
def get_chain_hash(contract, s, u_i, s_i, a, b, bytes_30, dyn_bytes, bar_uint, arr) -> bytes: """Uses the contract to create and hash a Foo struct with the given parameters.""" result = contract.functions.hashFooStructFromParams(s, u_i, s_i, a, b, bytes_30, dyn_bytes, bar_uint, arr).call() return result
2faeb03eff5ee1a4e564a50f8bff78fb99cdd169
47,216
def cluster_script(amoptd, python_path="ccp4-python"): """Create the script for ensembling on a cluster Parameters ---------- amoptd : dict An AMPLE option dictionary python_path : str, optional The path to the CCP4 python executable Returns ------- str The path to...
56a40a31f79ab12478c22542837d9606d29022d2
47,218
def build_hooks(model_configs, distributed_mode=False, is_chief=True): """ Builds training hooks. Args: model_configs: A dictionary of all configurations. distributed_mode: Whether is running under a distributed setting. is_chief: Whether this is the chief process. Returns: A list ...
916f84e9b02f9b22618ec55cbd7cf6e9beb46582
47,219
def attribute_vertex_perimeter(graph, edge_length=None): """ Vertex perimeter of the given graph. The perimeter of a vertex is defined as the sum of the length of out-edges of the vertex. If the input graph has an attribute value `no_border_vertex_out_degree`, then each vertex perimeter is assumed to b...
f8b0b9f3cfb4e060d48c1d6291ab75898f2b2af8
47,220
def get_status(dev, recipient, index = 0): """ Get status of the recipient Args: dev - pyusb device recipient - CTRL_RECIPIENT_DEVICE/CTRL_RECIPIENT_INTERFACE/CTRL_RECIPIENT_ENDPOINT index - 0 if recipient is device, interface index if recipient is interface, endpoint index if recipient...
5f05c9235bd180de5528fcfaf64e84087fdf19cd
47,221
from typing import Optional def map_ttf_to_shx(ttf: str) -> Optional[str]: """Map TTF file names to SHX font names. e.g. "txt_____.ttf" -> "TXT" """ return TTF_TO_SHX.get(ttf.lower())
cbb482f6f140c6022e64b358986fa0276be3027b
47,222
from typing import Collection def edit_beatmap_comment(request, collection_id, beatmap_entry_id): """View for edit beatmap comment in BeatmapEntry""" collection = get_object_or_404(Collection, id=collection_id) beatmap_entry = get_object_or_404(BeatmapEntry, id=beatmap_entry_id, collection=collection) ...
2d1fd8fc1310304aa17d51823ba5c9071679a282
47,224
def oct2text(oct_text): """ Takes in a string oct_text, returns the decoded plain text.""" #Raise exception if there are no spaces in the text if not " " in oct_text and len(oct_text)>3: raise ValueError(noSpaceError.format("oct_text")) oct_text = oct_text.strip() #Converts the oct to text plain_string = ''...
985590fa863bdc7ef648246e150714f2b7d9adef
47,226
def tanh(z): """Hyperbolic tangent function... Args: z (np.array) Returns: f(z) = 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0 (np.array) """ return 2.0 / (1.0 + np.exp(-2.0 * z)) - 1.0
a87b9a4b04500b0eb1f2ead3ff8fa68977530c7d
47,227
def graph_search_for_vis(problem): """Search through the successors of a problem to find a goal. The argument frontier should be an empty queue. If two paths reach a state, only use the first one.""" # we use these two variables at the time of visualisations iterations = 0 all_node_colors = [] ...
ad09cd644d7c8661069768dfbd928f7b98ee0d03
47,230
def api_runs(resource_id, run_id=None, content_type='json'): """ Get Runs (History of results) for Resource. """ if run_id: runs = [views.get_run_by_id(run_id)] else: runs = views.get_run_by_resource_id(resource_id) run_arr = [] for run in runs: run_dict = { ...
d6311528c3f9bbf82042313659d1e4776a3fc8da
47,231
def export_document_to_mstr(connection, document_id, instance_id, body, error_msg=None): """Export a specific document in a specific project to an .mstr file. Args: connection: MicroStrategy REST API connection object document_id (string): Document ID instanc...
0ec41f48022d7f5044b91dfa5fba8bafef1df0c7
47,232
def generate(row): """Get china: country, province, city. :param str row: The result of row parsed from qqwry :return: A tuple. """ candicates = Province.china for (cn, province) in candicates: if province in row: _, city = row.split(province) return cn, provi...
878eb7beca9eaa1f888a5fc0f3b0afa01a94c094
47,234
import signal def freqz_cas(sos,w): """ Cascade frequency response Mark Wickert October 2016 """ Ns,Mcol = sos.shape w,Hcas = signal.freqz(sos[0,:3],sos[0,3:],w) for k in range(1,Ns): w,Htemp = signal.freqz(sos[k,:3],sos[k,3:],w) Hcas *= Htemp return w, Hcas
1565a569d4d1e177eb49aa44673ac539062857dc
47,235
def import_dotted_path(path): """ Takes a dotted path to a member name in a module, and returns the member after importing it. """ # stolen from Mezzanine (mezzanine.utils.importing.import_dotted_path) try: module_path, member_name = path.rsplit(".", 1) module = import_module(mod...
677fc7095364bede668ea134997099ac02088823
47,236
import binascii def sdm_info(): """ SUN decrypting/validating endpoint. """ enc_picc_data = request.args.get(ENC_PICC_DATA_PARAM) enc_file_data = request.args.get(ENC_FILE_DATA_PARAM) sdmmac = request.args.get(SDMMAC_PARAM) if not enc_picc_data or not sdmmac: raise BadRequest("Par...
11b58fa8da785f5a0ccb392f2dd17b222d4a0066
47,238
import types def get_module_functions(module): """ Helper function to get the functions of an imported module as a dictionary. Args: module: python module Returns: dict: module functions mapping { "func1_name": func1, "func2_name": func2,... }...
d784e7d2d085c5f4f015a6107f9106653fe163ef
47,239