content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_hdf_filepaths(hdf_dir): """Get a list of downloaded HDF files which is be used for iterating through hdf file conversion.""" print "Building list of downloaded HDF files..." hdf_filename_list = [] hdf_filepath_list = [] for dir in hdf_dir: for dir_path, subdir, files in os.walk(dir):...
a64aa83d06b218a0faf3372e09c2ac337ce106aa
14,306
def mask_depth_image(depth_image, min_depth, max_depth): """ mask out-of-range pixel to zero """ ret, depth_image = cv2.threshold( depth_image, min_depth, 100000, cv2.THRESH_TOZERO) ret, depth_image = cv2.threshold( depth_image, max_depth, 100000, cv2.THRESH_TOZERO_INV) depth_image = np....
39fde62083666a9bb4a546c29aa736a23724e25f
14,307
def prompt_for_password(prompt=None): """Fake prompt function that just returns a constant string""" return 'promptpass'
49499970c7698b08f38078c557637907edef3223
14,309
def heading(start, end): """ Find how to get from the point on a planet specified as a tuple start to a point specified in the tuple end """ start = ( radians(start[0]), radians(start[1])) end = ( radians(end[0]), radians(end[1])) delta_lon = end[1] - start[1] delta_lat = log(tan(pi/4 +...
97bd69fc308bdf1a484901ad25b415def20f25ee
14,310
def get_frame_list(video, jump_size = 6, **kwargs): """ Returns list of frame numbers including first and last frame. """ frame_numbers =\ [frame_number for frame_number in range(0, video.frame_count, jump_size)] last_frame_number = video.frame_count - 1; if frame_numbers[-1] != last_...
786de04b4edf224045216de226ac61fdd42b0d7b
14,311
def build_xlsx_response(wb, title="report"): """ Take a workbook and return a xlsx file response """ title = generate_filename(title, '.xlsx') myfile = BytesIO() myfile.write(save_virtual_workbook(wb)) response = HttpResponse( myfile.getvalue(), content_type='application/vnd.openxmlf...
c9990c818b45fc68646ff28d39ea0b914e362db1
14,312
def top_k(*args, **kwargs): """ See https://www.tensorflow.org/api_docs/python/tf/nn/top_k . """ return tensorflow.nn.top_k(*args, **kwargs)
0b0a9f250a466f439301d840af2213f6b2758656
14,313
def determine_d_atoms_without_connectivity(zmat, coords, a_atoms, n): """ A helper function to determine d_atoms without connectivity information. Args: zmat (dict): The zmat. coords (list, tuple): Just the 'coords' part of the xyz dict. a_atoms (list): The determined a_atoms. ...
8b2a60f6092e24b9bc6f71e4ad8753e06c2e6373
14,314
def all_of_them(): """ Return page with all products with given name from API. """ if 'username' in session: return render_template('productsearch.html', username=escape(session['username']), vars=lyst) else: return "Your are not logged in"
cee22ba57e108edaedc9330c21caa9cb60968aa5
14,315
def is_blank(line): """Determines if a selected line consists entirely of whitespace.""" return whitespace_re.match(line) is not None
1120d7a70ce5c08eb5f179cd3d2a258af5cd3bc2
14,316
import re import collections import urllib def _gff_line_map(line, params): """Map part of Map-Reduce; parses a line of GFF into a dictionary. Given an input line from a GFF file, this: - decides if the file passes our filtering limits - if so: - breaks it into component elements - de...
555ca7d4ce455563e7230d4b85f4f4404fa839bc
14,317
def smoothEvolve(problem, orig_point, first_ref, second_ref): """Evolves using RVEA with abrupt change of reference vectors.""" pop = Population(problem, assign_type="empty", plotting=False) try: pop.evolve(slowRVEA, {"generations_per_iteration": 200, "iterations": 15}) except IndexError: ...
fd7f7e82e8b029597affd63ec04da3d40c049c98
14,318
def combine_color_channels(discrete_rgb_images): """ Combine discrete r,g,b images to RGB iamges. :param discrete_rgb_images: :return: """ color_imgs = [] for r, g, b in zip(*discrete_rgb_images): # pca output is float64, positive and negative. normalize the images to [0, 255] rgb ...
246653a698c997faffade25405b1dfafb8236510
14,319
def decohere_earlier_link(tA, tB, wA, wB, T_coh): """Applies decoherence to the earlier generated of the two links. Parameters ---------- tA : float Waiting time of one of the links. wA : float Corresponding fidelity tB : float Waiting time of the other link. wB : fl...
0ec19f50d1673f69211ac7af21ab942612fe8a67
14,320
import torch def train( network: RNN, data: np.ndarray, epochs: int = 10, _n_seqs: int = 10, _n_steps: int = 50, lr: int = 0.001, clip: int = 5, val_frac: int = 0.2, cuda: bool = True, print_every: int = 10, ): """Train RNN.""" network.train() opt = torch.optim.Adam...
97c642c0b2849cb530121d914c586bc6ee76a26b
14,321
def simple_lunar_phase(jd): """ This just does a quick-and-dirty estimate of the Moon's phase given the date. """ lunations = (jd - 2451550.1) / LUNAR_PERIOD percent = lunations - int(lunations) phase_angle = percent * 360. delta_t = phase_angle * LUNAR_PERIOD / 360. moon_day = int(delt...
539d407241a0390b140fad4b67e2173ff1dee66c
14,322
def fetch_traj(data, sample_index, colum_index): """ Returns the state sequence. It also deletes the middle index, which is the transition point from history to future. """ # data shape: [sample_index, time, feature] traj = np.delete(data[sample_index, :, colum_index:colum_index+1], history_len-...
da373d3890f2c89754e36f78b78fb582b429109d
14,323
from datetime import datetime def validate_date(period: str, start: bool = False) -> pd.Timestamp: """Validate the format of date passed as a string. :param period: Date in string. If None, date of today is assigned. :type period: str :param start: Whether argument passed is a starting date or an end...
99c76ee2e23beaff92a8ad67bf38b26c5f33f4bd
14,324
import copy def rec_module_mic(echograms, mic_specs): """ Apply microphone directivity gains to a set of given echograms. Parameters ---------- echograms : ndarray, dtype = Echogram Target echograms. Dimension = (nSrc, nRec) mic_specs : ndarray Microphone directions and direct...
91abe86095cab7ccb7d3f2f001892df4a809106b
14,325
def is_string_like(obj): # from John Hunter, types-free version """Check if obj is string.""" try: obj + '' except (TypeError, ValueError): return False return True
cb7682f91009794011c7c663f98e539d8543c8fd
14,326
def divide(): """Handles division, returns a string of the answer""" a = int(request.args["a"]) b = int(request.args["b"]) quotient = str(int(operations.div(a, b))) return quotient
50c48f9802b3f11e3322b88a45068cad7e354637
14,328
def ax2cu(ax): """Axis angle pair to cubochoric vector.""" return Rotation.ho2cu(Rotation.ax2ho(ax))
6f1c6e181d1e25a2bf28605f01d66fa6a8ffcd45
14,329
def define_genom_loc(current_loc, pstart, p_center, pend, hit_start, hit_end, hit_strand, ovl_range): """ [Local] Returns location label to be given to the annotated peak, if upstream/downstream or overlapping one edge of feature.""" all_pos = ["start", "end"] closest_pos, dmin = distance_to_peak_center( ...
87f89a1d392935a008b7997930bf16dda96cf36b
14,331
import torch def actp(Gij, X0, jacobian=False): """ action on point cloud """ X1 = Gij[:,:,None,None] * X0 if jacobian: X, Y, Z, d = X1.unbind(dim=-1) o = torch.zeros_like(d) B, N, H, W = d.shape if isinstance(Gij, SE3): Ja = torch.stack([ ...
87f85a713b72de65064224086d9c4715f704d800
14,333
def isPalindrome(s): """Assumes s is a str Returns True if s is a palindrome; False otherwise. Punctuation marks, blanks, and capitalization are ignored.""" def toChars(s): s = s.lower() letters = '' for c in s: if c in 'abcdefghijklmnopqrstuvwxyz': letters =...
496f5fa92088a5ecb1b99be811e68501513ee3a4
14,334
import logging def compute_irs(ground_truth_data, representation_function, random_state, diff_quantile=0.99, num_train=gin.REQUIRED, batch_size=gin.REQUIRED): """Computes the Interventional Robustness Score. Args: ground_truth_da...
0ff37699367946fa099f4a5a48cbc66d89af8a29
14,336
def Grab_Pareto_Min_Max(ref_set_array, objective_values, num_objs, num_dec_vars, objectives_names=[], create_txt_file='No'): """ Purposes: Identifies the operating policies producing the best and worst performance in each objective. Gets called automatically by processing_reference...
882ba260576550d2c9de20e950594d5369410187
14,337
def edist(x, y): """ Compute the Euclidean distance between two samples x, y \in R^d.""" try: dist = np.sqrt(np.sum((x-y)**2)) except ValueError: print 'Dimensionality of samples must match!' else: return dist
e0b0e586b49bf3e19eafa2cbf271fb3b1ddc2b99
14,338
def allsec_preorder(h): """ Alternative to using h.allsec(). This returns all sections in order from the root. Traverses the topology each neuron in "pre-order" """ #Iterate over all sections, find roots roots = root_sections(h) # Build list of all sections sec_list = [] for r in ro...
0407bd37c3f975ba91a51b3058d6c619813f2526
14,340
def get_func_bytes(*args): """get_func_bytes(func_t pfn) -> int""" return _idaapi.get_func_bytes(*args)
56000602c9d1d98fb1b76c809cce6c3458a3f426
14,341
def balanced_accuracy(y_true, y_score): """Compute accuracy using one-hot representaitons.""" if isinstance(y_true, list) and isinstance(y_score, list): # Online scenario if y_true[0].ndim == 2 and y_score[0].ndim == 2: # Flatten to single (very long prediction) y_true = ...
9745769ac047863b902f0e74f17680f9ccee5a53
14,342
import json from dateutil import tz from datetime import datetime async def get_weather(weather): """ For .weather command, gets the current weather of a city. """ if not OWM_API: await weather.reply( f"`{JAVES_NNAME}:` **Get an API key from** https://openweathermap.org/ `first.`") ...
b93c21eadefa2b4504708ae2663bfdcbf0555668
14,343
def read_table(source, columns=None, nthreads=1, metadata=None, use_pandas_metadata=False): """ Read a Table from Parquet format Parameters ---------- source: str or pyarrow.io.NativeFile Location of Parquet dataset. If a string passed, can be a single file name or di...
0d0e4990e88c39920e380cca315332f7c36f6ee8
14,344
def _export_cert_from_task_keystore( task, keystore_path, alias, password=KEYSTORE_PASS): """ Retrieves certificate from the keystore with given alias by executing a keytool in context of running container and loads the certificate to memory. Args: task (str): Task id of container t...
8ae8a0e1d46f121597d70aff35a26ce15c448399
14,346
def eta_expand( path: qlast.Path, stype: s_types.Type, *, ctx: context.ContextLevel, ) -> qlast.Expr: """η-expansion of an AST path""" if not ALWAYS_EXPAND and not stype.contains_object(ctx.env.schema): # This isn't strictly right from a "fully η expanding" perspective, # but for...
294e9b0e2aa158dc4e8d57917031986f824fd55d
14,347
from sklearn.naive_bayes import GaussianNB from sklearn.metrics import accuracy_score import timeit def NBAccuracy(features_train, labels_train, features_test, labels_test): """ compute the accuracy of your Naive Bayes classifier """ # create classifier clf = GaussianNB() # fit the classifier on the...
c4c6d5a37341a811023bb0040616ebeb1c44be13
14,348
import json def verify(body): # noqa: E501 """verify Verifies user with given user id. # noqa: E501 :param body: User id that is required for verification. :type body: dict | bytes :rtype: UserVerificationResponse """ if connexion.request.is_json: body = VerifyUser.from_dict(co...
76b2ad631dffbf59b1c2ffeb12069983d0540b51
14,349
def load_interface(interface_name, data): """ Load an interface :param interface_name: a string representing the name of the interface :param data: a dictionary of arguments to be used for initializing the interface :return: an Interface object of the appropriate type """ if interface_name n...
e57e0710d5ad5080b2da1f734581d1b205aedc77
14,350
def get_full_word(*args): """get_full_word(ea_t ea) -> ulonglong""" return _idaapi.get_full_word(*args)
8eb45586888fc836146441bb00bc3c3096ea2c5e
14,352
def full_setup(battery_chemistry): """This function gets the baseline vehicle and creates modifications for different configurations, as well as the mission and analyses to go with those configurations.""" # Collect baseline vehicle data and changes when using different configuration settings vehicle ...
9335521ad5a238ab0a566c80d1443cc5c052a37a
14,353
def sph_yn_exact(n, z): """Return the value of y_n computed using the exact formula. The expression used is http://dlmf.nist.gov/10.49.E4 . """ zm = mpmathify(z) s1 = sum((-1)**k*_a(2*k, n)/zm**(2*k+1) for k in xrange(0, int(n/2) + 1)) s2 = sum((-1)**k*_a(2*k+1, n)/zm**(2*k+2) for k in xrange(...
490c31a3311fb922f5d33337aaeb70f167b25772
14,354
def f_bis(n1 : float, n2 : float, n3 : float) -> str: """ ... cf ci-dessus ... """ if n1 < n2: if n2 < n3: return 'cas 1' elif n1 < n3: return 'cas 2' else: return 'cas 5' elif n1 < n3: return 'cas 3' elif n2 < n3: return 'c...
e46c147a5baef02878700e546b11b7ae44b8909a
14,355
def calc_B_effective(*B_phasors): """It calculates the effective value of the magnetic induction field B (microTesla) in a given point, considering the magnetic induction of all the cables provided. Firstly, the function computes the resulting real and imaginary parts of the x and y magnetic induc...
a24ae9330018f9dc24ebbba66ccc4bc4bd79a7cb
14,356
def elision_count(l): """Returns the number of elisions in a given line Args: l (a bs4 <line>): The line Returns: (int): The number of elisions """ return sum([(1 if _has_elision(w) else 0) for w in l("word")])
c031765089a030328d68718577872a6d2f70b88d
14,357
def get_final_df(model, data): """ This function takes the `model` and `data` dict to construct a final dataframe that includes the features along with true and predicted prices of the testing dataset """ # if predicted future price is higher than the current, # then calculate the true futur...
e28f19c5072693872bf17a89cf39cc6afa74517b
14,358
def read_fragment_groups(input_string,natoms,num_channels): """ read in the fragment groups for each channel """ inp_line = _get_integer_line(input_string,'FragmentGroups',natoms) assert inp_line is not None out=' '.join(inp_line) return out
81ae922add4d0c1680bbeb5223ad85a265ac3040
14,359
def pad_tile_on_edge(tile, tile_row, tile_col, tile_size, ROI): """ add the padding to the tile on the edges. If the tile's center is outside of ROI, move it back to the edge Args: tile: tile value tile_row: row number of the tile relative to its ROI tile_col: col number of the tile relative to its...
bf829ead79f6347423dae8f4c534352d648a3845
14,361
def calc_kfold_score(model, df, y, n_splits=3, shuffle=True): """ Calculate crossvalidation score for the given model and data. Uses sklearn's KFold with shuffle=True. :param model: an instance of sklearn-model :param df: the dataframe with training data :param y: dependent value :param n_...
09e646d40b245be543c5183b8c964fe8ee4f699f
14,362
def obter_forca (unidade): """Esta funcao devolve a forca de ataque da unidade dada como argumento""" return unidade[2]
34fe4acac8e0e3f1964faf8e4b26fa31148cf2a6
14,363
from typing import Dict def get_default_configuration(cookiecutter_json: CookiecutterJson) -> Dict[str, str]: """ Get the default values for the cookiecutter configuration. """ default_options = dict() for key, value in cookiecutter_json.items(): if isinstance(value, str) and "{{" not in v...
8a8e3a9b80d3440f1e6031498c210b7b5577aa03
14,364
def random_nodes_generator(num_nodes, seed=20): """ :param int num_nodes: An Integer denoting the number of nodes :param int seed: (Optional) Integer specifying the seed for controlled randomization. :return: A dictionary containing the coordinates. :rtype: dict """ np.random.seed(seed) ...
5fa08ccc2cd3a4c34962a29ca9a7566ca5e64592
14,365
def OpenDocumentTextMaster(): """ Creates a text master document """ doc = OpenDocument('application/vnd.oasis.opendocument.text-master') doc.text = Text() doc.body.addElement(doc.text) return doc
6813f527ced0f1cd89e0824ac10aeb78d06799a4
14,366
def get_visible_desktops(): """ Returns a list of visible desktops. The first desktop is on Xinerama screen 0, the second is on Xinerama screen 1, etc. :return: A list of visible desktops. :rtype: util.PropertyCookie (CARDINAL[]/32) """ return util.PropertyCookie(util.ge...
9fba922a5c83ed4635391f6ed5319fcfe4fd424d
14,367
def spherical_noise( gridData=None, order_max=8, kind="complex", spherical_harmonic_bases=None ): """Returns order-limited random weights on a spherical surface. Parameters ---------- gridData : io.SphericalGrid SphericalGrid containing azimuth and colatitude order_max : int, optional ...
82ef238ef0d72100435306267bf8248f82b70fd8
14,369
def rollback_command(): """Command to perform a rollback fo the repo.""" return Command().command(_rollback_command).require_clean().require_migration().with_database()
abfed20ff8cfa08af084fc8c956ebb8d312c985f
14,370
import numpy def circumcenter(vertices): """ Compute the circumcenter of a triangle (the center of the circle which passes through all the vertices of the triangle). :param vertices: The triangle vertices (3 by n matrix with the vertices as rows (where n is the dimension of the space)). :...
314e7650b6fec6c82880541de32c1378e720c8c8
14,371
def get_ROC_curve_naive(values, classes): """ Naive implementation of a ROC curve generator that iterates over a number of thresholds. """ # get number of positives and negatives: n_values = len(values); totalP = len(np.where(classes > 0)[0]); totalN = n_values - totalP; min_v...
5950c207746c39c4787b3a472c83fbca5599d654
14,373
import re def worker(path, opt): """Worker for each process. Args: path (str): Image path. opt (dict): Configuration dict. It contains: crop_size (int): Crop size. step (int): Step for overlapped sliding window. thresh_size (int): Threshold size. Patches wh...
68b43995cb147bedad7b94c6f4960cef2646ed87
14,374
def RobotNet(images,dropout): """ Build the model for Robot where it will be used as RobotNet. Args: images: 4-D tensor with shape [batch_size, height, width, channals]. dropout: A Python float. The probability that each element is kept. Returns: Output tensor with the computed ...
9bab69a9a0a01436c9b4225ec882231dc561c204
14,375
def cvReleaseMemStorage(*args): """cvReleaseMemStorage(PyObject obj)""" return _cv.cvReleaseMemStorage(*args)
a11985f756672ab7b7c5ed58336daad1a975c0d2
14,376
import typing def GetCommitsInOrder( repo: git.Repo, head_ref: str = "HEAD", tail_ref: typing.Optional[str] = None) -> typing.List[git.Commit]: """Get a list of all commits, in chronological order from old to new. Args: repo: The repo to list the commits of. head_ref: The starting point for i...
57db975d44af80a5c6a8e251842182f6a0f572af
14,378
def return_sw_checked(softwareversion, osversion): """ Check software existence, return boolean. :param softwareversion: Software release version. :type softwareversion: str :param osversion: OS version. :type osversion: str """ if softwareversion is None: serv = bbconstants.SE...
9f7efb06150468e553ac6a066b2c7750fd233d4c
14,380
from re import A import copy def apply( f: tp.Callable[..., None], obj: A, *rest: A, inplace: bool = False, _top_inplace: tp.Optional[bool] = None, _top_level: bool = True, ) -> A: """ Applies a function to all `to.Tree`s in a Pytree. Works very similar to `jax.tree_map`, but its v...
9a4d29546eb47ba4838fccb58f78495411c99e1c
14,381
import requests def imageSearch(query, top=10): """Returns the decoded json response content :param query: query for search :param top: number of search result """ # set search url query = '%27' + parse.quote_plus(query) + '%27' # web result only base url base_url = 'https://api.datam...
4c731b0ead57e5ec4ab290c9afc67d6066cce093
14,382
def pack_inputs(inputs): """Pack a list of `inputs` tensors to a tuple. Args: inputs: a list of tensors. Returns: a tuple of tensors. if any input is None, replace it with a special constant tensor. """ inputs = tf.nest.flatten(inputs) outputs = [] for x in inputs: if x is None...
2801929a1109cd3c416d8b3229399a0a9b73a38f
14,383
def entries_as_dict(month_index): """Convert index xml list to list of dictionaries.""" # Search path findentrylist = etree.ETXPath("//section[@id='month-index']/ul/li") # Extract data entries_xml = findentrylist(month_index) entries = [to_entry_dict(entry_index_xml) for entry_ind...
2fba6699457ca9726d4ce93b480e722bb6c8223d
14,384
def resnet50(): """Constructs a ResNet-50 model. """ return Bottleneck, [3, 4, 6, 3]
197dc833c966146226721e56315d3f12d9c13398
14,385
def build_service_job_mapping(client, configured_jobs): """ :param client: A Chronos client used for getting the list of running jobs :param configured_jobs: A list of jobs configured in Paasta, i.e. jobs we expect to be able to find :returns: A dict of {(service, instance): last_chronos_job} ...
58cdf0a7f7561d1383f8f4c4e4cdd0f46ccfad0c
14,386
def _validate_labels(labels, lon=True): """ Convert labels argument to length-4 boolean array. """ if labels is None: return [None] * 4 which = 'lon' if lon else 'lat' if isinstance(labels, str): labels = (labels,) array = np.atleast_1d(labels).tolist() if all(isinstance(...
6b4f4870692b3c89f2c51f920892852eeecc418d
14,387
def celsius_to_fahrenheit(temperature_C): """ converts C -> F """ return temperature_C * 9.0 / 5.0 + 32.0
47c789c560c5b7d035252418bd7fb0819b7631a4
14,388
import re from datetime import datetime def _parse_date_time(date): """Parse time string. This matches 17:29:43. Args: date (str): the date string to be parsed. Returns: A tuple of the format (date_time, nsec), where date_time is a datetime.time object and nsec is 0. Ra...
2d7f4b067d1215623c2e8e4217c98591a1794481
14,389
def parsed_user(request, institute_obj): """Return user info""" user_info = { 'email': '[email protected]', 'name': 'John Doe', 'location': 'here', 'institutes': [institute_obj['internal_id']], 'roles': ['admin'] } return user_info
773363dc41f599abe27a5913434f88d1a20c131d
14,390
def lastFromUT1(ut1, longitude): """Convert from universal time (MJD) to local apparent sidereal time (deg). Inputs: - ut1 UT1 MJD - longitude longitude east (deg) Returns: - last local apparent sideral time (deg) History: 2002-08-05 ROwen First version, loosely base...
0ba587125c0c422349acf7bb9753b09956fd9bed
14,391
import itertools def strip_translations_header(translations: str) -> str: """ Strip header from translations generated by ``xgettext``. Header consists of multiple lines separated from the body by an empty line. """ return "\n".join(itertools.dropwhile(len, translations.splitlines()))
b96c964502724008306d627d785224be08bddb86
14,393
import random def sample_targets_and_primes(targets, primes, n_rounds, already_sampled_targets=None, already_sampled_primes=None): """ Sample targets `targets` and primes `primes` for `n_rounds` number of rounds. Omit already sampled targets or primes which can be passed as s...
6b73cdadf3016f1dc248deb2625eae1dd620553b
14,394
def getsign(num): """input the raw num string, return a tuple (sign_num, num_abs). """ sign_num = '' if num.startswith('±'): sign_num = plus_minus num_abs = num.lstrip('±+-') if not islegal(num_abs): return sign_num, '' else: try: temp = float(...
46fc5a7ac8e366479c40e2ccc1a33f57a736b343
14,395
from typing import Mapping from typing import Union def _convert_actions_to_commands( subvol: Subvol, build_appliance: Subvol, action_to_names_or_rpms: Mapping[RpmAction, Union[str, _LocalRpm]], ) -> Mapping[YumDnfCommand, Union[str, _LocalRpm]]: """ Go through the list of RPMs to install and chan...
519d09754b18bcabef405f3d39a959b1296d3c6c
14,396
def fit_DBscan (image_X, eps, eps_grain_boundary, min_sample, min_sample_grain_boundary, filter_boundary, remove_large_clusters, remove_small_clusters, binarize_bdr_coord, b...
b32218e6d45dc766d749af9247ee1d343236fef0
14,397
def get_today_timestring(): """Docen.""" return pd.Timestamp.today().strftime('%Y-%m-%d')
f749a5a63f7c55053918eb3f95bb56c2325f4362
14,398
from pathlib import Path import json def load_json(filepath): """ Load a json file :param filepath: path to json file """ fp = Path(filepath) if not fp.exists(): raise ValueError("Unrecognized file path: {}".format(filepath)) with open(filepath) as f: data = json.load(f) ...
657509a50961f7b9c83536a8973884eef5bbed5e
14,399
import requests import random def handle(req): """handle a request to the function Args: req (str): request body """ r = requests.get("http://api.open-notify.org/astros.json") result = r.json() index = random.randint(0, len(result["people"]) - 1) name = result["people"][index]["nam...
7d951443bc5b6f3db86602d635a8c9ce84b703fb
14,400
import hashlib def get_file_hashsum(file_name: str): """Generate a SHA-256 hashsum of the given file.""" hash_sha256 = hashlib.sha256() with open(file_name, "rb") as f: for chunk in iter(lambda: f.read(4096), b""): hash_sha256.update(chunk) return hash_sha256.hexdigest()
d515b6b7b743396240ada8d888b8bfbc4c316373
14,401
def generate_primes(n): """Generates a list of prime numbers up to `n` """ global PRIMES k = PRIMES[-1] + 2 while k <= n: primes_so_far = PRIMES[:] divisible = False for p in primes_so_far: if k % p == 0: divisible = True break ...
4ea29f8dc8dad11bf6c71fcb1dcc6b75b91bece5
14,402
def Convex(loss, L2_reg): """ loss: src_number loss [loss_1, loss_2, ... loss_src_number] """ src_number = len(loss) lam = cp.Variable(src_number) prob = cp.Problem( cp.Minimize(lam @ loss + L2_reg * cp.norm(lam, 2)), [cp.sum(lam) == 1, lam >= 0] ) # prob.solve() prob.so...
f2a6ecc464e2f87684d1537775816d22dc30d837
14,403
from limitlessled.pipeline import Pipeline def state(new_state): """State decorator. Specify True (turn on) or False (turn off). """ def decorator(function): """Decorator function.""" # pylint: disable=no-member,protected-access def wrapper(self, **kwargs): """Wrap...
156b7bbad0a943af6bb4280e4fdb1dde2b6e320a
14,404
def rotTransMatrixNOAD(axis, s, c, t): """ build a rotate * translate matrix - MUCH faster for derivatives since we know there are a ton of zeros and can act accordingly :param axis: x y or z as a character :param s: sin of theta :param c: cos of theta :param t: translation (a 3 tuple) :...
f6e8d6474ba90e3a253229124e0571d67025c818
14,405
def angular_diameter_distance(z, cosmo=None): """ Angular diameter distance in Mpc at a given redshift. This gives the proper (sometimes called 'physical') transverse distance corresponding to an angle of 1 radian for an object at redshift `z`. Parameters ---------- z : array_like In...
694f9fcaa6ce2585315f63e69351ac47589e248c
14,406
def main(stdin): """ Take sorted standard in from Hadoop and return lines. Value is just a place holder. """ for line_num in stdin: # Remove trailing newlines. line_num = line_num.rstrip() # Omit empty lines. try: (line, num) = line_num.rsplit('\t', 1) ...
811e184d9425c1c76681c823b463b99ebde2c25c
14,407
def _ignore_module_import_frames(file_name, name, line_number, line): """ Ignores import frames of extension loading. Parameters ---------- file_name : `str` The frame's respective file's name. name : `str` The frame's respective function's name. line_number : `int` ...
8f3e506e99b32d2945ea665367d5447ef1b05732
14,408
def get_tf_tensor_data(tensor): """Get data from tensor.""" assert isinstance(tensor, tensor_pb2.TensorProto) is_raw = False if tensor.tensor_content: data = tensor.tensor_content is_raw = True elif tensor.float_val: data = tensor.float_val elif tensor.dcomplex_val: ...
f2d62a7ccba252d5c94cd9979eb01a0b44282d4a
14,409
def coth(x): """ Return the hyperbolic cotangent of x. """ return 1.0/tanh(x)
92d490563c8595b8c11334cd38afbf9ef389dfe8
14,411
def param_is_numeric(p): """ Test whether any parameter is numeric; functionally, determines if any parameter is convertible to a float. :param p: An input parameter :return: """ try: float(p) return True except ValueError: return False
b92579ba019389cf21002b63ca6e2ebdfad7d86f
14,412
def convert_graph_to_angular_abstract_graph(graph: Graph, simple_graph=True, return_tripel_edges=False) -> Graph: """Converts a graph into an abstract angular graph Can be used to calculate a path tsp Arguments: graph {Graph} -- Graph to be converted simple_graph {bool} -- Indicates if ...
2f81743824549d8e19f70f1843d6449eb12e7e5d
14,413
def login_to_site(url, username, password, user_tag, pass_tag): """ :param url: :param username: :param password: :param user_tag: :param pass_tag: :return: :raise: """ browser = mechanize.Browser(factory=mechanize.RobustFactory()) browser.set_handle_robots(False) browser.se...
6c906e037a619031eb45bb26f01da71833fa3e41
14,414
async def test_db( service: Service = Depends(Service) ) -> HTTPSuccess: """Test the API to determine if the database is connected.""" if service.test().__class__ is not None: return { "message": "Database connected." } else: return {"message": "Database not connected." }
67e4530af6959fef03f55879ee3781ebf993f11c
14,415
import tqdm def model_fit_predict(): """ Training example was implemented according to machine-learning-mastery forum The function takes data from the dictionary returned from splitWindows.create_windows function https://machinelearningmastery.com/stateful-stateless-lstm-time-series-forecasting-python...
753ca4e90034864e709809cc1bd2f30640554f28
14,416
from functools import partial import multiprocessing as mp import gc def mp_variant_annotations(df_mp, df_split_cols='', df_sampleid='all', drop_hom_ref=True, n_cores=1): """ Multiprocessing variant annotations see variantAnnotations.process_variant_annotations for description ...
8569a4eb82ff04db1bee46b00bbd9eedf8b4d094
14,417
def find_attachments(pattern, cursor): """Return a list of attachments that match the specified pattern. Args: pattern: The path to the attachment, as a SQLite pattern (to be passed to a LIKE clause). cursor: The Cursor object through which the SQLite queries are sent to...
614649f6fd5972b026b191bb1a272e270dedffe5
14,418
def generate_symmetric_matrix(n_unique_action: int, random_state: int) -> np.ndarray: """Generate symmetric matrix Parameters ----------- n_unique_action: int (>= len_list) Number of actions. random_state: int Controls the random seed in sampling elements of matrix. Returns ...
acb5d537762f2f306be8f300845dc6560c1dd121
14,419
def model_fields_map(model, fields=None, exclude=None, prefix='', prefixm='', attname=True, rename=None): """ На основании переданной модели, возвращает список tuple, содержащих путь в орм к этому полю, и с каким именем оно должно войти в результат. Обрабатываются только обычные поля, m2m и generic сюда...
812247543e5f714e0d2ef57cf018b0741679f83e
14,420