content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fetch_table_ocr(ocr_data, x0, x1, y0, y1): """ #TODO ARGUMENTS: ocr_data: This contains the ocr data of the entire file. x0: is the x coordinate of the top left of the table. x1: is the y coordinate of the top left of the table. y0: is the x coordinate of the bottom right of the tabl...
2a5a62555f5b410a1f20a6b2bee1340074bf310e
3,606,900
def azimuthalAverage(image, center=None, stddev=False, returnradii=False, return_nr=False, binsize=0.5, weights=None, steps=False, interpnan=False, left=None, right=None, return_max=False): """ Calculate the azimuthally averaged radial profile. NB: This was found online and should be properly credi...
a2a36dc2398ad9a2eabee3adb6eb785c386a1130
3,606,901
def get_constraints_D(D_topright, anchors, basis, vectorized=False, A=None, b=None): """ Get constraints on Z given by the distances. .. math:: t_{mn}^T Z t_{mn} = d_{mn}^2 where :math:`t_{mn} = (a_m^T -f_n^T)^T` :param D_topright: squared distsance measurements, shape (n_positions x n_anchor...
6d101509ab044c83bcb0dd17ddc8c623ec8cf70a
3,606,902
def mmd_poly(X, Y, degree=2, gamma=1, coef0=0): """MMD 多项式核 即 k(x,y) = (gamma <X, Y> + coef0)^degree 参数: X {[n_sample1, dim]} -- [X matrix] Y {[n_sample2, dim]} -- [Y matrix] 参数关键字: degree {int} -- [degree] (default: {2}) gamma {int} -- [gamma] (default: {1}) coef0 ...
329eca1200b14e2debdbddf4b07d70a956851095
3,606,903
def delete(id): """ deletes a director with given id. :param uuid.UUID id: person id. :returns: count of deleted items. :rtype: int """ return get_component(DirectorsPackage.COMPONENT_NAME).delete(id)
251a9f47b1377900bd4124d7b72bd9d8ea6ccbf7
3,606,904
def should_build( req, # type: InstallRequirement need_wheel, # type: bool check_binary_allowed, # type: BinaryAllowedPredicate ): # type: (...) -> Optional[bool] """Return whether an InstallRequirement should be built into a wheel.""" if req.constraint: # never build requirements tha...
3f25479fad5cd792f4bcfe9ee2dfa38f62a64a7b
3,606,905
def kill_multiedges_reaxis(f, v, fg): """Combine all multiedges between f and v in fg. DOES NOT PERFORM COMPUTATION. This is a helper function and should only be used in other functions which perform the appropriate computation. No indexing is performed on the factor of f. This purely deals with the ...
89de0ae46d84952d6c2d90aa9cc488f9976e5e75
3,606,906
async def authorize(): """Redirects to spotify authorization.""" url = await authorize_spotify() return RedirectResponse(url.get('spotify'))
80d4d5c15a2180ea1f7ffb7a61ef537bb26a36dd
3,606,907
import sys def req_missing(names, purpose, python=True, optional=False): """Log that we are missing some requirements. `names` is a list/tuple/set of missing things. `purpose` is a string, specifying the use of the missing things. It completes the sentence: In order to {pu...
818a915308040c9411d4bbfd1cff8d3abb63722d
3,606,908
import json def guest_clone(hypervisor, host, guest_id): """ Clone a guest :: POST /:hypervisor/:host/guests/:guest_id/clone """ response.content_type = "application/json" manager = create_manager(hypervisor, host) data = request.body.readline() if not data: abort(400,...
62f074a475305b0fec4cb0507ef03f3336c58ec5
3,606,909
def parse_date(s): """Parse date from string. If no timezone is specified, default is assumed to be local time zone. :param s: The date to parse. :type s: str """ return iso8601.parse_date(s, LOCAL_TIMEZONE)
76cd438facc18167593b95dd6428f1dddfe34988
3,606,910
def build_ip_dict(ip): """ Takes in ip address as string, if valid IP, builds a dictionary :param ip: :return: """ inner_ip = ip def _build_ip_dict(inner_ip): if valid_ip(inner_ip): return {"ip_address": inner_ip} if type(inner_ip) is dict: if 'entry_ip_add...
246a21891143c42386354654018d0302a33380d0
3,606,911
def calc_anchor(sam, scaf_to_ref): """anchoring、染色体を突き止めた度合い""" # scafs[scaf_name] = {T:0, F:0} scafs = defaultdict(lambda: {"T": 0, "F": 0}) refs = defaultdict(lambda: {"T": 0, "F": 0}) for ref_name, ref_start, scaf_name, scaf_start, mapq, ori in sam: if mapq >= 60 and scaf_name in scaf_to_...
821fec9eeb3a95b6b4e6758b29c87a4a7ef22b46
3,606,912
def pca(U, centre=False): """Compute the PCA basis for columns of input array `U`. Parameters ---------- U : array_like 2D data array with rows corresponding to different variables and columns corresponding to different observations center : bool, optional (default False) Flag ind...
491e64f4316e6be8db5c8359345a46ad370b5c42
3,606,913
def set_heads(doc, heads): """Set heads to doc in UD annotation style. If fail to set, return doc without doing anything. """ if max(heads) > len(doc) or min(heads) < 0: return doc for head, token in zip(heads, doc): if head == 0: token.head = token else: ...
bad84ae29c0f5000d02243c55350df0a2dc698f4
3,606,914
def get_feed_renderer(engines, name): """ From engine name, load the engine path and return the renderer class Raise 'FeedparserError' if any loading error """ if name not in engines: raise FeedparserError("Given feed name '{}' does not exists in 'settings.FEED_RENDER_ENGINES'".format(n...
3f9b8c68904b2abae6dddb27b286bd5502adddd9
3,606,915
from app import bcrypt from app import cors from app import db from app import migrate from app.api import api def create_app(environemnt): """ App factory for the server. Instantiates a Flask object. Configures the app according to the environment. Initializes the extensions. Adds the middle...
3ae92139a0c75d8405bb06f0f0746904a9ce110c
3,606,916
import os import requests def upload_file_to_site(local_file_path, site_upload_url, **req_kwargs): """ uploads a file using requests (not using chunks so don't use for very large files) :param local_file_path: :return: """ data = dict(upload=os.path.basename(local_file_path)) files = dict(upl...
287cfefc69d3fb7924a1a7e48527c22fa7f40d1f
3,606,917
def ping(request): """ Ping view for Service health checks Service is healthy if we can query database """ db_status = False try: Enquiry.objects.exists() db_status = True except OperationalError: pass return HttpResponse( "OK" if db_status else "ERROR"...
4cdc652e5eab990a6a0a3455361a07acd849fc23
3,606,918
def main(arguments): """ Main function that sets the functionality of the software that will be used [Pele, Adaptive, glide...] and launch the respective job """ #arguments = YamlParser(arguments.input_file) set_software_to_use(arguments) job = Launcher(arguments) job.launch() re...
f50434a5b5d958989399d3cddf6f491cdbbdb555
3,606,919
def sammenlign( kandidat, neste, koordinattoleranse = 1e-6): """ Regler for nå to oppføringer kan slås sammen: Samme koordinat, samme vegref-verdi og tilstøtende datoer """ dx = kandidat['geometry']['coordinates'][0] - neste['geometry']['coordinates'][0] dy = kandidat['geometry']['coordinates'...
d23b7ca13177255c135ead3687443d8693841022
3,606,920
import hicat.simulators import time import os def contrast_hicat_num(matrix_dir, matrix_mode='hicat', rms=1*u.nm): """ Compute the contrast for a random IrisAO mislignment on the HiCAT simulator. :param matrix_dir: str, directory of saved matrix :param matrix_mode: str, analytical or numerical; curren...
502924a1255ca76eb3ca7c62c3d7fc468d2e272d
3,606,921
def _get_vacuum_device_charging(): """Return a vacuum device charging.""" device = mock.Mock(spec=Dyson360Eye) device.name = "Device_Vacuum" device.state = mock.MagicMock() device.state.state = Dyson360EyeMode.INACTIVE_CHARGING device.state.battery_level = 40 device.state.power_mode = PowerM...
614b7a33e9c07cf026b7568aeffa0aa9ff91bf27
3,606,922
import random def gen(n_frames, n_points): """ Generate frames, each contains points with random y value n_frames -- Number of frames n_points -- Number of points """ frames = array_init(n_frames) for i in range(n_frames): points = array_init(n_points) # initialize a list with size for j in ran...
d58be345b9512fbbe3de35553fdd2620a4bec015
3,606,923
def proper_fits_shapes(qname, uname, frequencyname): """ Verify that the Q and U FITS cubes and the file with frequency data have compatible shapes. *qname* and *uname* are the filenames of the Q and U FITS files, respectively; *frequencyname* is the filename of the frequency file. Returns True...
019db6b7dab5ed05b41c2c86d7d00cc99beaaf55
3,606,924
def is_row(y): """ Checks if input array is a row Parameters ---------- y : array_like Input array """ y = np.asarray(y) shape = y.shape if len(shape) == 1: return True return shape[0] == 1
c7f68ab0c8f0e1229e56509e609f353f86137c79
3,606,925
import os def file_type_detection(filename): """Detect product type by using the file extension. Parameters ---------- filename: string : full path to the product Returns ------- MetExtractor: class : A metadata extractor class to extract metadata from the product """ ext = os.pa...
5d4a35da82d4997d758e08ed805f8d8e33c792f3
3,606,926
def input_fn_builder(input_files, max_seq_length, max_predictions_per_seq, is_training, vocab_size, num_cpu_threads=4): """Creates an `input_fn` closure to be passed to TPUEstimator.""" def input_fn(params): ...
9ae6cb71cad68a110ce1b884b5126a45dfdde932
3,606,927
def conv2d_transpose(inputs, num_output_channels, kernel_size, scope, stride=[1, 1], padding='SAME', data_format='NHWC', use_xavier=True, stddev=1e-3, ...
a062e3b5f8060e3a92b3a06125be2b1e39153c45
3,606,928
def uninominal(m, axis=1, turns=1): """ Uninominal. Args: turns: number of turns. """ if turns > 1: raise(Exception('Uninominal system is currently implemented only in one turn setting.')) ranking = rank(m, axis=1-axis) # convert to rank #for turn in range(turns): # TODO replace...
c7413f38d0e2a9cd794514d649e85a65e93736d9
3,606,929
from sys import path def translate_rna_to_protein(rna): """your code here""" codon_table = path.replace('dna.fasta', 'rna_codon_table.txt') with open(codon_table) as codons: codons = codons.read() codons = codons.replace('\n', ' ').split(' ') codons = set(codons) codons.remove(''...
915ff512dd04cf3c360ed95841ac892aa52db3e6
3,606,930
def is_valid(number): """Check if the number provided is a valid tax identification number. This checks the length, formatting and check digit.""" try: return bool(validate(number)) except ValidationError: return False
dfb03a49c109a9971d4d9c09921593de1f4ba420
3,606,931
def pack_bits(bits): """ Pack tf.uint8 bit arrays into arrays of tf.int64 by interpreting blocks of 64 bits as an int64. Args: bits: A tf.uint8 `Tensor` of shape (None, n_bits). `n_bits` must be a multiple of 64. Returns: bits: A tf.int64 `Tensor` of shape (None, n_bits // 64) ""...
f0ee8369f1836ce71bbebf225709b254e08cfeda
3,606,932
def gateway_info(country, language): """Load information about the hosts to use for API interaction. `country` and `language` are codes, like "US" and "en-US," respectively. """ return lgedm_post(GATEWAY_URL, {"countryCode": country, "langCode": language},)
b79a2d93e8a4ef334c08e77d4f96f89679966987
3,606,933
import torch def validate_inf( model, config, val_images, log_folder=None, use_full_size=True, global_threshold=None, use_tta=False, save=False, save_all_tta=False, ): """ Performs inference with a model on a list of train images. Args: model (torch model): Seg...
7b13a8c926679a94d2daf55515120ad4fd6b2cfb
3,606,934
import numpy as np import pandas as pd from scipy.special import erfcinv, gammaln from . import CiaoEnvironment def compute_bgband (evtpath, srcreg, bkgreg, ebins, env=None): """Compute background information for a source in one or more energy bands. evtpath Path to a CIAO events file srcreg ...
a1dc0abe9fbad4bc9e0a3cd7211f5e10cf95e17d
3,606,935
def compute_fs(photspec, x, dE_dVdt_inj, dt, method='old', cross_check=False): """ Compute f(z) fractions for continuum photons, photoexcitation of HI, and photoionization of HI, HeI, HeII Given a spectrum of deposited photons, resolve its energy into continuum photons, continuum photons, HI excitation, an...
46fe61a4584f898fdbf6534f70d109c950d11f3d
3,606,936
def tokenize(text): """Simple tokenizer, change for something more sophisticated """ return text.lower().split()
ce7269ebfe3446c70346cef38a526393accda8b8
3,606,937
from typing import Optional def build_compound(smiles: Optional[str] = None, name: Optional[str] = None, amount: Optional[str] = None, role: Optional[str] = None, is_limiting: Optional[bool] = None, prep: Optional[str] = No...
6802831b277c8d213e3b93c886264bd3d5457130
3,606,938
def num_components(): """Get the number of components available on the system. :rtype: int """ return lib.PAPI_num_components()
fdc2fe8cf766e48832c643fddab2f90aa7c8b1d1
3,606,939
def route_not_found(error): """route to handle error""" return error
83b1f52de8ed92e8b8a833ba85ce725cbb5d3757
3,606,940
def _task_to_entry_point_ids(meta_task): """Generate entry points from a meta-task. $entry:e_0, $entry:e_1, ... From the commandline, the usage would be -e e_0:/path/to/file1.txt -e e_1:/path/to/file2.txt This is used to automatically create pipeline entry points from the positional inputs of the...
768971a4b6f43bb13a56497c25de698abd9196ba
3,606,941
def crypt(key,data,iv='\00\00\00\00\00\00\00\00',n=32): """ Encrypt/decrypt variable length string using XTEA cypher as key generator (OFB mode) * key = 128 bit (16 char) * iv = 64 bit (8 char) * data = string (any length) >>> import os >>> key = os.urandom(...
2cc828f45b8dd1728154e6d1a9e58093e7c91854
3,606,942
import torch def genomepredict( sequence, mchr, mpos=-1, wpos=-1, models=["h1esc", "hff"], targets=None, annotation=None, use_cuda=True, nan_thresh=1, ): """Multiscale prediction for a 32Mb sequence input, zooming into the position specified when generating a series of 32Mb, 16Mb, 8Mb, 4Mb, 2Mb and 1M...
6285c222924dd1c8d1993214f262b242431e214c
3,606,943
def clean_mentions(line): """Escape anything that could resolve to mention.""" return line.replace("@", "@\u200b")
b23ae6f9f0d54c5c2d210cf9f8a14732acd5b532
3,606,944
def _parse_function(filename, label, n_channels, size): """ Returns resized and normalized image and its label """ resized_image = _parse_image(filename, n_channels, size) return resized_image, label
e8307e33a5a9ef39890b9c8bafc2bed8e2c5ed57
3,606,945
def delete(isamAppliance, name, check_mode=False, force=False): """ Delete a management authorization role """ if force is True or _check(isamAppliance, name) is True: if check_mode is True: return isamAppliance.create_return_object(changed=True) else: return isam...
e362caf8c34430a3d662cbf01bd8aff6fc4a5a50
3,606,946
def test_no_extra_meta(wrapper_class, build_fn): """Check that wrappers do not create any unexpected meta parameters. """ n, d = 20, 3 n_classes = 3 X = np.random.uniform(size=(n, d)).astype(float) y = np.random.choice(n_classes, size=n).astype(int) # with user kwargs clf = wrapper_clas...
14a72cf5f35136b7507da32df3e210acd151a59b
3,606,947
import re def _tf_model_node_name_reformat(node, node_name): """ Rename the node name by combining scope name and its original name. Args: node (OnnxGraphNode): OnnxGraphNode instance. node_name (str): node name saved in Graph. Returns: str, re-formatted node name. """ ...
3103ad87eaa4d923274f5f9aa529188879d48a7a
3,606,948
import time def ctime(): """ Get time now Returns: time_string (str): current time in string """ return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
57dfa3f2c9e4c7dbff51e18cdc63011df37a7241
3,606,949
def mean_percentage_error(y_true: np.ndarray, y_pred: np.ndarray): """ Mean Percentage Error Formula taken from: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5365136/ Parameters ---------- * y_true : pd.Series The observations of the time series * y_pred : pd.Series The val...
c5d3e7502dac6849629f8743a40ffc149c59304b
3,606,950
def conn_ravel_directed(da, sep='-', drop_within=False): """Ravel a directed array. This function reorganize a directed array that contains the coordinates x->y and y->x to a single coordinate 'x->y'. Parameters ---------- da : xarray.DataArray Xarray DataArray that should at least con...
ce4e9019a9282248f294cae1b5bb11f29287e692
3,606,951
def verify_credentials_command( client: Client, account_id: str, ) -> str: """Mark an account for verification by the CPM. :param client: The client object with an access token :param account_id: The unique ID of the account. :return: Action was succeeded notice """ client.verify...
9edd0ee67e326f63e9570674aea8463df41a6847
3,606,952
def is_clique(S, A): """Check if the subgraph of A induced by nodes S is a clique. Parameters ---------- S : set of ints set containing the nodes' indices A : np.array the adjacency matrix of the graph, where A[i,j] != 0 => i -> j and A[i,j] != 0 & A[j,i] != 0 => i - j. ...
4b4d54fe6df226def988069c421c03fd088461b3
3,606,953
from typing import List def mention_to_tokens( mention: Mention, token_type: str = "words", lowercase: bool = False ) -> List[str]: """ Extract tokens from the mention :param mention: mention object. :param token_type: token type that wants to extract (e.g. words, lemmas, poses). :type token_...
927e10cecd6dde28f2595ed594807a77d615c376
3,606,954
import ast def is_valid_ast(tree): """Make sure an ast is valid by trying to compile it""" try: ast.fix_missing_locations(tree) compiled = compile(tree, "<test-ast>", "exec") except (SyntaxError, ValueError, TypeError) as e: return (False, e) return (True, None)
ede0c703e463d9bfbe15831e03de474d669aba44
3,606,955
import math def solve_elbow_xy(xpos, ypos, parity, length1, length1sq, length2, length2sq): """ Helper function to solve the elbow location given a target position (xpos, ypos), parity choice (-1 or 1) and arm radii. In the polar coordinates, theta is an angle measured clockwise from the Y ax...
d69be29233d6906693135a28e9bf357ce1eac76c
3,606,956
from rasterio.features import rasterize from rasterio.features import bounds as calculate_bounds import click import json import os def rasterize( ctx, files, driver, like, bounds, dimensions, res, src_crs, all_touched, default_value, ...
7b20242911f0601c31715b64104e7330dccbba8c
3,606,957
def getCommonsMembersBetween(startDate, endDate, outputParameters= \ ['Constituencies', 'Parties', 'HouseMemberships']): """ Returns all Commons members between startDate and endDate, which must be instances of datetime.date. """ s = '{0}-{1}-{2}'.format(startDate.year, startDate.month, startDate.day) e = '{0}...
5fa9e76bb2c92f3c305f8fa1c1188c66ca50b6fb
3,606,958
def rstar_minmax(blk, crvlist): """ Allow only valid values of rstar in the given block. """ ## get min and max rstar values j = blk.j lims = rstar_limits(blk.master.metfunc) left, right = lims[j], lims[j+1] rstar_min, rstar_max = np.sort(np.array([left, right])) ## proceed to mask curves out = [] for crv in...
0dbea61f7c462d122dbd02b01e3f9aadf74b9d46
3,606,959
import os def filesByCell(fnames,cells): """given files and cells, return a dict of files grouped by cell.""" byCell={} fnames=smartSort(fnames) days = list(set([elem[:5] for elem in fnames if elem.endswith(".abf")])) # so pythonic! for day in smartSort(days): parent=None for i,fna...
e81d527d6c8deef709f92705e25744b7e44d91d9
3,606,960
from typing import List def get_characters_surrounding_index(password: str, index: int) -> List[str]: """ :param password: str :param index: int, index representing index from param password :return: list in form [str, optional str] where first index is character before the param index and the second ...
c78610300092d46fcc9ed171279f0025188cb98c
3,606,961
import re def param_name_is_valid(p, q): """Checks correct formatting of parameter name. Markup allowed: <> <{}> <[]> <()> Characters allowed: $,a-z,A-z,0-9,\-,_ :param p: pre-processed parameter name for JS <script> compatibility :param q: original parameter name in template :return: ""...
2415f0a198518f113fcfe10a671b9225619eb978
3,606,962
def count_words(s, n): """Return the n most frequently occuring words in s.""" # TODO: Count the number of occurences of each word in s words = {} for word in s.split(' '): if word in words: words[word] += 1 else: words[word] = 1 # TODO: Sort the occ...
6c28605fa5d17b36683fc941aa332b3fb3c5aeef
3,606,963
def HasTargetArch(): """Returns True if the user specified an architecture to compile for.""" return HAS_TARGET_ARCH
7b6917159853541881f7dff322c30fdcc7e476e9
3,606,964
def instance_has_suspended(instance, log_files, alarms, event_logs, alarm_history, start_datetime, end_datetime, action=False, guest_hb=False): """ Returns true if the instance has suspended """ success, reason = instance_is_suspended(instance) i...
9fcb0e394d94c3e2feb7f35c68dcbd26d5c6388b
3,606,965
def frame_predicate_distribution(collections, xlsx_path, output_folder, json_path, start_from_scratch=False, verbose=0): """extracts a d...
667d5f12e3ac36862c9033757b97de7130f72d16
3,606,966
import struct import hmac import hashlib import base64 def to_wire(message, secret=None): """Convert a message from dictionary format to wire format If the secret is not None, it will be used to sign the message. """ # Ensure there's no _auth section in the message message.pop('_auth', None) ...
1e6e38d80a311b38c4d2b9abbc0289f961498317
3,606,967
def clip_raster (in_raster, out_raster, extent, datatpye=gdal.GDT_Float32): """Clip a raster to extent Parameters: in_raster: path input raster file out_raster: path output raster file extent: tuple (minX, maxY, maxX, minY) """ tiff = gdal.Translate( out...
8b4dab0c624659ade9222a21abed590ea7f616bf
3,606,968
from django.http import HttpResponse from django.utils import simplejson from .decorators import _JSON_MIME_TYPE def render_to_json_response(data, **kwargs): """ Render data as JSON. :param encoder: custom `JSONEncoder` subclass to serialize additional types. This argument is an alias to `cls...
cad946b19353b82a05c6535361e354e8035336ce
3,606,969
import requests def query_registry( registry_session, image: ImageName, digest=None, version='v1', is_blob=False ) -> requests.Response: """Return manifest digest for image. :param registry_session: RegistrySession :param image: ImageName, the remote image to inspect :param digest: str, digest of...
d2e6653d1b0da1c919a561a73d1dd82ecc376893
3,606,970
import torch def data_loader(pcap_file, statistic_file, label_file, trimed_file_len, batch_size=256, workers=1, pin_memory=True): """读取处理好的 npy 文件, 并返回 pytorch 训练使用的 dataloader 数据 Args: pcap_file (str): pcap 文件转换得到的 npy 文件的路径 statistic_file (str): 统计特征对应的 npy 文件路径 label_file (str): 上面...
56e240031bcd7f0938b8dd5a0abd859582f44963
3,606,971
def TriclosestPoint(TRI, P): """[Calculate the distance of a given point P from a triangle TRI.] Args: TRI ([[P1;P2;P3]]): [The triangle is a matrix # formed by three rows of points TRI = [P1;P2;P3] each of size 1x3] P ([P0 = [0.5 -0.3 0.5]]): [Point P is a row vector of the form 1x3] """...
ea2c77fd470f76193f21834a1b6b76dd71f25875
3,606,972
def sample_labels(labels, num_samples, label_value, ignore_label=-1): """sample N labels with label value = sample_labels Args: labels(Tensor): shape of label is (N,) num_samples(int): label_value(int): Returns: label(Tensor): label after sampling """ assert labels....
923a762162a8136845abf7e41f6737b8aa06bd99
3,606,973
def get_settings() -> Settings: """get_settings() -> ahkpy.Settings Return the current settings for the active thread. """ try: return _current_settings.get() except LookupError: settings = default_settings.copy() _current_settings.set(settings) return settings
985ec62c5bfdcfcb848a96cf49b9eef1b2c4176c
3,606,974
def from_note_representation( array: ndarray, resolution: int = DEFAULT_RESOLUTION, program: int = 0, is_drum: bool = False, use_start_end: bool = False, encode_velocity: bool = True, default_velocity: int = 64, ) -> Music: """Decode note-based representation into a Music object. Pa...
5c2e89caece939130a21625b5d9dbee268efa3c1
3,606,975
def string2number(i): """ Convert a string to a number Input: string (big-endian) Output: long or integer """ return int(i.encode('hex'),16)
ced0537bea856822da630b565cfdeef2c22d1d8a
3,606,976
import os def data_import(foamfile_path): """input a list of filenames to be pulled, put out an array of temperature data. search the foamfiles directory for fnames that start with case_ and tally the number for looping through the file. loop through each and pull data from the files (3) convert to numpy arrays (...
6de50542f05407c81ade821824253b754ed1550c
3,606,977
def j(x, w, y, alpha=0): """The loss function, the aim of LogisticRegression is to minimize it. """ scores = h(x, w) log_score = np.log(scores) log_one_min_h = np.log(1 - scores) log_score[y == 0] = 0 log_one_min_h[y == 1] = 0 trimed_biases = bias_to_0(w) data_loss = (-np.sum(log_score +...
7d05f1082eea000b268119ebf5cf35e4c5e94467
3,606,978
def _process_group(group, window): """Find the patterns from given group. Args: group: Group of note pairs to find the patterns from. window: the number of notes there can be in between consecutive notes of a pattern. Notes played at the same time are counted as "one note". Returns: The patterns in the...
33ffa3b9384378d3ce374a95dd13527b5d37f802
3,606,979
def get_reference_data(p): """Summarise the bibliographic data of an article from an ADS query Returns dict of 'author' (list of strings), 'title' (string), and 'ref' (string giving journal, first page, and year). """ data = {} try: data['author'] = p.author except: data['author'] =...
f8f792d15bade96881e87c3a7e1047dddc125d15
3,606,980
import os def print_sim_datas(fname): """Read simulation results from HDF5 file. Parameters ---------- fname : str the file to read. Returns ------- results : dict[str, any] the result dictionary. """ if not os.path.isfile(fname): raise ValueError('%s is n...
2523084e261f41b3ac097a36aa814b92d8041f8f
3,606,981
def Add211(x, y, precision=None): """ Multi-precision Addition (2sum) HI, LO = x + y TODO: missing assumption on input order """ zh, zl = generate_twosum(x, y, precision) return zh, zl
ad89268edf4b15b60b0581258f5d8479d3c7071a
3,606,982
def generate_junit_result(logdata): """ Generate results in JUnit format for Jenkins from the log data written by application <testsuite> <testcase classname="foo" name="ASuccessfulTest"/> <testcase classname="foo" name="AnotherSuccessfulTest"/> <testcase classname="foo" name="AFailingT...
d2ef152399f08165e923a17575db952581a5209b
3,606,983
import os import tqdm def load_images(path, n_jobs=12, rgb=False, uCT=False): """ Loads multiple images from directory and stacks them into 3D numpy array Parameters ---------- path : str Path to image stack. axis : tuple Order of loaded sample axes. n_jobs : int N...
985d36eaf3f85e1a7ddb08818016a324048c638c
3,606,984
import warnings import re import requests import os def get_notebook_filepath(): """ Returns the filesystem path of the Jupyter notebook running the Client. This implementation is from https://github.com/jupyter/notebook/issues/1000#issuecomment-359875246. Returns ------- str Raises ...
d9d6a99969606f7a183abc89b5223600dccd1aaa
3,606,985
def getGoldTradePartners(playerOrID): """ Returns a list of CyPlayers that can trade gold with <player>. """ return getTradePartnersByTeam(playerOrID, lambda fromTeam, toTeam: fromTeam.isGoldTrading() or toTeam.isGoldTrading())
8ea901bbeb4297972222b5602aec012326f4907b
3,606,986
from functools import reduce def build_stream_function(*funcs): """ 构建流处理函数 函数参数更严格 只接受一个参数 d 字典值 函数执行的顺序是从左到右 :param funcs: :return: """ return reduce(lambda f, g: lambda d: g(f(d)), funcs)
0f09c3f39e8a469f60748a60da5013cfb2cc3758
3,606,987
def is_url(path): """Test if path represents a valid URL string. :param str path: Path to file. :return: True if path is valid url string, False otherwise. :rtype: :py:obj:`True` or :py:obj:`False` """ try: parse_result = urlparse(path) return all((parse_result.scheme, parse_res...
bf3d5959a376d4e8242a602d3d5ac7cc1f00dee7
3,606,988
import os def from_strehl(strehl_file, header_kws=default_keys): """ Gets NIRC2 header data based on contents of a Strehl file. strehl_file: string, path to Strehl file header_kws: header keywords to pull from NIRC2 data files returns: dataframe with Strehl and NIRC2 data """ # Get direct...
add74ddf71ea0cc7ce54b19a2d25f2567504c7a7
3,606,989
import socket def addresses(private_only=True): """Returns a tuple of all non-local ip addresses.""" results = set() for interface in netifaces.interfaces(): addrinfo = netifaces.ifaddresses(interface) for address in addrinfo.get(socket.AF_INET, []): addr = address.get("addr")...
37d4a667333f3a8c83e5b712dd96596d1b656a23
3,606,990
import numpy def cartesian_to_spherical(vectors): """ Return the spherical coordinates for coordinates in Cartesian space. This function does an opposite to :func:`spherical_to_cartesian`. :param vectors: Array of 3d vectors in Cartesian space of shape (..., 3) :returns: Tuple of...
2b82ea26d4cea8c03b860621349c832eb76f24b1
3,606,991
def referencejunctions(uid): """Returns the genereated reference junction points as geojson. This can be used to display the generated reference junction points in a leaflet.js map. """ uid = uid.encode('ISO-8859-1') try: data = db.engine.execute('SELECT row_to_json(fc) FROM ( SELECT \'Featu...
02daebb3d3528d4c717fd6391698afcdd62a14b0
3,606,992
from typing import Optional from typing import Dict from typing import Union def get_column_validation_method( header: str, values_profile: Optional[Dict[str, Dict[str, Dict]]] = get_values_profile() ) -> Union[None, str]: """ Indicates how to validate the values in a given column, according to the ...
f68ea9df299f38f3d406bb8157d9b190088d10d1
3,606,993
def get_current_override_configs(): """Get and return all override definitions""" return Response(str(override_resource_config), status=200, mimetype='application/plaintext')
24274f7854a0ee706e7b6f53eedb14289ea9db91
3,606,994
import os def epfl_deconv_data(channel: int, verbose: bool = False, cache_path: str = None) -> Array: """Get deconvolution problem data from EPFL Biomedical Imaging Group. If the data has previously been downloaded, it will be retrieved from a local cache. Args: channel: Channel number betwe...
076f77931610bb946b649874686f3eada234a7d7
3,606,995
def get_container_by_name(context, container_type, container_name): """Return a container. :param context: The security context :param container_type: The container type :param container_name: The name of a container. :returns: A container. """ return _get_dbdriver_instance().get_container_...
5586cf0ef5be4f2c08c080a88333a599d107a164
3,606,996
def slowparts(d, re, preDz, preWz, SRW, RSW, yxV, xyU, resid): """ computes the linear algebra intensive part of the gradients of the grae """ fprime = lambda x: 1 - power(tanh(x), 2) partialDU = zeros((d+1, re, 2*d, d)) for k in range(2*d): for i in range(d): partialDU[:,:,k,i]...
898dbad6cb7f1737fbf75425ef15560125c2a6f4
3,606,997
import os def is_locked(filepath): """Checks if a file is locked by opening it in append mode. If no exception thrown, then the file is not locked. """ locked = None file_object = None if os.path.exists(filepath): try: print("Trying to open", filepath) buffer_si...
fb3aeed3f350c19c94a004c95faa9dea12d91ee5
3,606,998
import torch def sample_grid(fm, bbox, sample_size): """ :param fm: tensor(b,c,h,w) the global feature map :param bbox: list [b* nparray(x1, y1, x2, y2)] the (x1,y1) is the left_top of bbox, (x2, y2) is the right_bottom of bbox there are in range [0, 1]. x is corresponding to width dimension and y is ...
11276994c3c1127b27dcd463dcf26f462d98fc75
3,606,999