content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def failed_jobs(username, root_wf_id, wf_id): """ Get a list of all failed jobs of the latest instance for a given workflow. """ dashboard = Dashboard(g.master_db_url, root_wf_id, wf_id) args = __get_datatables_args() total_count, filtered_count, failed_jobs_list = dashboard.get_failed_jobs( ...
5d755f6e84f7c406174fb1a7bdb8de64a6e0c049
3,200
def get_vm_types(resources): """ Get all vm_types for a list of heat resources, do note that some of the values retrieved may be invalid """ vm_types = [] for v in resources.values(): vm_types.extend(list(get_vm_types_for_resource(v))) return set(vm_types)
f13e8860d5b25cd03360e859527d61a06d103f53
3,201
import os def list_files(directory, suffix='.nc'): """ Return a list of all the files with the specified suffix in the submission directory structure and sub-directories. :param str directory: The root directory of the submission :param str suffix: The suffix of the files of interest :returns...
ba9a00ba749930120cfa3677771a24181bf58685
3,202
def interface_names(obj): """ Return: a list of interface names to which `obj' is conformant. The list begins with `obj' itself if it is an interface. Names are returned in depth-first order, left to right. """ return [o.__name__ for o in interfaces(obj)]
99aad05e14daeb13ed7f19599684acc8b324df84
3,203
import six def add_basic(token): """For use with Authorization headers, add "Basic ".""" if token: return (u"Basic " if isinstance(token, six.text_type) else b"Basic ") + token else: return token
cd579e77e243fdfba0853a87087e45cf58bcc6f2
3,204
import json import requests def updateUser(token, leaderboard=None, showUsername=None, username=None): """ Update user account information. Parameters- token: Authentication token. leaderboard: True to show user's profit on leaderboard. showUsername: True to show the username on LN Marktes pu...
9b953256b85327411445729b574cf9b79750e735
3,205
def init_validator(required, cls, *additional_validators): """ Create an attrs validator based on the cls provided and required setting. :param bool required: whether the field is required in a given model. :param cls: the expected class type of object value. :return: attrs validator chained correct...
924b5ff6e77d38c989eef187498f774a2322ed48
3,206
import requests def next_search(request, *args, **kwargs): """ Handle search requests :param request: :return: """ server = FhirServerUrl() in_fmt = "json" get_fmt = get_format(request.GET) if settings.DEBUG: print("Server:", server) print("Kwargs:",kwargs) c...
47316d3a127a0c31dfb8ce10b0f8c4465bdfd8ba
3,207
def ShiftRight(x, **unused_kwargs): """Layer to shift the tensor to the right by padding on axis 1.""" if not isinstance(x, (list, tuple)): # non-chunked inputs pad_widths = [(0, 0)] * len(x.shape) pad_widths[1] = (1, 0) # Padding on axis=1 padded = np.pad(x, pad_widths, mode='constant') return pa...
ec5265b5937e3e90e2c3267b6501b008ac7090e5
3,208
import os def connect_kafka_producer(): """Return a MSK client to publish the streaming messages.""" # Use a global variable so Lambda can reuse the persisted client on future invocations global kafka_client if kafka_client is None: logger.debug('Creating new Kafka client.') try:...
c0dc1c98881dd6452fdf8359aec11f3e6cf8b71a
3,209
def empty_record(): """Create an empty record.""" record = dump_empty(Marc21RecordSchema) record["metadata"] = "<record> <leader>00000nam a2200000zca4500</leader></record>" record["is_published"] = False record["files"] = {"enabled": True} return record
7797e1bf0ade98a2400daff1f7937b7af2da280d
3,210
def illuminanceToPhotonPixelRate(illuminance, objective_numerical_aperture=1.0, illumination_wavelength=0.55e-6, camera_pixel_size=6.5e-6, objective_magnification=1, ...
cbbb2f6bdce7592f997b7ab3784c15beb2b846b1
3,211
def stop_tuning(step): """ stop tuning the current step method """ if hasattr(step, 'tune'): step.tune = False elif hasattr(step, 'methods'): step.methods = [stop_tuning(s) for s in step.methods] return step
45e02b8d3ec86ceda97de69bbc730aa62affb06d
3,212
import json def assemble_english(): """Assemble each statement into """ if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) stmts_json = body.get('statements') stmts = stmts_from_json(stmts_json) sentences = {} fo...
24c267e2763198056e275feda1e81ef1bf280bdb
3,213
def schema_class(classname, schema, schemarepr=None, basename='SchemaBase'): """Generate code for a schema class Parameters ---------- classname : string The name of the class to generate schema : dict The dictionary defining the schema class basename : string (default: "SchemaB...
2f497de54205e5c180805d77638c9ffe342f76c8
3,214
import requests def orthology_events(ids='R-HSA-6799198,R-HSA-168256,R-HSA-168249', species='49633'): """ Reactome uses the set of manually curated human reactions to computationally infer reactions in twenty evolutionarily divergent eukaryotic species for which high-quality whole-genome sequence data...
8a75e2bc9af34358164492d1d2b2d8154d4e696e
3,215
def judge(name): """ Return some sort of score for automatically ranking names based on all the features we can extract so far. I guess we'll just add the scores * weights up for now. """ score = 0 for scoreID, scorer, weight in weights: subscore = scorer(name) score += subs...
34811f49fc8fe6c88ef31978702cacddbacd5314
3,216
import re def parse_year(inp, option='raise'): """ Attempt to parse a year out of a string. Parameters ---------- inp : str String from which year is to be parsed option : str Return option: - "bool" will return True if year is found, else False. - Return yea...
a91efb0614e7d0ad6753118f9b4efe8c3b40b4e2
3,217
def retry_import(e, **kwargs): """ When an exception occurs during channel/content import, if * there is an Internet connection error or timeout error, or HTTPError where the error code is one of the RETRY_STATUS_CODE, return return True to retry the file transfer * the file ...
b125841dff7154352b2031013ffa7058242e4974
3,218
def cvCloneMat(*args): """cvCloneMat(CvMat mat) -> CvMat""" return _cv.cvCloneMat(*args)
84dc4f59d29580477b7ded41f26d95011b2804b3
3,219
from typing import Callable import time def run_episode(kwargs) -> [Trajectory]: """ Runs a single episode and collects the trajectories of each agent """ total_controller_time = 0 env_dict: Callable = kwargs.get("env_dict") obs_builder = kwargs.get("obs_builder") controller_creator: Calla...
91b64a8df57e1fc47ffecc184b0473d633b545c4
3,220
async def _reverse_proxy_handler(request: web.Request) -> web.Response: """ - Adds auth layer - Adds access layer - Forwards request to catalog service SEE https://gist.github.com/barrachri/32f865c4705f27e75d3b8530180589fb """ user_id = request[RQT_USERID_KEY] # path & quer...
f26a4410ab43dd9d3c12f3490f6dfb9fb2da234a
3,221
def get_data(request: Request): """ Get the data page. Parameters ---------- request : Request The request object. Returns ------- HTMLResponse The data page. """ return templates.TemplateResponse("data.html", {"request": request})
4a44df5122f9db9009a769d4d9bec99d924fb0f7
3,222
def remove_last_measurements(dag_circuit, perform_remove=True): """Removes all measurements that occur as the last operation on a given qubit for a DAG circuit. Measurements that are followed by additional gates are untouched. This operation is done in-place on the input DAG circuit if perform_pop=Tru...
858a16c33de67f835cf32535f2e69f9c144d6e25
3,223
import urllib3 import certifi import sys def get_html(url): """ Given a URL, will return the HTML using urllib3. :param url: The url to extract the HTML from :return: If extracted successfully, the HTML is returned. If there is a failure, a message with HTTP status. If an exception is thrown, -1 is r...
031a444d28674593b9e6994b6ddcae7dd2c4b8cd
3,224
def J(*args, **kwargs): """Wrapper around jsonify that sets the Content-Type of the response to application/vnd.api+json. """ response = jsonify(*args, **kwargs) response.mimetype = "application/vnd.api+json" return response
714537b180cab60b7ad614018fa551020aeee292
3,225
import os import sys def readable_dir(prospective_dir): """ check if dir is exist or acessable""" if not os.path.isdir(prospective_dir): sys.exit("{} is not a valid path".format(prospective_dir)) if os.access(prospective_dir, os.R_OK): return prospective_dir else: sys.exit("{}...
8c8ea6928605baa3dfb224c258102b2d263932cd
3,226
def is_gzipped(filename): """ Returns True if the target filename looks like a GZIP'd file. """ with open(filename, 'rb') as fh: return fh.read(2) == b'\x1f\x8b'
b1afb5b9cddc91fbc304392171f04f4b018fa929
3,227
import os def load_data(loc='./data/'): """ Load the SICK semantic-relatedness dataset """ trainA, trainB, devA, devB, testA, testB = [],[],[],[],[],[] trainS, devS, testS = [],[],[] with open(os.path.join(loc, 'sick_train.txt'), 'r') as f: for line in f: text = line.strip...
58c15084e3874fa0cdda4cce3b701b18a2529634
3,228
def tag_helper(tag, items, locked=True, remove=False): """ Simple tag helper for editing a object. """ if not isinstance(items, list): items = [items] data = {} if not remove: for i, item in enumerate(items): tagname = '%s[%s].tag.tag' % (tag, i) data[tagname] = i...
27500df099824fff1d93afbe7649d42141ffa9c1
3,229
def get_keys_from_file(csv): """Extract the credentials from a csv file.""" lines = tuple(open(csv, 'r')) creds = lines[1] access = creds.split(',')[2] secret = creds.split(',')[3] return access, secret
eccf56c52dd82656bf85fef618133f86fd9276e6
3,230
import pkg_resources import json def fix_model(project, models, invert=False): """Fix model name where file attribute is different from values accepted by facets >>> fix_model('CMIP5', ['CESM1(BGC)', 'CESM1-BGC']) ['CESM1(BGC)', 'CESM1(BGC)'] >>> fix_model('CMIP5', ['CESM1(BGC)', 'CESM1-BGC'], inver...
b1e91ba7305a75ed376948d92607b1ab97bc93f2
3,231
from re import X def rectified_linear_unit(x): """ Returns the ReLU of x, or the maximum between 0 and x.""" # TODO return np.maximum(0, X)
0cf0057d771a69e01a7c9de94f94544359ee6489
3,232
import os def create_save_directory(path, directory_name): """ This function makes the directory to save the data. Parameters ---------- path : string Where the the directory_name will be. directory_name : string The directory name where the plots will be save Returns ...
3f449935bd5e3e72fdffd9c31968d8dcef615b0d
3,233
import os def encode_to_filename(folder, animal, session, ftypes="processed_all"): """ :param folder: str folder for data storage :param animal: str animal name: e.g. A2A-15B-B_RT :param session: str session name: e.g. p151_session1_FP_RH :param ftype: list or s...
8c976f0522fd3a485f81b9f778c91248f71e9b04
3,234
from typing import Union from typing import List from typing import Tuple def _get_choices(choices: Union[str, List]) -> List[Tuple[str, str]]: """Returns list of choices, used for the ChoiceFields""" result = [('', '')] if isinstance(choices, str): result.append((choices, choices)) else: ...
249a068571b0ddca858cd8dcc4f2f7af25689b9d
3,235
def invalid_file(): """Create an invalid filename string.""" return "/tmp/INVALID.FILE"
9a249f3ef9445cb78bc962e46ef524360bb44bdb
3,236
def get_model(app_label, model_name): """ Fetches a Django model using the app registery. All other methods to acces models might raise an exception about registery not being ready yet. This doesn't require that an app with the given app label exists, which makes it safe to call when the regis...
dd3ba70f2220ba09d256ae58b418cd3401f129e6
3,237
def affaires_view(request): """ Return all affaires """ # Check connected if not check_connected(request): raise exc.HTTPForbidden() query = request.dbsession.query(VAffaire).order_by(VAffaire.id.desc()).all() return Utils.serialize_many(query)
c44e703680034230121c426e7496746355b8ee4b
3,238
from typing import Union def metric_try_to_float(s: str) -> Union[float, str]: """ Try to convert input string to float value. Return float value on success or input value on failure. """ v = s try: if "%" in v: v = v[:-1] return float(v) except ValueError: ...
6b0121469d35bc6af04d4808721c3ee06955d02e
3,239
import os import logging def calculate_boot_time(pngs_dir, fps, refer_end_pic): """ 通过一系列的截图文件,计算出启动时间 :param pngs_dir: 截图所在目录 :param fps: 帧数 :param refer_end_pic: 结束位置参考图片 :return: 启动时间 """ # 找启动的开始(点击响应)、结束时间(渲染首页内容)点 pngs = os.listdir(pngs_dir) pngs.sort() start_t, end_t...
ef1d370ad024450956f400f9ee4747b159a6ad01
3,240
def _table_difference(left: TableExpr, right: TableExpr): """ Form the table set difference of two table expressions having identical schemas. A set difference returns only the rows present in the left table that are not present in the right table Parameters ---------- left : TableExpr ...
aae66ddb29d30a0bc95750d62ce87c16773d3d63
3,241
def select(receivers, senders, exceptions, timeout): """ receivers - list of one element, the simulated receiver socket senders - list of one element, the simulated sender socket exceptions - empty list, the simulated sockets with exceptions ignore timeout - there is no real concurrency here """...
4fd94593521c0e0626b574922286b2b374707fce
3,242
def parse_args(): """ It parses the command-line arguments. Parameters ---------- args : list[str] List of command-line arguments to parse Returns ------- parsed_args : argparse.Namespace It contains the command-line arguments that are supplied by the user """ par...
7849b9a1422e959be9e5b2504dc7d42c2475572d
3,243
def parse_row(row, entity_dict, span_capture_list, previous_entity): """ updates the entity dict and span capture list based on row contents """ bio_tag, entity = parse_tag(row.tag) if bio_tag == 'B': # update with previous entity, if applicable entity_dict, span_capture_list, pre...
a7d49b6e4dbe747c65688c01652f1d413314b407
3,244
def _is_fn_init( tokens: list[Token] | Token, errors_handler: ErrorsHandler, path: str, namehandler: NameHandler, i: int = 0 ): """ "fn" <fn-name> "("<arg>*")" (":" <returned-type>)? <code-body>""" tokens = extract_tokens_with_code_body(tokens, i) if tokens is None ...
2e65dbe9e7976f7e13215fbf04bd40f08da7e16e
3,245
import asyncio from typing import cast async def http_connect(address: str, port: int) -> HttpConnection: """Open connection to a remote host.""" loop = asyncio.get_event_loop() _, connection = await loop.create_connection(HttpConnection, address, port) return cast(HttpConnection, connection)
2d98815b17f6d0e03763b643a052737f6931a33f
3,246
def make_parallel_transformer_config() -> t5_architecture.EncoderDecoder: """Returns an EncoderDecoder with parallel=True.""" dtype = jnp.bfloat16 num_attn_heads = 8 make_dropout = lambda: nn.Dropout(rate=0.1, broadcast_dims=(-2,)) make_layer_norm = layer_norm.T5LayerNorm def _make_encoder_layer(shared_rel...
f61c02d66075fb71fbecd58e8c369a6ba406c15f
3,247
def get_device_mapping(embedding_sizes, num_gpus, data_parallel_bottom_mlp, experimental_columnwise_split, num_numerical_features): """Get device mappings for hybrid parallelism Bottom MLP running on device 0. Embeddings will be distributed across among all the devices. Optimal solu...
2265831d87d8f48c4b87ca020c7f56293cb62647
3,248
def _generate_relative_positions_embeddings(length, depth, max_relative_position, name): """Generates tensor of size [length, length, depth].""" with tf.variable_scope(name): relative_positions_matrix = _generate_relative_positions_matrix( length, max_relative...
7c69705cf5cc161144181b09a377f66d863b12ae
3,249
def continTapDetector( fs: int, x=[], y=[], z=[], side='right', ): """ Detect the moments of finger-raising and -lowering during a fingertapping task. Function detects the axis with most variation and then first detects several large/small pos/neg peaks, then the function determines sample-w...
742a7f5590e8ad76e521efe5d1c293c43d71de0b
3,250
def parallelize(df, func): """ Split data into max core partitions and execute func in parallel. https://www.machinelearningplus.com/python/parallel-processing-python/ Parameters ---------- df : pandas Dataframe func : any functions Returns ------- data : pandas Dataframe R...
dc9c085ada6ffa26675bd9c4a218cc06807f9511
3,251
def get_functional_groups(alkoxy_mol): """ given a molecule object `alkoxy_mol`. This method returns a dictionary of groups used in the Vereecken SAR with the key being the group and the value being the number of occurances it has. """ #print 'getting groups from {}'.format(alkoxy_mol.toSMIL...
9c0280bb09e6ef606aac2a14fe2826c0a9feb06d
3,252
def rough(material, coverage, scale, det, e0=20.0, withPoisson=True, nTraj=defaultNumTraj, dose=defaultDose, sf=True, bf=True, xtraParams=defaultXtraParams): """rough(material, coverage, scale, det, [e0=20.0], [withPoisson=True], [nTraj=defaultNumTraj], [dose = 120.0], [sf=True], [bf=True], [xtraParams={}]) Mon...
0aa6a21a2cdae22bf9f56cd6babfa9c3402ce465
3,253
def jsonify(comment_lower: str) -> str: """pyNastran: SPOINT={'id':10, 'xyz':[10.,10.,10.]}""" sline = comment_lower.split('=') rhs = sline[1].rstrip() return rhs.replace("'", '"').replace('}', ',}').replace(',,}', ',}')
e8641d5e94cff32389f7ade3360935a2abbcf297
3,254
import time def set_attributes_polling(test_case, device_proxy, device_server, poll_periods): """Set attribute polling and restore after test Parameters ---------- test_case : unittest.TestCase instance device_proxy : tango.DeviceProxy instance device_server : tango.Device instance T...
103d9dba615e0c99ac35766348f016139831c12c
3,255
from catalyst.engines.torch import ( DataParallelEngine, DeviceEngine, DistributedDataParallelEngine, ) from catalyst.engines.amp import ( AMPEngine, DataParallelAMPEngine, DistributedDataParallelAMPEngine, ) from catalyst.engines.apex import (...
6d29e0c1938c5889b6e4a7fa972945065bc2cf3a
3,256
import shutil def disk_usage(pathname): """Return disk usage statistics for the given path""" ### Return tuple with the attributes total,used,free in bytes. ### usage(total=118013599744, used=63686647808, free=48352747520) return shutil.disk_usage(pathname)
c7a36e2f3200e26a67c38d50f0a97dd015f7ccfa
3,257
import os import yaml def get_default_log_config(): """Get the default logging configuration. Returns: dict: The default logging configuration. """ root = os.path.dirname(__file__) config_file = os.path.join(root, "logging.yaml") with open(config_file, "r") as file_object: da...
7fc4479c7efb666b80ddd3e450b107ac73cf3c16
3,258
from typing import Tuple def create_new_deployment( runner: Runner, deployment_arg: str, expose: PortMapping, add_custom_nameserver: bool ) -> Tuple[str, str]: """ Create a new Deployment, return its name and Kubernetes label. """ span = runner.span() run_id = runner.session_id runner....
d15e9e1ec9d09669b8becd4e169049d5a1e836ab
3,259
import logging def score_latency( references, reference_wavs, partial_translations, target_language="en-US" ): """Measures the "final" translation lag after all corrections have been made.""" logger = logging.getLogger("evaluation") tokenizer = get_tokenizer(target_language) min_len = min(len(par...
9d31e029247e44448103d99760019f0dffa1cf44
3,260
def shapelet_with_w_term( coords, frequency, coeffs, beta, delta_lm, lm, dtype=np.complex128 ): """ shapelet: outputs visibilities corresponding to that of a shapelet Inputs: coords: coordinates in (u,v) space with shape (nrow, 3) frequency: frequency values with shape (nchan,) c...
f6c9f9011306cc2de5054e015857b3b47c7e6cd9
3,261
import numpy def CylindricalVectorsToCartesian(coordinates, data): """ Project the supplied cylindrical coordinates (r-phi-z) vectors to 3D Cartesian (x-y-z). coordinates must be in Cartesian. """ if optimise.DebuggingEnabled(): assert(len(coordinates) == len(data)) for i, coord in enumerate(coor...
abc3bd3eecd6f087dc932b882600e8779903f556
3,262
from typing import Counter def _entropy_counter2(arr): """ calculate the base 2 entropy of the distribution given in `arr` using a `Counter` and the `values` method (for python3) """ arr_len = len(arr) if arr_len == 0: return 0 log_arr_len = np.log2(len(arr)) return -sum(val * ...
1f72c7a7e5db56aa9a0e5c3811cf28c600420949
3,263
from sys import path def update_deleted_strain(_, strain_to_del): """Update ``deleted-strain`` var. This happens after a user clicks the OK btn in the confirm strain deletion modal. We also delete the files associated with the strain at this step. :param _: User clicked the OK btn :param st...
0086aa0c17910ed75f480e4a6ac0d2950d5d84dd
3,264
def get_changes_between_models(model1, model2, excludes=None): """ Return a dict of differences between two model instances """ if excludes is None: excludes = [] changes = {} for field in model1._meta.fields: if (isinstance(field, (fields.AutoField, ...
1f62afdc7818574553fa7a53eb05e766c2805edd
3,265
def get_intersect(x1, y1, x2, y2): """ Returns the point of intersection of the lines or None if lines are parallel Ex. p1=(x1,x2)... line_intersection((p1,p2), (p3,p4)) a1: [x, y] a point on the first line a2: [x, y] another point on the first line b1: [x, y] a point on the second line b2: ...
8e9ed2f2351b41658400badc7339eedc9791db8a
3,266
def removeDuplicateColumns(df): """ Removes columns that have a duplicate name. :return pd.DataFrame: """ duplicates = getDuplicates(df.columns) done = False idx = 0 df_result = df.copy() additions_dict = {} while not done: if idx >= len(df_result.columns): done = True break colu...
dc46580d221b8e4279ba73e8d97eee079e65309c
3,267
def conv_block(data, name, channels, kernel_size=(3, 3), strides=(1, 1), padding=(1, 1), epsilon=1e-5): """Helper function to construct conv-bn-relu""" # convolution + bn + relu conv = sym.conv2d(data=data, channels=channels, kernel_size=kernel_size, strid...
90464c208c12a6e9907f5a206ddd324fd92638ff
3,268
import sys def var2fa(stream, gzipped=False): """convert variant calling's .var file to fasta""" for line in stream: if gzipped: line = line.decode() if line[0]!='V': continue line = line.strip().split('\t') _1, chrom, start, end, _2, _3, ref, alt, queryname, q_start, q_end, st...
48e5c9390dc954dcf602e63152815e5af843d270
3,269
import pickle import torchvision import torch def utzappos_tensor_dset(img_size, observed, binarized, drop_infreq, cache_fn, *dset_args, transform=None, **dset_kwargs): """ Convert folder dataset to tensor dataset. """ cache_fn = UTZapposIDImageFolder.get_cache_name(cache_fn, ...
8008f8d19453884106832746a4cefb55c9813c45
3,270
def compare_versions(aStr, bStr): """ Assumes Debian version format: [epoch:]upstream_version[-debian_revision] Returns: -1 : a < b 0 : a == b 1 : a > b """ # Compare using the version class return cmp(Version(aStr), Version(bStr))
a17e333cc555b1b260cf826a5e4c29b0e291c479
3,271
import sys def alpha_034(code, end_date=None, fq="pre"): """ 公式: MEAN(CLOSE,12)/CLOSE Inputs: code: 股票池 end_date: 查询日期 Outputs: 因子的值 """ end_date = to_date_str(end_date) func_name = sys._getframe().f_code.co_name return JQDataClient.instance().get_alpha_...
1f251db49bb5cb6a0326af5cf2d07c4bbef2144a
3,272
import numbers def unscale_parameter(value: numbers.Number, petab_scale: str) -> numbers.Number: """Bring parameter from scale to linear scale. :param value: Value to scale :param petab_scale: Target scale of ``value`` :return: ``value`` on linear scale ...
f04156220e8a39c31473507a60fee3d5185bda0c
3,273
def perturb(sentence, bertmodel, num): """Generate a list of similar sentences by BERT Arguments: sentence: Sentence which needs to be perturbed bertModel: MLM model being used (BERT here) num: Number of perturbations required for a word in a sentence """ # Tokenize the sentence tokens = tokenizer.tokenize(s...
598ed7e37185de6bf2a977c226bb58677684772d
3,274
import logging def discovery_dispatch(task: TaskRequest) -> TaskResponse: """Runs appropriate discovery function based on protocol Args: task (TaskRequest): namedtuple Returns: TaskResponse[str, dict[str, str|int|bool|list]] """ task = TaskRequest(*task) proto = constant.Proto...
3fe6394cf81fdb3e25343df27479f4b4ab3033fa
3,275
def get_free_times(busy_times, begin_date, end_date): """ Gets a list of free times calculated from a list of busy times. :param busy_times: is the list of busy times in ascending order. :param begin_date: is the start of the selected time interval. :param end_date: is the end of the selected time i...
95f33c22e28e9ed7bc299ac966767a2292cf6d7b
3,276
from datetime import datetime import pytz def upstream_has_data(valid): """Does data exist upstream to even attempt a download""" utcnow = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) # NCEP should have at least 24 hours of data return (utcnow - datetime.timedelta(hours=24)) < valid
e222ca16820f2e9030170877f8e2ae4faff8d5b7
3,277
def encode_array(x, base=2, **kwds): """Encode array of integer-symbols. Parameters ---------- x : (N, k) array_like Array of integer symbols. base : int Encoding base. **kwds : Keyword arguments passed to :py:func:`numpy.ravel`. Returns ------- int ...
b16546350638967dd60812b98295ffc4c95abd4d
3,278
import itertools def str_for_model(model: Model, formatting: str = "plain", include_params: bool = True) -> str: """Make a human-readable string representation of Model, listing all random variables and their distributions, optionally including parameter values.""" all_rv = itertools.chain(model.unobserve...
89711e4fd12572339a501698c39fc8b81deca8a3
3,279
from typing import Callable from typing import Optional from typing import Union def get_device( raw_data: dict, control_data: dict, request: Callable ) -> Optional[ Union[ HomeSeerDimmableDevice, HomeSeerFanDevice, HomeSeerLockableDevice, HomeSeerStatusDevice, HomeSeer...
616c16e749fef7dc45539a7eb8bdbc9f11d3edd1
3,280
def wait(): """ Gets the New Block work unit to send to clients """ return _event.get()
d24047d92b3774c675369ee739ec697ab23f0fea
3,281
from typing import Optional def process(msd_id: str, counter: AtomicCounter) -> Optional[dict]: """ Processes the given MSD id and increments the counter. The method will find and return the artist. :param msd_id: the MSD id to process :param counter: the counter to increment :return: the dictionary cont...
6bd93bf72a7ecfa6ddb41557b0550a629b9612f4
3,282
def choose_run(D, var2align, run): """Get input for the alignment. Do it by indicating a run to align to. Args: D (pd.DataFrame): DataFrame containing columns 'id', 'run', and ... var2align (str): Name of the column to align. run (whatever): The run to align to. Returns: ...
54fc84e61b3874219d473659c85bd369b367a05d
3,283
import os def keyring(homedir, monkeypatch, scope='module'): """Default keyring, using the test profile""" monkeypatch.setattr(os.path, "expanduser", lambda d: homedir) kr = S3Keyring(profile_name='test') kr.configure(ask=False) return kr
c3c5c1a77148338a4457a7a27db7e4bbfb837acf
3,284
def stack(tensor_list, axis=0): """ This function is the same as torch.stack but handles both numpy.ndarray and torch.Tensor :param tensor_list: :param axis: :return: """ if isinstance(tensor_list[0], th.Tensor): return th.stack(tensor_list, axis) else: return np.stac...
9d8e5d8fbd9f89acb40ada362d0ae8d4913df939
3,285
def alias(alias): """Select a single alias.""" return {'alias': alias}
35364346da4d7b1f6de2d7ba6e0b5721b6bef1dd
3,286
def model_creator(config): """Constructor function for the model(s) to be optimized. You will also need to provide a custom training function to specify the optimization procedure for multiple models. Args: config (dict): Configuration dictionary passed into ``PyTorchTrainer``. Returns: ...
81909a284bddd83a62c8c9adacfbe75cf46650bd
3,287
import numbers def ensure_r_vector(x): """Ensures that the input is rendered as a vector in R. It is way more complicated to define an array in R than in Python because an array in R cannot end with an comma. Examples -------- >>> ensure_r_vector("string") "c('string')" >>> ensure_r_...
14fdeb6bf73244c69d9a6ef89ba93b33aa4a66d8
3,288
from typing import Optional def open_and_prepare_avatar(image_bytes: Optional[bytes]) -> Optional[Image.Image]: """Opens the image as bytes if they exist, otherwise opens the 404 error image. then circular crops and resizes it""" if image_bytes is not None: try: with Image.open(BytesIO(ima...
f5b4543f64b15180deed3cb8e672a3e1b96956f7
3,289
def is_GammaH(x): """ Return True if x is a congruence subgroup of type GammaH. EXAMPLES:: sage: from sage.modular.arithgroup.all import is_GammaH sage: is_GammaH(GammaH(13, [2])) True sage: is_GammaH(Gamma0(6)) True sage: is_GammaH(Gamma1(6)) True ...
9cfba55901a45d4482b6926673bfb87fabc88030
3,290
def _run_with_interpreter_if_needed(fuzzer_path, args, max_time): """Execute the fuzzer script with an interpreter, or invoke it directly.""" interpreter = shell.get_interpreter(fuzzer_path) if interpreter: executable = interpreter args.insert(0, fuzzer_path) else: executable = fuzzer_path runner...
3739db213571ed00c5e026f9a768ca610e0ac318
3,291
def remove_vol(im_in, index_vol_user, todo): """ Remove specific volumes from 4D data. :param im_in: [str] input image. :param index_vol: [int] list of indices corresponding to volumes to remove :param todo: {keep, remove} what to do :return: 4d volume """ # get data data = im_in.dat...
4e5ffe6ade64f4c9dbabf5e090662711bdf926f7
3,292
def cost_logistic(p, x, y): """ Sum of absolute deviations of obs and logistic function L/(1+exp(-k(x-x0))) Parameters ---------- p : iterable of floats parameters (`len(p)=3`) `p[0]` L - Maximum of logistic function `p[1]` k - Steepness of logistic function ...
32b89ef7d33d49b7af63c8d11afffeb641b12de1
3,293
from datetime import datetime def estimate_dt(time_array): """Automatically estimate timestep in a time_array Args: time_array ([list]): List or dataframe with time entries Returns: dt ([datetime.timedelta]): Timestep in dt.timedelta format """ if len(time_array) < 2: # ...
6e6b8dcd4d2d85b4bfb97137294774bb4bcc2673
3,294
import uu def gen_uuid() -> str: """ 获取uuid :return: uuid """ return uu.uuid4().hex
82fd4fa7a3e39cc0c91ab16be3cf0c6a3f63eb3d
3,295
import inspect def make_signature(arg_names, member=False): """Make Signature object from argument name iterable or str.""" kind = inspect.Parameter.POSITIONAL_OR_KEYWORD if isinstance(arg_names, str): arg_names = map(str.strip, arg_name_list.split(',')) if member and arg_names and arg_na...
2730e50ea68e6fe2942c629caa3b3119aea9a325
3,296
def set_trace_platform(*args): """ set_trace_platform(platform) Set platform name of current trace. @param platform (C++: const char *) """ return _ida_dbg.set_trace_platform(*args)
9f581018960cdd0949ca41750286eddf1fa43741
3,297
def leapfrog2(init, tspan, a, beta, omega, h): """ Integrate the damped oscillator with damping factor a using single step Leapfrog for separable Hamiltonians. """ f = forcing(beta, omega) return sym.leapfrog(init, tspan, h, lambda x, p, t: -x-a*p+f(t))
a8eebe1ee7f50c87e515c2c5cca0bdc30605dc8f
3,298
def get_paths(config, action, dir_name): """ Returns 'from' and 'to' paths. @param config: wrapsync configuration @param action: 'push'/'pull' @param dir_name: name of the directory to append to paths from the config @return: dictionary containing 'from' and 'to' paths """ path_from = ''...
f03ee64a76bafcf832f8dddcdcb4f16c28529c5c
3,299