content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def overlap(a, b): """check if two intervals overlap. Positional arguments: a -- First interval. b -- Second interval. """ return a[1] > b[0] and a[0] < b[1]
88860f46a94eb53f1d6f636211916dd828c83550
3,645,100
import warnings import re def contAvg_headpos(condition, method='median', folder=[], summary=False): """ Calculate average transformation from dewar to head coordinates, based on the continous head position estimated from MaxFilter Parameters ---------- condition : str String contain...
42b65ce84f7b303575113ca2d57f5b61841f8294
3,645,101
from . import __path__ as path from numpy import fromfile from os.path import join from os import listdir from ..IO.output import printError def getconstantfunc(name, **kwargs): """Get constants from file by name.""" path = path[0] if not name in listdir(path): printError("File {0} not exists."....
ae5279587c9d292d4f2cb0aa9480169ee386cc99
3,645,102
def scalar_prod_logp0pw_beta_basis_npf(pw, p0, DV, alpha): """ From normalized p_fact Args: pw: a batch of probabilities (row:word, column:chi) DV: centered statistics (for p0, to be consistent) p0: the central probability on which tangent space to project (row vector) alpha...
be63a3bcd791be4ee116a1e9abbd10a455e10bfc
3,645,103
from typing import List from typing import Tuple from datetime import datetime from bs4 import BeautifulSoup def get_seminars() -> List[Tuple[str, str, datetime, str]]: """ Returns summary information for upcoming ITEE seminars, comprising seminar date, seminar title, venue, and an information link. "...
c1f149fa1625492f60b81b7c987f839c9d14abf3
3,645,104
def cluster_hierarchically(active_sites,num_clusters=7): """ Cluster the given set of ActiveSite instances using a hierarchical algorithm. Input: a list of ActiveSite instances (OPTIONAL): number of clusters (default 7) Output: a list of clusterings (each clustering is a list of lists o...
e7ca3f8a9a098630a51944ae870b1beb730684dd
3,645,105
def insert(table: _DMLTableArgument) -> Insert: """Construct an :class:`_expression.Insert` object. E.g.:: from sqlalchemy import insert stmt = ( insert(user_table). values(name='username', fullname='Full Username') ) Similar functionality is available via...
70bd0accf66e72d6240f7cd586fc47c927e109a6
3,645,106
def parallelize_window_generation_imap(passed_args, procs=None): """Produce window files, in a parallel fashion This method calls the get_win function as many times as sets of arguments specified in passed_args. starmap is used to pass the list of arguments to each invocation of get_win. The pool is cr...
74cf5c8138ad1511c9aeae62a3f14c705a3735b5
3,645,107
def build_train(q_func, ob_space, ac_space, optimizer, sess, grad_norm_clipping=None, scope="deepq", reuse=None, full_tensorboard_log=False): """ Creates the train function: :param q_func: (DQNPolicy) the policy :param ob_space: (Gym Space) The observation space of the environment :...
395899bdb0497db5f56d42bd968ad07117cf0126
3,645,108
def _make_global_var_name(element): """creates a global name for the MAP element""" if element.tag != XML_map: raise ValueError('Expected element <%s> for variable name definition, found <%s>' % (XML_map,element.tag)) base_name = _get_attrib_or_None(element,XML_attr_name) if base_name is None: ...
7a4c26ae3791ea0543a2690a61651604e727abf6
3,645,109
def list_user_images(user_id): """ Given a user_id, returns a list of Image objects scoped to that user. :param user_id: str user identifier :return: List of Image (messsage) objects """ db = get_session() try: imgs = [msg_mapper.db_to_msg(i).to_dict() for i in db.query(Image).filte...
5a00ccae4fdea9417f26158d9042cc62a56e1013
3,645,110
def is_lower_cased_megatron(pretrained_model_name): """ Returns if the megatron is cased or uncased Args: pretrained_model_name (str): pretrained model name Returns: do_lower_cased (bool): whether the model uses lower cased data """ return MEGATRON_CONFIG_MAP[pretrained_model_na...
6ff0954a35e19144e99aa0bdbbbeddc7542aad9d
3,645,111
import subprocess import json def bright(args, return_data=True): """ Executes CA Brightside with arguments of this function. The response is returned as Python data structures. Parameter ``return_data`` is by default ``True`` and it caused to return only the data section without metadata. Metadata ...
cbc2824a2f78893fc4a5a38db95760a214c058d1
3,645,112
def decipher(string, key, a2i_dict, i2a_dict): """ This function is BASED on https://github.com/jameslyons/pycipher """ key = [k.upper() for k in key] ret = '' for (i, c) in enumerate(string): i = i % len(key) ret += i2a_dict[(a2i_dict[c] - a2i_dict[key[i]]) % len(a2i_dict)] ...
a414892f8ccf18ab5d3189b662b284939c931382
3,645,113
def keep_samples_from_pcoa_data(headers, coords, sample_ids): """Controller function to filter coordinates data according to a list Parameters ---------- headers : list, str list of sample identifiers, if used for jackknifed data, this should be a list of lists containing the sample ide...
c33eaf6c593fcebc09e98ec479ca0505c52424c8
3,645,114
import platform def get_default_command() -> str: """get_default_command returns a command to execute the default output of g++ or clang++. The value is basically `./a.out`, but `.\a.exe` on Windows. The type of return values must be `str` and must not be `pathlib.Path`, because the strings `./a.out` and `a....
d06abdefab189f9c69cba70d9dab25ce83bebc75
3,645,115
from skymaps import Band def roi_circle(roi_index, galactic=True, radius=5.0): """ return (lon,lat,radius) tuple for given nside=12 position """ sdir = Band(12).dir(roi_index) return (sdir.l(),sdir.b(), radius) if galactic else (sdir.ra(),sdir.dec(), radius)
303c288749e3bd9ee63c95e79ef5460468d2cea0
3,645,116
from typing import List def find_by_user_defined_key(user_defined_key: str) -> List[models.BBoundingBoxDTO]: """Get a list of bounding boxes by a user-defined key.""" res_json = BoundingBoxes.get('query/userdefinedkey/{}'.format(user_defined_key)) return list(map(models.BBoundingBoxDTO.from_dict, res_json...
a60137fdc43b04c1404eaeae021f61381c39c761
3,645,117
def object_type(r_name): """ Derives an object type (i.e. ``user``) from a resource name (i.e. ``users``) :param r_name: Resource name, i.e. would be ``users`` for the resource index URL ``https://api.pagerduty.com/users`` :returns: The object type name; usually the ``type`` property of...
b74e373691edf8a8b78c2a3ff5d7b9666504330a
3,645,118
import traceback def create_comment(args, global_var): """ 创建一条新评论 (每天只能允许创建最多 1000 条评论) ------------- 关于 uuid: 1. raw_str 就用 data["content"] 2. 由于生成的 comment_id 格式中有中划线, 很奇怪, 所以建议删掉: uuid = "-".join(uuid) """ can_create = hit_daily_comment_creation_threshold(global_var) if not c...
d8596febf2a020357654291952e447f175f2fe20
3,645,119
from datetime import datetime import pprint def get_aggregated_metrics(expr: ExperimentResource): """ Get aggregated metrics using experiment resource and metric resources. """ versions = [expr.spec.versionInfo.baseline] if expr.spec.versionInfo.candidates is not None: versions += expr.spe...
047f6aac3f2662f73133fb3f4be6716d2e070035
3,645,120
from fairseq.models.bart import BARTModel import torch def get_bart(folder_path, checkpoint_file): """ Returns a pretrained BART model. Args: folder_path: str, path to BART's model, containing the checkpoint. checkpoint_file: str, name of BART's checkpoint file (starting from BART's folde...
504a242d24946761f2a880db66e1955752b89677
3,645,121
import os def construct_s3_raw_data_path(study_id, filename): """ S3 file paths for chunks are of this form: RAW_DATA/study_id/user_id/data_type/time_bin.csv """ return os.path.join(RAW_DATA_FOLDER, study_id, filename)
d8ed6753947b055e88fc762135f434b5cb7eb7c7
3,645,122
def _mixed_s2(x, filters, name=None): """Utility function to implement the 'stride-2' mixed block. # Arguments x: input tensor. filters: a list of filter sizes. name: name of the ops # Returns Output tensor after applying the 'stride-2' mixed block. """ if len(filte...
b4260c1b2a9e5c38a6c48baab611ac2e0d73c888
3,645,123
from typing import Union from typing import Type def get_convertor(cls: Union[Type, str]) -> Convertor: """Returns Convertor for data type. Arguments: cls: Type or type name. The name could be simple class name, or full name that includes the module name. Note: When `cls` is...
c70ce0a032efc031de67fc965a6984779dd635e7
3,645,124
def _is_mchedr(filename): """ Checks whether a file format is mchedr (machine-readable Earthquake Data Report). :type filename: str :param filename: Name of the mchedr file to be checked. :rtype: bool :return: ``True`` if mchedr file. .. rubric:: Example >>> _is_mchedr('/path/to/m...
f8d5521cfd6ebcdf490af41877e865fb185f0f7c
3,645,125
import math def ddr3_8x8_profiling( trace_file=None, word_sz_bytes=1, page_bits=8192, # number of bits for a dram page/row min_addr_word=0, max_addr_word=100000 ): """ this code takes non-stalling dram trace and reorganizes the trace to meet the bandwidth requirement. currently, it doe...
6a3369a79ae77e6f984b5250e17a7e79393e18d2
3,645,126
def get_sites_by_latlon(latlon, filter_date='', **kwargs): """Gets list of sites from BETYdb, filtered by a contained point. latlon (tuple) -- only sites that contain this point will be returned filter_date -- YYYY-MM-DD to filter sites to specific experiment by date """ latlon_api_arg = "%s,%...
40c9bcbd8884d287a8bbdf233376f27c6c2d041e
3,645,127
import logging def get_context(book, chapter, pharse): """ Given book, chapter, and pharse number, return the bible context. """ try: context = repository['{} {}:{}'.format(book, chapter, pharse)] return context except KeyError: bookname = bookid2chinese[book] phars...
a9d261a780b57db06af921c11001786107886b68
3,645,128
def find_cocotb_base (path = "", debug = False): """ Find Cocotb base directory in the normal installation path. If the user specifies a location it attempts to find cocotb in that directory. This function failes quietly because most people will probably not use cocotb on the full design so it's not...
41bdc488a82017730785b1cad8b1f1925a82bbb7
3,645,129
import os def read_dicom_volume(dcm_path): """ This function reads all dicom volumes in a folder as a volume. """ dcm_files = [ f for f in os.listdir(dcm_path) if f.endswith('.dcm')] dcm_files = ns.natsorted(dcm_files, alg=ns.IGNORECASE) Z = len(dcm_files) reference = dicom.read_file(os.path.jo...
f93526bf0228c6f75638915bb1933b484bc23e13
3,645,130
from typing import OrderedDict def _compare_namelists(gold_namelists, comp_namelists, case): ############################################################################### """ Compare two namelists. Print diff information if any. Returns comments Note there will only be comments if the namelists were...
7a4b8fc1fa23f54bf1015c2cfd7b4b05da33b5b4
3,645,131
def directMultiCreate( data, cfg_params='', *, dtype='', doInfo = True, doScatter = True, doAbsorption = True ): """Convenience function which creates Info, Scatter, and Absorption objects directly from a data string rather than an on-disk or in-memory file. Such usage obviously...
1fe6262c0f59c836d1edcc7555b30f3182ceb2e0
3,645,132
def write_date_json(date: str, df: DataFrame) -> str: """ Just here so we can log in the list comprehension """ file_name = f"pmg_reporting_data_{date}.json" print(f"Writing file {file_name}") df.to_json(file_name, orient="records", date_format="iso") print(f"{file_name} written") return file...
7af4d44559b28c92f2df409cb59abd441f29dde5
3,645,133
def fit_composite_peak(bands, intensities, locs, num_peaks=2, max_iter=10, fit_kinds=('lorentzian', 'gaussian'), log_fn=print, band_resolution=1): """Fit several peaks to a single spectral feature. locs : sequence of float Contains num_peaks peak-location guesses, ...
b6cffef481fb158cf019831db716fd14ca8d6a86
3,645,134
def param(): """ Create a generic Parameter object with generic name, description and no value defined """ return parameter.Parameter("generic_param",template_units.kg_s,"A generic param")
1062351f477405a8be66ea1b3e10ae1f8a6403c7
3,645,135
def extract_filter(filter_path): """Given a path to the weka's filter file, return a list of selected features.""" with open(filepath) as f: lnum = 0 for line in f: lnum += 1 #pointer to the next line to read if line.strip().startswith('Selected attributes:'): ...
cc8e91ac268cdeb4d9a0e4c72eeb50659342cda6
3,645,136
def convert_to_roman_numeral(number_to_convert): """ Converts Hindi/Arabic (decimal) integers to Roman Numerals. Args: param1: Hindi/Arabic (decimal) integer. Returns: Roman Numeral, or an empty string for zero. """ arabic_numbers = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9,...
f970517a7c2d1ceb13ec025d6d446499ce5c21ff
3,645,137
def rotate_xyz(vector: Vector, angle_x: float = 0., angle_y: float = 0., angle_z: float = 0.): """ Rotate a 3d-vector around the third (z) axis :param vector: Vector to rotate :param angle_x: Rotation angle around x-axis (in degrees) :param angle_y: Rotation angle around y-axis (in degrees) :pa...
efe98080d3354713dfc4b7b26a19b21a1551ab69
3,645,138
def get_project_from_data(data): """ Get a project from json data posted to the API """ if 'project_id' in data: return get_project_by_id(data['project_id']) if 'project_slug' in data: return get_project_by_slug(data['project_slug']) if 'project_name' in data: return get_...
6ab01c4273248310ecd780fa24d6541fe1e9b0ad
3,645,139
def _from_atoms_and_bonds(atm_dct, bnd_dct): """ Construct a molecular graph from atom and bond dictionaries. format: gra = (atm_dct, bnd_dct) :param atm_dct: atom dictionary :type atm_dct: dict :param bnd_dct: bond dictionary :type bnd_dct: dict :rtype:...
0bd2d37442e2a141d9a0f81f77b6b45c5b82c06a
3,645,140
def __getattr__(item): """Ping the func map, if an attrib is not registered, fallback to the dll""" try: res = func_map[item] except KeyError: return dll.__getattr__(item) else: if callable(res): return res # Return methods from interface. else: r...
7b93dd68ce4b658226c0f6c072bb3cb51be82206
3,645,141
def seed_random_state(seed): """ Turn seed into np.random.RandomState instance """ if (seed is None) or (isinstance(seed, int)): return np.random.RandomState(seed) elif isinstance(seed, np.random.RandomState): return seed raise ValueError("%r cannot be used to generate numpy.rand...
61639222ab74ffbb3599c5d75ee0c669db463965
3,645,142
def _normalize_dashboard_link(link, request): """ Given a dashboard link, make sure it conforms to what we expect. """ if not link.startswith("http"): # If a local url is given, assume it is using the same host # as the application, and prepend that. link = url_path_join(f"{reque...
57ff43c2b364fbce94ef06447a79eeec29c06b90
3,645,143
async def delete(category_id: int): """Delete category with set id.""" apm.capture_message(param_message={'message': 'Category with %s id deleted.', 'params': category_id}) return await db.delete(category_id)
2c1aa6e9f40006d5c07fe94a9838b5f2709bc781
3,645,144
import glob import os def find_files(fields): """ Finds all FLT files from given fields and places them with metadata into OrderedDicts. Parameters ---------- fields : list of strings The CLEAR fields; retain ability to specify the individual pointings so that can easily re-run s...
2ba34c95e996bf7a4ecb6f886df59502f6797339
3,645,145
def to_canonical_name(resource_name: str) -> str: """Parse a resource name and return the canonical version.""" return str(ResourceName.from_string(resource_name))
e9e972a8bc2eb48751da765b65ea8881e033d05c
3,645,146
import six def apply_query_filters(query, model, **kwargs): """Parses through a list of kwargs to determine which exist on the model, which should be filtered as ==, and which should be filtered as LIKE """ for k, v in six.iteritems(kwargs): if v and hasattr(model, k): column = ge...
1a7885ab55645d6a00f35668718bc119a8b18939
3,645,147
def bytes_to_b64_str(bytestring: bytes) -> str: """Converts random bytes into a utf-8 encoded string""" return b64encode(bytestring).decode(config.security.ENCODING)
cff8e979b3d5578c39477e88f2895ebbb07f794e
3,645,148
def read_event_analysis(s:Session, eventId:int) -> AnalysisData: """read the analysis data by its eventId""" res = s.query(AnalysisData).filter_by(eventId=eventId).first() return res
4dba5e7489e6cee28312710fa233b7066d04b995
3,645,149
def eval_semeval2012_analogies( vectors, weight_direct, weight_transpose, subset, subclass ): """ For a set of test pairs: * Compute a Spearman correlation coefficient between the ranks produced by vectors and gold ranks. * Compute an accuracy score of answering MaxDiff questions....
f8b13ef5520129e753024bc5ec3d25d7ab24ccee
3,645,150
def form_examples(request, step_variables): """ extract the examples from the request data, if possible @param request: http request object @type request rest_framework.request.Request @param step_variables: set of variable names from the bdd test @type step_variables: set(basestring) @retu...
2385974ace0091fb54dbce3b820cc36082a90e78
3,645,151
def get_typefromSelection(objectType="Edge", info=0): """ """ m_num_obj, m_selEx, m_objs, m_objNames = get_InfoObjects(info=0, printError=False) m_found = False for m_i_o in range(m_num_obj): if m_found: break Sel_i_Object = m_selEx[m_i_o] Obj_i_Object = m_objs[m_i_o]...
a2e55139219417b05fc9486bb9880bc6d17e1777
3,645,152
def load_file(file_path, mode='rb', encoder='utf-8'): """ Loads the content of a given filename :param file_path: The file path to load :param mode: optional mode options :param encoder: the encoder :return: The content of the file """ with xbmcvfs.File(xbmcvfs.translatePath(file_path), ...
118f18fd651a332728e71d0b7fac5e57ad536f4b
3,645,153
def centcalc_by_weight(data): """ Determines the center (of grtavity) of a neutron beam on a 2D detector by weigthing each pixel with its count -------------------------------------------------- Argments: ---------- data : ndarray : l x m x n array with 'pixel' - data to weight ove...
6d3bb14820bb11ac61c436055d723bbd49f77740
3,645,154
def sum(a, axis=None, dtype=None, out=None, keepdims=False): """Returns the sum of an array along given axes. Args: a (cupy.ndarray): Array to take sum. axis (int or sequence of ints): Axes along which the sum is taken. dtype: Data type specifier. out (cupy.ndarray): Output arra...
7382cbd6cbcf555cf63acc7b48a65f59a3d847c3
3,645,155
import os def to_bool(env, default="false"): """ Convert a string to a bool. """ return bool(util.strtobool(os.getenv(env, default)))
a8471d8bb7600e7f54e8ad1612a5f1c090e864c5
3,645,156
import textwrap def public_key(): """ returns public key """ return textwrap.dedent(''' -----BEGIN RSA PUBLIC KEY----- MIIBCgKCAQEAwBLTc+75h13ZyLWlvup0OmbhZWxohLMMFCUBClSMxZxZdMvyzBnW +JpOQuvnasAeTLLtEDWSID0AB/EG68Sesr58Js88ORUw3VrjObiG15/iLtAm6hiN BboTqd8jgWr1yC3LfNSKJk82qQzH...
4d27c3e72714bccd885178c05598f0f1d8d7914d
3,645,157
import pickle import tqdm def fetch_WIPOgamma(subset, classification_level, data_home, extracted_path, text_fields = ['abstract', 'description'], limit_description=300): """ Fetchs the WIPO-gamma dataset :param subset: 'train' or 'test' split :param classification_level: the classification level, eith...
05d3f19950321c5e94abf846bd7fab2d9b905f39
3,645,158
from typing import Optional import requests def latest_maven_version(group_id: str, artifact_id: str) -> Optional[str]: """Helper function to find the latest released version of a Maven artifact. Fetches metadata from Maven Central and parses out the latest released version. Args: group_id (...
1c5f3b3e683e5e40f9779d53d93dad9e1397e25d
3,645,159
def zeropoint(info_dict): """ Computes the zero point of a particular system configuration (filter, atmospheric conditions,optics,camera). The zeropoint is the magnitude which will lead to one count per second. By definition ZP = -2.5*log10( Flux_1e-_per_s / Flux_zeromag ), where Flux_1e-_per_s ...
0deba397aa14226a45af7a1acca6f51ec846083b
3,645,160
def model_comp(real_data, deltaT, binSize, maxTimeLag, abc_results1, final_step1, abc_results2, final_step2,\ model1, model2, distFunc, summStat_metric, ifNorm,\ numSamplesModelComp, eval_start = 3, disp1 = None, disp2 = None): """Perform Baysian model comparison with ABC fits from m...
060fa9dcd133363b93dd22353eee5c47e3fd90dd
3,645,161
def unwrap(*args, **kwargs): """ This in a alias for unwrap_array, which you should use now. """ if deprecation_warnings: print('Use of "unwrap" function is deprecated, the new name '\ ' is "unwrap_array".') return unwrap_array(*args, **kwargs)
156b5607b3b76fff66ede40eed79ca5cf74b1313
3,645,162
def solve(): """solve form""" if request.method == 'GET': sql="SELECT g.class, p.origin, p.no, p.title, p.address FROM GIVE g, PROBLEM p WHERE g.origin=p.origin AND g.no=p.no AND class = 1" cursor.execute(sql) week1=[] for result in cursor.fetchall(): week1.append({ "class":result['class'], "origin...
4d1d117b686ef4bb265b9fcc2185f07351710f49
3,645,163
import re def build_path(entities, path_patterns, strict=False): """ Constructs a path given a set of entities and a list of potential filename patterns to use. Args: entities (dict): A dictionary mapping entity names to entity values. path_patterns (str, list): One or more filename p...
120811c5560fabe48e10f412c0b3c0ab3592a887
3,645,164
def schedule_compensate(): """ swagger-doc: 'schedule' required: [] req: course_schedule_id: description: '课程id' type: 'string' start: description: '课程开始时间 format YYYY-mm-dd HH:MM:ss.SSS' type: 'string' end: description: '课程结束时间 in sql format YYY...
7c3a14af27287e64535d7b9150531d8646cb0cfe
3,645,165
def parse(xml): """ Parse headerdoc XML into a dictionary format. Extract classes, functions, and global variables from the given XML output by headerdoc. Some formatting and text manipulation takes place while parsing. For example, the `@example` is no longer recognized by headerdoc. `parse()` will extract exam...
f130a7b457d3b347153a3ea013f69a11dc3859c2
3,645,166
import os def ReadKeywordValueInFile(filename,keyword): """ Get value in the expression of keyword=vlaue in file :param str filenname: file name :param str keywors: keyword string :return: value(str) - value string """ value=None; lenkey=len(keyword) if not os.path.exists(filename): r...
cea315129a39384a80de227d17f647d24fcd27c7
3,645,167
def getSolventList(): """ Return list of solvent molecules for initializing solvation search form. If any of the Mintz parameters are None, that solvent is not shown in the list since it will cause error. """ database.load('solvation', '') solvent_list = [] for index, entry in database.solva...
ea202459ac69b02d362c422935e396be04e7ec30
3,645,168
import random def subset_samples(md_fp: str, factor: str, unstacked_md: pd.DataFrame, number_of_samples: int, logs:list) -> pd.DataFrame: """ Subset the metadata to a maximum set of 100 samples. ! ATTENTION ! In case there are many columns with np.nan, these should be ...
36b99aaecf7fc67b4a5809bb00758b158d753997
3,645,169
def _process_image(filename, coder): """Process a single image file. Args: filename: string, path to an image file e.g., '/path/to/example.JPG'. coder: instance of ImageCoder to provide TensorFlow image coding utils. Returns: image_buffer: string, JPEG encoding of RGB image. height:...
2b5c78a6b641ce31aed3f80590dcf6dbe3a36baa
3,645,170
def to_rna_sequences(model): """ Convert all the sequences present in the model to RNA. :args dict model: Description model. """ for seq, path in yield_sub_model(model, ["sequence"]): set_by_path(model, path, str(Seq(seq).transcribe().lower())) return model
8a0929e631e6d162f47ba1773975116b0e2caff4
3,645,171
def rest_get_repositories(script, project=None, start=0, limit=50): """ Gets a list of repositories via REST :param script: A TestScript instance :type script: TestScript :param project: An optional project :type project: str :param start: The offset to start from :type start: int :p...
772b1682ba3de11b98d943f4a768386b7907b1d9
3,645,172
def clean_float(input_float): """ Return float in seconds (even if it was a timestamp originally) """ return (timestamp_to_seconds(input_float) if ":" in str(input_float) else std_float(input_float))
8ce6ca89b40750bb157d27a68631ddd64a824f3a
3,645,173
def resize( image, output_shape, order=1, mode="constant", cval=0, clip=True, preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None, ): """A wrapper for Scikit-Image resize(). Scikit-Image generates warnings on every call to resize() if it doesn't receive the rig...
21273e385e892e21e6fb40241d9c430b6f41ba3d
3,645,174
def get_subsystem_fidelity(statevector, trace_systems, subsystem_state): """ Compute the fidelity of the quantum subsystem. Args: statevector (list|array): The state vector of the complete system trace_systems (list|range): The indices of the qubits to be traced. to trace qubits...
13d3ef7fc3e7d414fe6b936f839c42321a5e0982
3,645,175
import requests def jyfm_data_coke(indicator="焦炭总库存", headers=""): """ 交易法门-数据-黑色系-焦炭 :param indicator: ["焦企产能利用率-100家独立焦企产能利用率", "焦企产能利用率-230家独立焦企产能利用率", "焦炭日均产量-100家独立焦企焦炭日均产量", "焦炭日均产量-230家独立焦企焦炭日均产量", "焦炭总库存", "焦炭焦企库存-100家独立焦企焦炭库存", "焦炭焦企库存-230家独立焦企焦炭库存", "焦炭钢厂库存", "焦炭港口库存", "焦企焦化利润"] :typ...
23f1c0cad5cb93953f5d5745f0c3e14aedd51fd8
3,645,176
from typing import Tuple from typing import Any def generate_index_distribution( numTrain: int, numTest: int, numValidation: int, params: UQDistDict ) -> Tuple[Any, ...]: """ Generates a vector of indices to partition the data for training. NO CHECKING IS DONE: it is assumed that the data could be par...
f3c35d5c99a3f79b40f3c7220519152b85fe679d
3,645,177
def generacionT (v, m): """ Signature of a message with hash, hashed. Here we have to use the private key. Parameters: m (int): Number of oil v (int): Number of vinager Returns: T (matrix): Matrix with dimension nxn """ #Matriz de distorsion T = [] n = v + m for i in range(n): ...
6fd4d9f8ebeea5f422c937b3b92c5c5134ffd541
3,645,178
from io import StringIO import pandas from datetime import datetime def isotherm_from_bel(path): """ Get the isotherm and sample data from a BEL Japan .dat file. Parameters ---------- path : str Path to the file to be read. Returns ------- dataDF """ with open(path) as ...
7aa144942ef6e0cb3d2926817015692b8fe8b99b
3,645,179
import os import random def image(height, width, image_dir): """ Create a background with a image """ images = [xx for xx in os.listdir(image_dir) \ if xx.endswith(".jpeg") or xx.endswith(".jpg") or xx.endswith(".png")] if len(images) > 0: image_name = images[random.rand...
c08c047490d1f14d7c97b8bd7927fca5f04dfeed
3,645,180
def model(x, a, b, c): """ Compute .. math:: y = A + Be^{Cx} Parameters ---------- x : array-like The value of the model will be the same shape as the input. a : float The additive bias. b : float The multiplicative bias. c : float The expone...
12a8272fb773226ad328daeb460cc2ca84d4c6e0
3,645,181
from typing import List import os def add_abspath(dirs: List): """Recursively append the absolute path to the paths in a nested list If not a list, returns the string with absolute path. """ if isinstance(dirs, list): for i, elem in enumerate(dirs): if isinstance(elem, str): ...
544fb5bb680b6a7874c7364090109ee3cdc75632
3,645,182
import inspect def equal_matches( matches_a: kapture.Matches, matches_b: kapture.Matches) -> bool: """ Compare two instances of kapture.Matches. :param matches_a: first set of matches :param matches_b: second set of matches :return: True if they are identical, False otherwise. ...
57efdd63a56f4e94afc9a57e05f4e4f726ce7b44
3,645,183
def convert_to_example(img_data, target_data, img_shape, target_shape, dltile): """ Converts image and target data into TFRecords example. Parameters ---------- img_data: ndarray Image data target_data: ndarray Target data img_shape: tuple Shape of the image data (h,...
d8dd2b78a85d2e34d657aa36bfe3515ef1dd5418
3,645,184
def linear(args, output_size, bias, bias_start=0.0, scope=None, var_on_cpu=True, wd=0.0): """Linear map: sum_i(args[i] * W[i]), where W[i] is a variable. Args: args: a 2D Tensor or a list of 2D, batch x n, Tensors. output_size: int, second dimension of W[i]. bias: boolean, whether to add a bi...
1072115bc42b3d2acb3d41cd0116a636f6bb7804
3,645,185
def _start_job(rule, settings, urls=None): """Start a new job for an InfernoRule Note that the output of this function is a tuple of (InfernoJob, DiscoJob) If this InfernoJob fails to start by some reasons, e.g. not enough blobs, the DiscoJob would be None. """ job = InfernoJob(rule, settings, ...
5eab30433004240d79f1ec4eeac868b40632cdde
3,645,186
def mult(dic,data,r=1.0,i=1.0,c=1.0,inv=False,hdr=False,x1=1.0,xn='default'): """ Multiple by a Constant Parameter c is used even when r and i are defined. NMRPipe ignores c when r or i are defined. Parameters: * dic Dictionary of NMRPipe parameters. * data array of spectral data. ...
833ab3784dc9210aa6be0f968f9115982ea93753
3,645,187
import os def generate_gps_photon(stream, source, focus, angle_gantry, angle_couch, angle_coll, beamletsize, sad, sfd, energy_mev, desc='Diverging Square field', gps_template=None): """Generate the gps input file using a template Args: idx (int): index of beamlet in beam (row-major order) ...
918c31ee44fe241a07c67587ccd673c4a83cdb2c
3,645,188
import re def navigation_target(m) -> re.Pattern: """A target to navigate to. Returns a regular expression.""" if hasattr(m, 'any_alphanumeric_key'): return re.compile(re.escape(m.any_alphanumeric_key), re.IGNORECASE) if hasattr(m, 'navigation_target_name'): return re.compile(m.navigation_...
62cc847f5454e76afb128fd752b7fa83fd2e167e
3,645,189
def hammingDistance(strA, strB): """ Determines the bitwise Hamming Distance between two strings. Used to determine the fitness of a mutating string against the input. Example: bin(ord('a')) == '0b1100001' bin(ord('9')) == '0b0111001' bin...
d417ac22a1abd4c2df0f274d809096f354ac4150
3,645,190
import regex def convert(s, syntax=None): """Convert a regex regular expression to re syntax. The first argument is the regular expression, as a string object, just like it would be passed to regex.compile(). (I.e., pass the actual string object -- string quotes must already have been removed an...
e61a9d555008c9b36b579f6eb1e32e1e9fa0e983
3,645,191
import select def current_user(request): """Return the list of all the users with their ids. """ query = select([ User.id.label('PK_id'), User.Login.label('fullname') ]).where(User.id == request.authenticated_userid) print return dict(DBSession.execute(query).fetchone())
6951a6c638886d773a9e92e161d9aa2b166b17b3
3,645,192
def get_test_examples_labels(dev_example_list, batch_size): """ :param dev_example_list: list of filenames containing dev examples :param batch_size: int :return: list of nlplingo dev examples, dev labels """ dev_chunk_generator = divide_chunks(dev_example_list, NUM_BIG_CHUNKS) test_examples...
e46a3c1d9780c8b74fcef3311267ad87f5938a66
3,645,193
import uuid import tokenize from operator import getitem from typing import Iterator from typing import OrderedDict def unpack_collections(*args, **kwargs): """Extract collections in preparation for compute/persist/etc... Intended use is to find all collections in a set of (possibly nested) python object...
d855a4cea5cb16a5863d670edb4bda6d15e2b371
3,645,194
def get_usernames(joomlasession): """Get list of usernames on the homepage.""" users = joomlasession.query(Jos_Users).all() return [user.username for user in users]
b866cdd8fb47d12b7b79291f3335ded217fa8a1d
3,645,195
def minor_block_encoder(block, include_transactions=False, extra_info=None): """Encode a block as JSON object. :param block: a :class:`ethereum.block.Block` :param include_transactions: if true transaction details are included, otherwise only their hashes :param extra_i...
53b0eb26e7a8ef0c05f4149c71b09ff6505f85d0
3,645,196
def heaviside(x): """Implementation of the Heaviside step function (https://en.wikipedia.org/wiki/Heaviside_step_function) Args: x: Numpy-Array or single Scalar Returns: x with step values """ if x <= 0: return 0 else: return 1
5ef05263637501f82cea3befe897cd60ec39994d
3,645,197
def FallbackReader(fname): """Guess the encoding of a file by brute force by trying one encoding after the next until something succeeds. @param fname: file path to read from """ txt = None for enc in GetEncodings(): try: handle = open(fname, 'rb') reader = codec...
d9f4235df9f472c7584192e920980f5f2668202a
3,645,198
def graph_3D(data, col="category", list_=[None], game=None, extents=None): """ 3D t-sne graph data output :param data: a pandas df generated from app_wrangling.call_boardgame_data() :param col: string indicating which column (default 'category') :param list_: list of elements in column (default [No...
17ad05f2c7cc3413c145009fb72aed366ec9ab49
3,645,199