content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_test_stat(name): """ Get the test statistic function by name. The following test statistics are supported: - :func:`~pyhf.infer.test_statistics.q0` - :func:`~pyhf.infer.test_statistics.qmu` - :func:`~pyhf.infer.test_statistics.qmu_tilde` Example: >>> from pyhf.infer import uti...
763d018d78b52fd7219be7dc82c3c3d3c6360786
64,353
def avg_last_k_value(energies, k): """ Compute the average of the last k absolute differences between the values of a list. """ diff = [] L = len(energies) for i in range(L - 1,L - (k+1),-1): diff.append(abs(energies[i]-energies[i-1])) return np.mean(diff)
6051dcd659e6166593078fdbc9e7b43f931a1ce3
64,354
def FormatDescriptorToPython(i): """ Format a descriptor into a form which can be used as a python attribute example:: >>> FormatDescriptorToPython('(Ljava/lang/Long; Ljava/lang/Long; Z Z)V') 'Ljava_lang_LongLjava_lang_LongZZV :param i: name to transform :rtype: str """ i...
8d217883603ae9e9c8f282985b456aa97494beba
64,356
def convert_input_data(d): """ Checks if the input data are a astropy.table.Table and if not it converts it to a Table. :param d: The input data :type d: numpy.ndarray, astropy.table.Table :return: The input data as an astropy.table.Table :rtype: astropy.table.Table """ if type(d) is no...
1ae0ed2837f4ea7f620bb9cda77e676ffb1eeccf
64,357
def recode_rangesig(rsig, encode=True, copy=False): """ In - place rsig recoding :param rsig: :param encode: if true encodes to byte representation, otherwise decodes from byte representation :param copy: :return: """ recode_int = crypto.encodeint if encode else crypto.decodeint reco...
581d6a7ac08f9ac5c3d5fab35f6299404300755b
64,358
def sif_view(file, layout_name='fcose'): """ Read graph stored in SIF format using NetworkX and render a visualization of it Parameters ---------- file : str Path to file in sif format layout_name : str Name of layout to use Returns ------- """ return Viz(data=...
3867735c1e0e51461f425268eb627c421a546c7c
64,359
import numpy as np import xarray as xr from ds21grl.misc import month_to_dayofyear,leap_year_test def read_yt_zm_ml_daily(var,level,dir_in,dim): """ read daily zonal-mean yt data on a given model level acro...
ddf02cfb5233bdb981a1cc1497e6fd174bd8589a
64,360
def quantize_evecs(evecs, odf_vertices=None): """ Find the closest orientation of an evenly distributed sphere Parameters ---------- evecs : ndarray odf_vertices : None or ndarray If None, then set vertices from symmetric362 sphere. Otherwise use passed ndarray as vertices Ret...
4138b6bcace476b9f3edc15265953b03c15a657b
64,361
def _get_features(coord, properties, projection, layer, clipped, projected, spacing, id_property, skip_empty_fields=False): """ Return a list of features in an OGR layer with properties in GeoJSON form. Optionally clip features to coordinate bounding box, and optionally limit returned features ...
70ae6255ceffa18ab2f53c99aece1bedaba33d23
64,362
def touche_pressee(keysym): """ Renvoie `True` si ``keysym`` est actuellement pressée. :param keysym: symbole associé à la touche à tester. :return: `True` si ``keysym`` est actuellement pressée, `False` sinon. """ return keysym in __canevas.pressed_keys
d7ef068efcf30c3e30625aab1cc6eb5188564597
64,363
def factoring_visitor(state, primes): """Use with multiset_partitions_taocp to enumerate the ways a number can be expressed as a product of factors. For this usage, the exponents of the prime factors of a number are arguments to the partition enumerator, while the corresponding prime factors are in...
0692d5c2260ca6c98ab874b4a44dc10f3630c57b
64,364
def shortestPath(G, start, end): """ Find a single shortest path from the given start vertex to the given end vertex. The input has the same conventions as Dijkstra(). The output is a list of the vertices in order along the shortest path. """ D, P = Dijkstra(G, start, end) Path = [] whi...
c9adae6620e585b88e48077138af989e6fe545d5
64,365
def impute_values(X_train, X_test, col_names, missing_val, impute_strategy, impute_val=None): """ Impute missing values with either a constant value or statistics using the scikit learn SimpleImputer Parameters - X_train: (pandas dataframe) dataframe with 1 - test_percentage of entries ...
c0a0bfdca7013ebbc361c8600fd1656062bcfaf4
64,366
def delete_get(u_id): """Render a delete form for the logged in user. Login required. Arguments: u_id (int): the id of the desired user. """ return render_template('delete_user.html')
f58217f1c46ae277dffa28bd6c1b888f3a91cce9
64,367
def typed_struct(cls: type[_CSU]) -> type[_CSU]: """A decorator to allow declaring ctypes.Structure subclasses with type annotations instead of _fields_. To use, decorate a Structure subclass with your fields as class-level attributes, using CField annotations or CStr. Omit the _fields_ attribute e...
513c5b84f3466ab1f742e17279cf20e02643afca
64,368
def predict(master, input, center, centers, map_reader = reader): """ Predict the closest clusters for the datapoints in input. """ job = master.new_job(name = 'kcluster_predict', input = input, map_reader = map_reader, map = pre...
6d23915882c1b988134b27d77e837ff37014c9bd
64,369
def start(): """ Display the WebGUI """ return render_template('index.html')
ba34063f338136c5d7ddef40aa77c9df8c3c62dc
64,370
def layer_severity(layers, layer): """Return severity of layer in layers.""" return layers[layer]['severity']
e8a7a95268ddd2d4aa6b5f7fa66d5828016517eb
64,371
def central_difference(x, y): """ Compute the derivative of y with respect to x via central difference. Parameters ---------- x : np.ndarray Array of x values y : np.ndarray Array of y values Returns ------- Tuple containing x values and corresponding y ...
a97e1d6cfac44eb89b7158974d6df5f1017c23d3
64,372
import logging def get_upstream_coords(uSite, uLen, seqlen, feat, children_list, gffdb): """ Subroutine takes upstream site, length, reference sequence length, parent mRNA feature (GffLine object), list of child feature types and a GFFutils.GFFDB object as the input If upstream of TSS is requeste...
30dd59f7a52533804cba9ca4e6307b8d9ed396f0
64,373
def generate_x_y(): """ generates FAKE_SAMPLE_SIZE number of rows of fake images :return: input, vectorized labels, scalar labels """ x_dim = (conf.FAKE_SAMPLE_SIZE, conf.IMAGE_SIZE) y_dim = (10, conf.FAKE_SAMPLE_SIZE) x = np.random.rand(x_dim[0], x_dim[1]) labels = np.random.choice(a=[0, 1, 2, 3, 4, 5...
5023ce089877613dd65479e054492ab18d885fcb
64,375
def bootstrap_se_ci(data, seed, num_samples, statistic, alpha): """ Return bootstrap estimate of standard error of statistic and bootstrap estimate of 100*(1-2*alpha)% confidence interval for statistic in a dictionary along with specified seed and nun_samples (B) and alpha. """ assert isinstance...
206a82efbd99ab81b132ee83da38c27ea5e0db22
64,377
def is_same_res(instance: Instance, result: bool = False, message: str = None) -> bool: """ Return True if solving an instance returns the expected result and False otherwise. """ try: same_res = result == check_satis(instance, get_stats=False) instance.check_model() if inst...
ace142a7e0df4453b6193c76418122bbc2d8bf1a
64,379
from typing import Any from typing import Type import numpy def get_type_uint(obj: Any) -> Type[UInt]: """ Return the NPType that corresponds to obj. :param obj: an uint compatible object. :return: an UInt type. """ return _get_type_of_number(UInt, obj, { numpy.uint8: 8, numpy....
37ea7d91600786fcd1c65ce97768888961ed0995
64,381
def order_verts_by_edge_connection(connected_verts, results=[]): """ Orders connected verts by edge connection. """ next_verts = list( set(results[-1].connectedVertices()) & set(connected_verts) ) for vert in next_verts: if vert not in results: results.append(vert) ...
9f6b8cc6dc4816c4136da234e90924d2a8d2eae5
64,382
def pad(tensor, paddings, mode='CONSTANT', constant_values=0, name=None): """Pads a tensor. This operation pads a `tensor` according to the `paddings` you specify. `paddings` is a list of integers with shape `[n, 2]`, where n is the rank of `tensor`. For each dimension D of `input`, `paddings[D, 0]` in...
6350af57b042a221c3e4dc6be47d40b402d3b834
64,383
def make_gax_metrics_api(client): """Create an instance of the GAX Metrics API. :type client: :class:`~google.cloud.logging.client.Client` :param client: The client that holds configuration details. :rtype: :class:`_MetricsAPI` :returns: A metrics API instance with the proper credentials. """ ...
e23cf70547cbc3a583b0fe2f5cf8dcfd480ded3e
64,384
def create_optimizers(α=0.002, β1=0.0, β2=0.99, ε=K.epsilon()): """ Create n adam optimizers with given hyper-paramaters :param α: alpha / learning rate, default=0.002, paper range (0.0015 - 0.003) :param β1: beta1 for adam optimizer, default = 0.0 :param β2: beta2 for adam optimizer, default = 0.99...
0d7e28a73557a46b912f3070f0850ad9425e2614
64,385
def compute_kth_distance(coords, k=15): """Find the (Euclidean) distance to the `k` th nearest neighbour. :param coords: An array of shape (n,N) of N points in n dimensional space; if n=1 then input is an array of shape (N). :param k: The nearest neighbour to use, defaults to 15, if N is too small ...
9c1b96994ca16cb8f777d2ecfc72e6931cc68f2a
64,386
def get_operating_system_info(**options): """ gets the current operating system info. :returns: dict(str name: os name, str release: os release, str version: os version) :rtype: dict """ return get_component(AuditPackage.COMPONENT_NAME).get_operating_syste...
edcf90205c2e411a653ac80310b05f0543a16536
64,387
def _parse_alt_title(html_chunk): """ Parse title from alternative location if not found where it should be. Args: html_chunk (obj): HTMLElement containing slice of the page with details. Returns: str: Book's title. """ title = html_chunk.find( "input", {"src": ...
bd5df0edfc174653731256d50e0a8f84a6f84880
64,388
def rebin(wl, f, r, bin_siz=15): """ To rebin my flux spectra Parameters ---------- wl : array 1D array containing the wavelengths to be rebinned f : array 1D array containing the fluxes to be rebinned r : array 1D array containing the errors on the fluxes to be rebi...
052221bc28ba1381503ce0e617b48b6b20ae6bd1
64,389
def np2qi(array): """ Convert numpy array to Qt Image. source from: https://kogs-www.informatik.uni-hamburg.de/~meine/software/vigraqt/qimage2ndarray.py :param array: :return: """ if np.ndim(array) == 2: return gray2qi(array) elif np.ndim(array) == 3: return rgb2qi(arra...
c25a11af485b019548ccc6b3ff429dadde63f831
64,390
def load_sxs_waveform(file_name, modes=None, extraction="OutermostExtraction.dir"): """ Load the spherical harmonic modes of an SXS numerical relativity waveform. Parameters ---------- file_name: str Name of file to be loaded. modes: dict Dictionary of spherical harmonic modes t...
f763e562b46022a49273a0c648aec1f48d751e86
64,391
def getChargeURL(request): """ 팝빌 연동회원 포인트 충전 URL을 반환합니다. - 보안정책에 따라 반환된 URL은 30초의 유효시간을 갖습니다. - https://docs.popbill.com/kakao/python/api#GetChargeURL """ try: # 팝빌회원 사업자번호 CorpNum = settings.testCorpNum # 팝빌회원 아이디 UserID = settings.testUserID url = kak...
8bd572814cf285a8de55b614e0d30e7b857ed9c2
64,392
import copy def simulating_y_from_clinical( clinical_sim, var = 'creatinine', simulate_y = False, rep = 30): """Simulate the outcome Y from clinical or mu(x,t). Args: clinical_sim: pd.DataFrame with simulated pi() and mu(). Colnames: 'eid', 'image_id', 'sim_0_pi','sim_0_mu0','sim_0_mu1', ...
9b952e1db32b2ffe5f66cd8d103ec08b144b88d7
64,393
def prompt_worker_amount(cpu_cores: int): """Prompt the user for the amount of Celery workers they want to run. Start 2 less workers than amount of CPU cores by default.""" answer = 0 safe_cores_suggestion = cpu_cores - 2 def invalid_answer(): """Restart prompt if answer invalid""" ...
2f2e4d423eb94d0bf709feda09c5c45ca8cc481a
64,394
from typing import Union def mach_strlen(code_chunk: Union[bytes, MachineCodeBuilder]) -> MachineCodeBuilder: """ push ecx xor ecx, ecx @@: cmp byte [eax+ecx], 0 ; assume that eax contains a string address jz success cmp ecx, 100h jg skip inc ecx ...
15f769f7f60a678204d95590cdbdee0c74d7f77e
64,396
def get_quartiles(df, column_name, df_project, units): """Get the ensemble quartiles""" assert len(df) == len(df_project) quartiles = ['# ' + column_name + ' quartiles'] for project in ['cmip6', 'cmip5']: df_subset = df[df_project == project] upper_quartile = df_subset[column_...
191cfa94ab780172e44892647a7c1f3bdeda8be0
64,397
import threading import functools def glib_idle_add_wait(function, *args, **kwargs): """ Execute *function* in the main GTK loop using :py:func:`GLib.idle_add` and block until it has completed. This is useful for threads that need to update GUI data. :param function function: The function to call. :param args:...
55ad7afe92906f211af3b6e2c8525068178ac83c
64,398
def email_data(): """fields every email needs""" site = models.SiteSettings.objects.get() return { "site_name": site.name, "logo": site.logo_small_url, "domain": DOMAIN, "user": None, }
ebc177c30bb5b5ac3e88cbffe56b33ca91bc2dc3
64,400
def home(sort_type='hot'): """ If not trending we order by creation date """ atom_url = url_for('subreddits.atom_feed', subreddit_name='frontpage', _external=True) trending = True if request.path.endswith('trending') else False page_title = "Trending" if trending else "Frontpage" thread_pagi...
e28f72b0c6d29b94b578833a7282ee6345f6fadc
64,401
def get_path_loss(range_m, freq_hz, tx_ht_m, rx_ht_m, include_atm_loss=True, atmosphere=None): """ Computes the propagation loss according to a piece-wise model where free space is used at close range, and two-ray is used at long range. The cross-over range between the two is the Fresnel Zone. Ported ...
d75be948be368140c0e81cdd969c9dd34125c821
64,402
def get_patch_dims(im, patch_size, patch_position): """ Returns the dimensions of an image patch of size `patch_size`, with its center at `patch_position` expressed as a ratio of the image's H and W * im: np.ndarray of size H x W x C * patch_size: 2-tuple of patch H x W * pa...
a078747b1978f33aed608e2867f9b18f0fd3f811
64,404
def fluent_comments_list(parser, token): """ A tag to select the proper template for the current comments app. """ return FluentCommentsList()
c5d611a772891ada2244953f5589e640dd458fa8
64,405
def getMRotFromNodeOutput(node_mob, rotOrder = om2.MEulerRotation.kXYZ): """ finds the angular output of the argument node and returns it as a Euler rotation where that angle is the X element :param node_mob: [MObject] the node to get the output port from :param rotOrder: [int] the factory constant...
e2f911b760e0a287919cd9967eaf41c7eae26785
64,406
import json def getAll(filepath): """ Get all config value """ with open(filepath, "r", encoding="utf-8") as target: return json.load(target)
450597deb942c9fdbde33ec37c8feee9d2edd1ec
64,407
from typing import Union def filter_vset_by_metric(metric_dict: dict, vset: Vset, *vsets: Vset, n_keep: int = 1, bigger_is_better: bool = True, filter_on=None, group: bool = False) -> Union[Vset, list]: """Returns a new Vset by filtering `vset.modules` based on ...
9b70c1bd1a50df7b164b64a4ad0f473ae256657a
64,408
def safe_div(x: int, y: int): """ Computes x / y and fails if x is not divisible by y. """ assert isinstance(x, int) and isinstance(y, int) assert y != 0 assert x % y == 0, f'{x} is not divisible by {y}.' return x // y
250678a7d6b3b5564ee734a852b17d1cea7ac536
64,410
import time def Timer(): """Returns a Single representing the number of seconds elapsed since midnight""" ltime = time.localtime() h, m, s = ltime[3:6] return h*3600.0 + m*60.0 + s
9e93ac420a439574aaed07520bbd457577dfe3f9
64,411
def format_entry(e): """ Format an entry from the data in the original database to something that uses html """ txt = e.midashigo1 strlen = len(txt) acclen = len(e.ac) accent = "0"*(strlen-acclen) + e.ac # Get the nasal positions nasal = [] if e.nasalsoundpos: positions = e.nasa...
17cbc7270a70cb8bb88ec7faa2295f1f42b041af
64,412
def resnet_model_fn(inputs, training): """Our model_fn for ResNet to be used with our Estimator.""" network = resnet_model.imagenet_resnet_v2( resnet_size=18, num_classes=class_num, mode='se', data_format=None) inputs= network(inputs=inputs, is_training=training) feat = tf.nn.l2_normalize(input...
be238ae34089d39db6f50b7771abf5588e5370ee
64,413
def update_categorygraph_without_scc(categorypages, categorygraph): """Update categorygraph for containing all reachable content without scc. Args: categorypages (Hash[String, Set[String]]): category to page name list dictionary. categorygraph (Hash[String, Set[String]]): category to category l...
bebb98d4992d0db9f652b7b7d80c8499292850c2
64,416
from datetime import datetime def to_datetime(dt_str, format="%Y-%m-%d %H:%M:%S", utc=False): """ utc: False 按当前时区解析,True 按UTC解析 """ try: dt = datetime.strptime(dt_str, format) return _utc_tz.localize(dt) if utc else _local_tz.localize(dt) except Exception: return None
dbdc62b8fce82f12f2a1e6fde32f74da6b7e7f0a
64,417
def dropna_except(df, except_subset, inplace=False): """drop rows containing nans from a Pandas dataframe, but allow nans in the specified subset of columns, in place""" subset = set(df.columns) for ec in except_subset: subset.remove(ec) df = df.dropna(inplace=inplace, subset=subset) ...
708bd3e9cab520f9453cd82d6f36aa8ec8183fc0
64,418
def rf_array_to_tile(array_col: Column_type, num_cols: int, num_rows: int) -> Column: """Convert array in `array_col` into a Tile of dimensions `num_cols` and `num_rows'""" jfcn = RFContext.active().lookup('rf_array_to_tile') return Column(jfcn(_to_java_column(array_col), num_cols, num_rows))
dc879f164567172344206869df3f6a4149e6eb6f
64,419
import six def with_metaclass(meta, *bases, **with_metaclass_kwargs): """Extends the behavior of six.with_metaclass. The normal usage (expanded to include temporaries, to make the illustration easier) is: .. code-block:: python temporary_class = six.with_metaclass(meta, *bases) temp...
80a33fa94d8efa8d770d561ccccab06bfd3fdbf2
64,420
def _timeSlice__compare(self,other): """Compare two time slices, returning tuple (<return code>, <slice>, <comment>), with the larger slice if succesful. If return code is negative, no solution is found. If return code is 2, the slices are disjoint and both returned.""" assert self._h.label == 'timeSlic...
d03b9a4f68c08e232753ae64c52225d8643380d5
64,421
import urllib3 import logging def _SendFileToServer(pool, fullpath, subpath, basename, rebalance): """Sends a specific data store file to the server.""" fp = FileCopyWrapper(rebalance, subpath, basename, fullpath) try: # Content-Length is 0 since we do not know the size of the compressed data. # We wri...
1b5d7be84be6cfac8463e6d62d9491f5084d5e00
64,422
def get_entities_set(domain='gaming', selected=True): """[summary] Keyword Arguments: domain {str} -- [description] (default: {'gaming'}) """ entities = [ 'Badges', 'Comments', 'PostHistory', 'PostLinks', 'Posts', 'Tags', 'Users', 'Votes'] meta_path_template = 'raw\\{0}\\m...
114bef412767f228a11066c90b63d971fb604a3d
64,423
def amp2db(amp, ref=1): """Conversion of an amplitude value into dB Parameters: ----------- amp: np.array amplitude values to be converted ref: float reference value """ if ref == 0: raise ValueError("Reference must be different from 0") elif ref != 0: d...
d54b8fcd8840f22c80600e86e3de2504f72f5847
64,424
def promote_dtypes(dt1, dt2): """ >>> from datashape.coretypes import int32, int64, float32 >>> promote_dtypes(int32, int64) ctype("int64") >>> promote_dtypes(int64, float32) ctype("float64") """ if dt1 == dt2: return dt1 elif isinstance(dt1, CType) and isinstance(dt2, CTyp...
63fde49f279bf628daec6115ac6d0fe26db79c1b
64,425
def convert_s3_url_to_http_url(s3_url): """Convert s3 url to http url. Converts the S3 URL s3://bucket-name/object to HTTP URL https://s3.amazonaws.com/bucket-name/object. Args: s3_url Returns: http url Raises: """ u = urlparse(s3_url) s3bucket = u.netloc s3ke...
c4ea7e64eb1e7e05ee6373e6f013c88c58955014
64,427
def GaussianKernel(shape=(3, 3), sigma=0.5): """ 2D gaussian kernel which is equal to MATLAB's fspecial('gaussian',[shape],[sigma]) """ radius_x, radius_y = [(radius-1.)/2. for radius in shape] y_range, x_range = np.ogrid[-radius_y:radius_y+1, -radius_x:radius_x+1] h = np.exp(- (x_range*x_range ...
e39d0f0d446318075b1d7769327fda19ddb9f443
64,429
def quiz_models(directory, test, labels, visualize=False, capsnet=False, eval_model=None, train_df=None): """Loads models from directory and runs the quiz on them. If capsnet, eval_model must be passed in.""" model_directory = './models' + directory[1:] print('\nquizzing best accuracy model...\n') i...
90a1cdbba7a68114eaa24a0ef6b5d3ac102fabbf
64,430
from datetime import datetime import math def pretty_date(iso_datetime): """ Takes an ISO time and returns a string representing how long ago the date represents. Ported from PrettyDate by John Resig """ if not iso_datetime: return '' if isinstance(iso_datetime, basestring): iso_datetime = datetime.strp...
2af9917f001b3400fe479ad8b80edb4f86b4a89a
64,431
from typing import Dict from typing import cast def _double_cross_over_cz( op: ops.Operation, held_w_phases: Dict[ops.Qid, value.TParamVal] ) -> 'cirq.OP_TREE': """Crosses two W flips over a partial CZ. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ──...
9df193afd7329cb760926edf2770049d723b91ca
64,432
def fj_load_df_from_csv(dir, file): """ Load dataframe from csv file Input: dir: directory for csv file file: csv file Returns: Pandas dataframe corresponding to processed and saved csv file """ df = pd.read_csv(dir + file) print(df.describe()) print ('NAs in data') print(df.isna().sum()) return...
a8849aa47c309ebbade587a17c5867dfc3acb192
64,434
def band_element_orbital_spin_polarized( folder, element_orbital_dict, output='band_element_orbital_sp.png', display_order=None, scale_factor=5, color_list=None, legend=True, linewidth=0.75, band_color='black', unprojected_band_color='gray', unprojected_linewidth=0.6, fon...
2bb2c6a8049da26718004ed667643bf6cfc0194f
64,435
def func_c(c,d_h,d_w,st_h,st_w,par): """ utility function for couples""" # high skilled hs_h = transitions.state_translate(st_h,'high_skilled',par) hs_w = transitions.state_translate(st_w,'high_skilled',par) # initialize to both working (then overwrite if not) alpha_h = 0.0 phi...
be6b2fe346bc6e7de7ae013f11d3b098925fba56
64,436
def assign_submit(): """Finalize assignment of assignments to a session with a due date""" if request.method == 'POST': # Get all the necessary form data date = request.form['date'] assign_id = request.form['assign_id'] session_id = request.form['session_id'] # Validate ...
ec6287f8dec81259db74d4f039165f64e8f427c7
64,437
def loadGiftiVertexData(filename): """Loads vertex data from the given GIFTI file. See :func:`prepareGiftiVertexData`. Returns a tuple containing: - The loaded ``nibabel.gifti.GiftiImage`` object - A ``(M, N)`` numpy array containing ``N`` data points for ``M`` vertices """ g...
4368e394a1bacaf8709f5b294ef39ec5d9359fd0
64,438
import requests def ehld_stids(): """ Retrieves a list of high-level hierarchy pathway with Enhanced High Level Diagrams (EHLD) https://reactome.org/icon-info/ehld-specs-guideline :return: list of pathway stIds """ url = "https://reactome.org/download/current/ehld/svgsummary.txt" try: ...
4bd4af4f7ed78c47b1b4431f958e7d790da0f068
64,439
def _split_lobster_filename(filename): """ splits the LOBSTER-type filename into Ticker, Date, Time Start, Time End, File Type, Number of Levels """ filename2,_ = filename.split(".") ticker_str, date_str, time_start_str, time_end_str, file_type_str, num_levels = filename2.split("_") return ticker_str,...
ae4e11cc653b345c780b33902b740f6b7cb707f6
64,440
def image(x, y, path, width=None, height=None): """ Draws and returns an :py:class:`~jygsaw.image.Image`. :param x: x-coordinate of upper-left corner. :type x: int :param y: y-coordinate of upper-left corner. :type y: int :param path: Internet URL or local file path to the image. :type ...
68cc93e7571c587bb7f21e135d844974150cd681
64,441
def project(points, camera_params): """Convert 3-D points to 2-D by projecting onto images.""" assert camera_params.shape[1] == 14 points_proj = rotate(points, camera_params[:, :3]) points_proj += camera_params[:, 3:6] points_proj = points_proj[:, :2] / points_proj[:, 2, np.newaxis] fx = came...
469ba74c735077f0410c9b1a1159a965900d4499
64,442
def ordinal_filter(num): """ Format a number as an ordinal. """ num = int(num) if 10 <= num % 100 <= 20: suffix = 'th' else: suffix = ORDINAL_SUFFIXES.get(num % 10, 'th') return unicode(num) + suffix
e139f9f7b8d8802550ef64dc3e5a06544f4a5568
64,443
def tab_delimited(list_to_write): """Format list of elements in to a tab-delimited line""" list_to_write = [str(x) for x in list_to_write] return '\t'.join(list_to_write) + '\n'
921a3316f01aecaba1efb43c524b1ad5cca89546
64,445
import time def six_hump_camel_simple(x, persis_info, sim_specs, _): """ Evaluates the six hump camel function for a single point ``x``. :See: ``/libensemble/libensemble/tests/regression_tests/test_fast_alloc.py`` """ O = np.zeros(1,dtype=sim_specs['out']) O['f'] = six_hump_camel_fu...
0341d5b7c8977acb171c75cf053c70bd6f097677
64,446
from typing import Optional def argwhere_op(x, dtype: Optional[flow.dtype] = None): """This operator finds the indices of input Tensor `x` elements that are non-zero. It returns a list in which each element is a coordinate that points to a non-zero element in the condition. Args: x (oneflow.Ten...
20dd69bdc71243f94bd50316c843d9e8db63727e
64,448
from gdsfactory.pdk import get_layer def strip( wg_width: float = 0.5, layer: LayerSpec = "WG", layer_cladding: LayerSpec = "WGCLAD", radius: float = 10.0, cladding_offset: float = 3.0, euler_bend: bool = True, wg_type: str = "strip", ) -> WaveguideTemplate: """ wg_type: strip, slo...
3633ce54efb11c0c039d84db44c8ea2682a49e4d
64,449
def ImageScaler(max_scale_power=1): """ Возвращает keras.layer преобразующий батч входных изображений в [images, images // 2, images // 4, ..., images // 2**max_scale_power] список изображений в разных масштабах ("//" выше обозначает перемасштабирование а не деление) :param max_scale_power: сколько ...
03a9e78d3e26c73455416db4e77d21e25a9f66e9
64,450
import six def render_path(path_to_item): """Returns a string representation of a path""" result = "" for pth in path_to_item: if isinstance(pth, six.integer_types): result += "[{0}]".format(pth) else: result += "['{0}']".format(pth) return result
bf9c9b40d8c6357813cb329c1dcb611aba45eacc
64,451
import multiprocessing def clusterpolate(points, values, targets, radius=1, kernel_factory=bump, neighbors=None, num_jobs=None): """ Clusterpolate data. ``points`` (array-like) are the data points and ``values`` (array-like) are the associated values. ``targets`` (array-like) are ...
689f7273e9aa2c9dd4c5c957018f8c990d565d16
64,453
def letter_frequency_dict(text, alphabet = None, # {{{1 precision = FREQ_PRECISION): """Calculates letter frequencies.""" if alphabet is None: alphabet = ALPHAS freqs = dict(izip(alphabet, [0]*len(alphabet))); n = float(len(text)) if not text: return freqs for c in tex...
604d1b47897b4c82ab8aa2a7f231a9f3c5b6c2d5
64,454
def discounts(num_steps: int, discount: float) -> np.ndarray: """Return the discounts array $[1., \\gamma, \\gamma^2, \\ldots]$. :param num_steps: size of the output array :param discount: discount factor :rtype: (N,) np.ndarray of discounts """ checkraise(num_steps > 0, ValueError, 'invalid ...
75b862e599ba4719550de8087ebd02e34c2bbd72
64,455
def compute_lognorm_cdf(hist, bins='', params=False, plot=False, ax=None): """ Returns a fitted CDF of a lognormal distribution, from a given histogram of distances If params=True, returns the parameters of the fitted lognorm """ if bins == '': bins = [i*2 for i in range(len(hist)+1)] db = b...
0b81145a2154ee7f31e404d17f7396c718aa188a
64,456
def random_prime(num_digits, is_prime = miller_rabin): """ Returns a random prime with num_digits digits. Input: num_digits -- a positive integer is_prime -- (optional argment) a function of one argument n that returns either True if n is (probably) ...
05a6dbd0da078dca2be40c0133f0f39bcc8a0e04
64,457
def remove_outliers_mad( *, data, threshold=2.5, fill_value='interpolate', rolling=False, window='1H', dist_const=1.4826 ): """ Outlier removal by robust median estimator. Remove outliers of a DataFrame or Series based on the (rolling) median of the difference of the data to...
302ffcd5b37a5b6a8f3144fd514f43dbee65c904
64,458
def diff_to_wfp(diff, md5, src_path): """ This function converts a parsed diff data structure into WFP Parameters ---------- diff : dict A dictionary containing as keys the filenames contained in the diff and as values its contents stored as a list of strings. md5 : str src_path : str Path t...
bcd31fca4bd5cbdd3fb12270b232245797b90107
64,459
def az_to_polar(x, y): """Convert azimuthal x,y to polar co-ordinates""" lat = -np.sqrt((x**2)+(y**2)) * np.pi + np.pi/2 lon = np.arctan2(-y,x) return lon, lat
3524ec9c3f38eccc96622060dde943b5fb4364ed
64,460
def get_node_continuous_info(node_name): """ 根据node_name 返回一段时间内的连续信息 :param node_name: :return: """ continuous_info = r.lindex(node_name, 0) continuous_dict = ast.literal_eval(continuous_info) return_data = {} return_data["data"] = continuous_dict return_data["status"] = 100 ...
4376c23d102160526229b27d17755aad00a91182
64,461
def parse_datetime(dt, ignoretz=True, **kwargs): """ :param dt: string datetime to convert into datetime object. :return: datetime object if the string can be parsed into a datetime. Otherwise, return None. :see: http://labix.org/python-dateutil Examples: >>> parse_datetime('2011-12-3...
d45cc5ae7c33533111498511e13be362579d3126
64,462
def route_remove_group_member(): """Remove a group member""" group = _lookup_group_from_request() member = request.json.get('member') user = get_user(username=member) remove_group_member(group, user) return make_json_response(removed=user.get_public_dict())
ef146e12da3bcb47ed8203ab943bedf6fbafe0fe
64,463
def get_watermark_for_topic( kafka_client, topic, ): """This method: * refreshes metadata for the kafka client * fetches watermarks :param kafka_client: KafkaToolClient instance :param topic: the topic :returns: dict <topic>: [ConsumerPartitionOffsets] """ # Refresh clie...
83e10f30bd2f97af0646651854663bcbd879114c
64,464
def render_placeholder_info(context, **kwargs): """Render the list of available placeholders. :param context: the context where the placeholders are used :param kwargs: arguments specific to the context """ placeholders = sorted(list(get_placeholders(context, **kwargs).values()), key=attrgetter('na...
75f47fa5781acd9c601dec67d8232e1278ee3045
64,465
def transform_data(data, verbose=False): """Transform the input data to be used by prediction. Args: data (list or dataframe): Input data in a list or dataframe with column name `sequence`. verbose (bool, optional): Whether to print out statistics of input protein sequen...
16858ac496c3c29e33c9cd990cfbd48349379b50
64,466
def _unadvertise(name): """Remove the advert for a name This is intended for internal use only at the moment. When a process exits it can remove adverts for its services from the beacon running on that machine. (Of course, if the beacon thread is part of of the same service, all its adverts will ce...
9ad38ba689637ac128af12bda9f7f50696331565
64,467
def PrintIOConversions(*args): """ PrintIOConversions(os=std::cout) PrintIOConversions() """ return _Ravl.PrintIOConversions(*args)
fe30aa3bf0694db33b363087aa22f131ec690f1a
64,468
def create_mask(mask_type, h, w): """ create mask according to shape """ mask = np.zeros((h, w, 3)) coords = shape_coords(h, w, mask_type) for i in range(h): for j in range(w): if in_polygon(i, j, coords): mask[i, j, :] = 1 return mask
39f34e2cb1a8c46c94ed1c2f05277302d7367f99
64,469