content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def check_records(msg: dict) -> int: """ Returns the number of records sent in the SQS message """ records = 0 if msg is not None: records = len(msg[0]) if records != 1: raise ValueError("Not expected single record") return records
7036f943b733ca34adaaa5ff917b3eb246075422
24,800
def get_processes_from_tags(test): """Extract process slugs from tags.""" tags = getattr(test, 'tags', set()) slugs = set() for tag_name in tags: if not tag_name.startswith('{}.'.format(TAG_PROCESS)): continue slugs.add(tag_name[len(TAG_PROCESS) + 1:]) return slugs
16d333d1371ab533aa5ed7a26c4bdd968233edf9
24,801
from src.common_paths import get_submissions_version_path import logging import os import json def get_best_score(version): """ Given an existing version, retrieves the alias and score of the best score obtained :param version: version to be evaluated (str|unicode) :return: alias, score (str, float) ...
fa5a69da36ec439027212928f74992387e3be277
24,802
import random def eight_ball(): """ Magic eight ball. :return: A random answer. :rtype: str """ answers = [ 'It is certain', 'It is decidedly so', 'Not a fucking chance!', 'without a doubt', 'Yes definitely', 'I suppose so', 'Maybe', ' No fucking way!', 'Sure :D', ...
728aea44a111a25d878ec7686038d993fe49f71c
24,803
def head(line, n: int): """returns the first `n` lines""" global counter counter += 1 if counter > n: raise cbox.Stop() # can also raise StopIteration() return line
221f8c6ac5a64b5f844202622e284053738147aa
24,804
def onehot(x, numclasses=None): """ Convert integer encoding for class-labels (starting with 0 !) to one-hot encoding. If numclasses (the number of classes) is not provided, it is assumed to be equal to the largest class index occuring in the labels-array + 1. The output is an array...
6595ef4fc837296f6ba31c78a4b3047aaca7ee49
24,805
import numpy def draw_graph(image, graph): """ Draw the graph on the image by traversing the graph structure. Args: | *image* : the image where the graph needs to be drawn | *graph* : the *.txt file containing the graph information Returns: """ tmp = draw_edges(image, graph)...
2454e654969d766af60546686d9c305c67199c8a
24,806
def valid_octet (oct): """ Validates a single IP address octet. Args: oct (int): The octet to validate Returns: bool: True if the octet is valid, otherwise false """ return oct >= 0 and oct <= 255
9dd2346bb5df5bc00bb360013abe40b8039bdc45
24,807
def load_clean_dictionaries(): """ is loading the combilex data into two dictionaries word2phone and phone2word :return: g2p_dict, p2g_dict """ grapheme_dict = {} phonetic_dict = {} with open(COMBILEX_PATH, encoding='utf-8') as combilex_file: for line in combilex_file: ...
ab7257c78ec8ba0786a0112362ba318468e69e02
24,808
import traceback import itertools import operator def build_missing_wheels( packages_and_envts, build_remotely=False, with_deps=False, dest_dir=THIRDPARTY_DIR, ): """ Build all wheels in a list of tuple (Package, Environment) and save in `dest_dir`. Return a list of tuple (Package, Environ...
261433deb7bc691f92d995d606e108a807201b97
24,809
import os def load_reads(path, format='bed', paired=False, shift=100, name=None): """Read reads from file. Parameters ---------- path : str Path to load the reads. format : str, optional File format, default='bed'. paired : bool, optional Whether the reads are paired-e...
43595ad806ebf00513841b8324ccb19263333cb6
24,810
import modulefinder def sketch_blocks(modulepaths, pkg_dirs): """Creates a graph of all the modules in `modulepaths` that are related to each other by their imports. The directories used to resolve an import is `pkg_dirs` Args: modulepaths (List[str]): list of modules filepaths to analyze. ...
c4989d9df214205f9beaadeb619fde92d05ec65b
24,811
def str_to_bool(string): """ Parses string into boolean """ string = string.lower() return True if string == "true" or string == "yes" else False
e7c1645ab3ba59fc4721872df76f406c571cab8f
24,812
def rerotateExtremaPoints(minSepPoints_x, minSepPoints_y, maxSepPoints_x, maxSepPoints_y,\ lminSepPoints_x, lminSepPoints_y, lmaxSepPoints_x, lmaxSepPoints_y,\ Phi, Op, yrealAllRealInds): """ Rotate the extrema points from (the projected ellipse centered at the origin and x-axis aligned with semi-major ...
b656116d73cd98903fae0f54e3d575a59ae4b102
24,813
import glob def does_name_exist(name): """ check if a file with that name already exists """ return len(glob.glob('./photos/'+name+'.*')) > 0
c377f5fdb15d1d88ba6082c9be0e0400f5a8094d
24,814
def cont_hires(npoints, elecs, start_timestamp=0): """ Retrieve hires data (sampled at 2 kHz). Parameters and outputs are the same as the `cont_raw` function. Args: npoints: number of datapoints to retrieve elecs: list of electrodes to sample start_timestamp: NIP timestamp to s...
6d420e19e0de94f83992c0945e0f9a994b1e5483
24,815
import torch def batch_grid_subsampling_kpconv_gpu(points, batches_len, features=None, labels=None, sampleDl=0.1, max_p=0): """ Same as batch_grid_subsampling, but implemented in GPU. This is a hack by using Minkowski engine's sparse quantization functions Note: This function is not deterministic and ...
9d4eb2b0d5ad7d36199cc6ff6ba567c49dccff4b
24,816
import configparser import re def hot_word_detection(lang='en'): """ Hot word (wake word / background listen) detection What is Hot word detection? ANSWER: Hot word listens for specific key words chosen to activate the “OK Google” voice interface. ... Voice interfaces use speech recognition techno...
d982c33dc9b8af0e1592a88438664342fb25b8cc
24,817
def parse_ph5_length(length): """ Method for parsing length argument. :param length: length :type: str, numeric, or None :returns: length value as a float :type: float or None """ err_msg = "Invalid length value. %s" % (length) return str_to_pos_float(length, err_msg)
f5f669bdcd28611e45bbefa80fce6f2bf16a663f
24,818
import torch import os from typing import Iterator def _generate(payload: ModelSpec, is_udf: bool = True): """Construct a UDF to run pytorch model. Parameters ---------- payload : ModelSpec the model specifications object Returns ------- A Spark Pandas UDF. """ model = pa...
06ded035bfa2c9410561e6aeb4b02cd49f08c93b
24,819
from typing import Tuple def check_proper_torsion( torsion: Tuple[int, int, int, int], molecule: "Ligand" ) -> bool: """ Check that the given torsion is valid for the molecule graph. """ for i in range(3): try: _ = molecule.get_bond_between( atom1_index=torsion[...
7b43e4838bf65ebb4505d1660819ace98bdbd038
24,820
def find_all_occurrences_and_indexes(seq): """ seq: array-like of pretty_midi Note Finds all patterns and indexes of those patterns. """ list_patterns = list() list_indexes = list() res = list() seq_x = seq while res!=None: seq_x, res, indexes = find_occurrences_and_inde...
ab85dca7f30768d75e28ab76b974e50364e8746a
24,821
from functools import reduce from .model_store import get_model_file import os def get_drn(blocks, simplified=False, model_name=None, pretrained=False, root=os.path.join('~', '.chainer', 'models'), **kwargs): """ Create DRN-C or DRN-D model with spec...
06bdf9c3005ad580d239ee380f6284a59879f78a
24,822
def get_uas_volume_admin(volume_id): """Get volume info for volume ID Get volume info for volume_id :param volume_id: :type volume_id: str :rtype: AdminVolume """ if not volume_id: return "Must provide volume_id to get." return UasManager().get_volume(volume_id=volume_id)
55cd59c8e7c116f8a975ef4f14f808c07700d955
24,823
def cyclic_learning_rate(global_step, learning_rate=0.01, max_lr=0.1, step_size=50000., gamma=0.99994, max_steps=100000., scale_rate=0.9, mode='t...
cae33d6b167c4356dec52c0511d36fd23ca68434
24,824
def getElementsOnFirstLevelExceptTag(parent, element): """Return all elements below *parent* except for the ones tagged *element*. :param parent: the parent dom object :param elemnt: the tag-name of elements **not** to return """ elements = [] children = getElements(parent) for c in childre...
7ce5b578090d7079cf6bc3905d0d25fecf06461a
24,825
def get_first_child_element(node, tag_name): """Get the first child element node with a given tag name. :param node: Parent node. :type node: xml.dom.Node :returns: the first child element node with the given tag name. :rtype: xml.dom.Node :raises NodeNotFoundError: if no child node wit...
479b311ec52814b9276e401361bbb1b040527d23
24,826
import re def parse_iso(filename='iso.log'): """ parse the isotropy output file Args: filename: the isotropy output file name Returns: lname: list of irreps lpt: list of atom coordinate lpv: list of distortion vectors, might be multi-dimensional """ #read in the ...
f0331c7a0c962d9763f1b3a15c997dda5a3c951c
24,827
def revoke_database(cursor: Cursor, user: str, db: str) -> Result: """ Remove any permissions for the user to create, manage and delete this database. """ db = db.replace("%", "%%") return Result(_truthy(query(cursor, _format("REVOKE ALL ON {}.* FROM %s@'%%'", db), user)))
9cb496ffde12fbbed4750a9442572a6bbd74497a
24,828
def get_ex1(): """Loads array A for example 1 and its TruncatedSVD with top 10 components Uk, Sk, Vk = argmin || A - Uk*diag(Sk)*Vk|| Over; Uk, Sk, Vk Where; Uk is a Orthonormal Matrix of size (20000, 10) Sk is a 10 dimensional non-negative vector Vk is a Orthonormal Matrix of size (1...
9afab6220acd28eedcfed1eee9920da97c1ff207
24,829
from typing import Any def render_variable(context: 'Context', raw: Any): """ Render the raw input. Does recursion with dict and list inputs, otherwise renders string. :param raw: The value to be rendered. :return: The rendered value as literal type. """ if raw is None: return Non...
36b6148589a447c8c9397f2b199a0c9da025fd50
24,830
from pathlib import Path import os def resolve_ssh_config(ssh_config_file: str) -> str: """ Resolve ssh configuration file from provided string If provided string is empty (`""`) try to resolve system ssh config files located at `~/.ssh/config` or `/etc/ssh/ssh_config`. Args: ssh_config_...
c9f03965e8eab7b3e1c30d1740b966890c2a48fb
24,831
import requests import sys def check_kafka_rest_ready(host, port, service_timeout): """Waits for Kafka REST Proxy to be ready. Args: host: Hostname where Kafka REST Proxy is hosted. port: Kafka REST Proxy port. timeout: Time in secs to wait for the service to be available. Return...
1531ab2a2b89bf7f6e8f3dad592ce156c6fe8535
24,832
def is_p2wpkh_output(cscript: CScript) -> bool: """Checks if the output script if of the form: OP_0 <pubkey hash> :param script: Script to be analyzed. :type script: CScript :return: True if the passed in bitcoin CScript is a p2wpkh output script. :rtype: bool """ if len(cscript...
1efec498daa89c1b345538d4e976aaa9ac9dd6cd
24,833
def check_update_needed(db_table_object, repository_name, pushed_at): """ Returns True if there is a need to clone the github repository """ logger.info(f"This is the repo name from check_update <<{repository_name}>> and db_table <<{db_table_object}>>") result = get_single_repository(db_table_object...
1ab5b3e29e504b60deb928f634a0e8d11cf71d3b
24,834
def return_one(result): """return one statement""" return " return " + result
94298fd5811877fa9e6a84cb061fc6244f3fda3b
24,835
def inv(a): """The inverse rotation""" return -a
dbf88fc5f8f2f289f0132a19e0d0af0e82f232bd
24,836
from App import Proxys def wrapCopy(object): """Wrap a copy of the object.""" return eval( serialize(object), Proxys.__dict__ )
ece99c49d9e5cd3603ee91f6614e5f63bc122751
24,837
def return_edges(paths, config, bidirectional=False): """ Makes graph edges from osm paths :param paths: dictionary {osm_way_id: {osmid: x, nodes:[a,b], osmtags: vals}} :param config: genet.inputs_handler.osm_reader.Config object :param bidirectional: bool value if True, reads all paths as both ways...
7f218db652cf9fdbbedde4fea4aa8c74a46a56c8
24,838
def pi_eq_func(ylag,pilag,v,s,slag,alpha,h,b,phi,gamma): """ equilibrium value for inflation Args: ylag (float): lagged output pilag (float): lagged inflation v (float): demand disturbance s (float): supply disturbance slag (float): lagged supply disturbance alp...
fca249f970e2d97b32d0f8a8b03602370c19b36d
24,839
import time def set_mode(vehicle, mode): """ Set the vehicle's flight modes. 200ms period state validation. Args: vehicle(dronekit.Vehicle): the vehicle to be controlled. mode(str): flight mode string, supported by the firmware. Returns: bool: True if success, Fal...
7c8590989ce7d7c0ffbc9910c8f8cf7018090e95
24,840
import joblib import tqdm import sys def apply_parallel(data_frame, num_procs, func, *args, progress_bar=False, backend='loky'): """ This function parallelizes applying a function to the rows of a data frame using the joblib library. The function is called on each row individually. This function ...
ae8382e1d8ba58b4308119fc79fc9b640c089281
24,841
def _setdoc(super): # @ReservedAssignment """This inherits the docs on the current class. Not really needed for Python 3.5, due to new behavior of inspect.getdoc, but still doesn't hurt.""" def deco(func): func.__doc__ = getattr(getattr(super, func.__name__, None), "__doc__", None) return ...
47da03ae9951e18fccaaa2cf891d39dfdcc324c9
24,842
def test_module(client: Client) -> str: """Tests API connectivity and authentication' Returning 'ok' indicates that the integration works like it is supposed to. Connection to the service is successful. Raises exceptions if something goes wrong. :type client: ``Client`` :param Client: client t...
d3bd13ee0b928d9ffb14a93efb4738f484979dfc
24,843
import functools import warnings def warns(message, category=None): """警告装饰器 :param message: 警告信息 :param category: 警告类型:默认是None :return: 装饰函数的对象 """ def _(func): @functools.wraps(func) def warp(*args, **kwargs): warnings.warn(message, category, stacklevel=2) ...
4c481dc7eeb42751aef07d87ab9da34b04c573f4
24,844
import urllib def handle_exceptions(func) -> object: """ This is needed since pytube current version is quite unstable and can raise some unexpected errors. """ def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except KeyError as e: window.s_...
ef162302186b5da5c86cec67286dcfecefd1ddd0
24,845
def templated_sequence_component(location_descriptor_tpm3): """Create test fixture for templated sequence component""" params = { "component_type": "templated_sequence", "region": location_descriptor_tpm3.dict(exclude_none=True), "strand": "+" } return TemplatedSequenceComponent(...
c92cfd2e0691c097898d82d7ff2d9eb16e5e2023
24,846
def joint_probability(people, one_gene, two_genes, have_trait): """ Compute and return a joint probability. The probability returned should be the probability that * everyone in set `one_gene` has one copy of the gene, and * everyone in set `two_genes` has two copies of the gene, and ...
c2e8d5d617220d44f625c80f9474ab7327800b6f
24,847
import os def _is_child_path(path, parent_path, link_name=None): """ Checks that path is a path within the parent_path specified. """ b_path = to_bytes(path, errors='surrogate_or_strict') if link_name and not os.path.isabs(b_path): # If link_name is specified, path is the source of the link and w...
a46ab1872aa5d3a873b07769c15822ecbaafb435
24,848
def rf_predict_img_win(win_arr, trained_classifier, prob=True): """Predict image window using input trained classifier. Args: win_arr (numpy.arr): In rasterio order (channels, y, x) trained_classifier (sklearn.model): Trained sklearn model to use for predictions. prob (bool, optional): ...
29b79fb4bcc909cce18889bdd624d6db17eb2d29
24,849
from typing import Dict import os def get_schema(passed_schema: 'Schema' = None, _cached_schema: Dict[str, Schema] = {}) -> 'Schema': """If passed a schema (not None) it returns it. If passed none, it checks if the default schema has been initialized. If not initialized, it initializes it. Then it returns...
080bd818ac9fa8f09ae1e4c74b329ba39001a74d
24,850
def ShowIPC(cmd_args=None): """ Routine to print data for the given IPC space Usage: showipc <address of ipc space> """ if not cmd_args: print "No arguments passed" print ShowIPC.__doc__ return False ipc = kern.GetValueFromAddress(cmd_args[0], 'ipc_space *') if not...
4511c0aa1315fe594ee8e1209b6bc2e26d633ad9
24,851
import logging def dqn(env, n_episodes=1001, max_t=1000 * FRAME_SKIP, eps_start=1.0, eps_end=0.001, eps_decay=0.995, solution_threshold=13.0, checkpointfn='checkpoint.pth', load_checkpoint=False, reload_every=None): """Function that uses Deep Q Networks to learn environments. Paramete...
078e956b0620e7b10a27e1107224bfe15d3ea79a
24,852
def get_mesh_faces(edge_array): """ Uses an edge array of mesh to generate the faces of the mesh. For each triangle in the mesh this returns the list of indices contained in it as a tuple (index1, index2, index3) """ triangles = [] neibs = neibs_from_edges(edge_array) for edge in ...
e1f555985e3e55c2d0fbc3d0fd92befc6eb2c878
24,853
def _make_attribution_from_nodes(mol: Mol, nodes: np.ndarray, global_vec: np.ndarray) -> GraphsTuple: """Makes an attribution from node information.""" senders, receivers = _get_mol_sender_receivers(mol) data_dict = { 'nodes': nodes.astype(np.float32), 'sende...
dcf3f82c0634afa8ba6ea97694ea36e9fd62c563
24,854
def subrepo(repo, subset, x): """Changesets that add, modify or remove the given subrepo. If no subrepo pattern is named, any subrepo changes are returned. """ # i18n: "subrepo" is a keyword args = getargs(x, 0, 1, _('subrepo takes at most one argument')) pat = None if len(args) != 0: ...
c95cdb08671ca1800ffbc0df94833cdb29ba534a
24,855
def format_output(item, show_url=False): """ takes a voat post and returns a formatted string """ if not item["Title"]: item["Title"] = formatting.truncate(item["Linkdescription"], 70) else: item["Title"] = formatting.truncate(item["Title"], 70) item["link"] = voat_fill_url.format(item["...
1b730507fbff1ab2deadeaaefcfbcd23356ee437
24,856
def get_compiled_table_name(engine, schema, table_name): """Returns a table name quoted in the manner that SQLAlchemy would use to query the table Args: engine (sqlalchemy.engine.Engine): schema (str, optional): The schema name for the table table_name (str): The name of the table ...
91234bbfea2ff55d9d3e14b1ad70eb81ff09fc5d
24,857
def build(filepath): """Returns the window with the popup content.""" ttitlebar = titlebar.build() hheading = heading.build(HEADING_TITLE) top_txt_filler = fillers.horizontal_filler(2, colors.BACKGROUND) message = sg.Text( text=MESSAGE_TEXT + filepath, font=MESSAGE_FONT, te...
b5bfd7f46955351a94763360fb44cc59eeccbb39
24,858
def format_float(digit=0, is_pct=False): """ Number display format for pandas Args: digit: number of digits to keep if negative, add one space in front of positive pct is_pct: % display Returns: lambda function to format floats Examples: >>> format_f...
9f719b7e1609744d673226eb32f0395b50b34f51
24,859
def get_overexpressed_genes( matrix: ExpMatrix, cell_labels: pd.Series, exp_thresh: float = 0.05, ignore_outliers: bool = True, num_genes: int = 20) -> pd.DataFrame: """Determine most over-expressed genes for each cluster.""" # make sure matrix and cell_labels are aligned matrix = m...
44c02d2a9be936cee582c750c680925024604f64
24,860
def heat_degree_day(Tcolumn): """ Returns a list of the heating degree day from an outdoor temperature list params: df is a pandas dataframe with datetime index and field named 'outT' which contains outdoor temperature in Fahrenheit base -- temperature base for the heating degree day va...
60cb58520f5451b25b3e8a42bb35c262018bb902
24,861
def quantile_loss(y_true, y_pred, taus): """ The quantiles loss for a list of quantiles. Sums up the error contribution from the each of the quantile loss functions. """ e = skewed_absolute_error( K.flatten(y_true), K.flatten(y_pred[:, 0]), taus[0]) for i, tau in enumerate(taus[1:]): ...
1d06085b0939cf8307d1ceb2bd65a8f7bbde53e0
24,862
from typing import Tuple from typing import Sequence import string def parse_a3m(a3m_string: str) -> Tuple[Sequence[str], DeletionMatrix]: """Parses sequences and deletion matrix from a3m format alignment. Args: a3m_string: The string contents of a a3m file. The first sequence in the file should be the...
5b1f5f9cfc54cd55602e1d73b92460fbc99b3594
24,863
def build_sub_lattice(lattice, symbol): """Generate a sub-lattice of the lattice based on equivalent atomic species. Args: lattice (ASE crystal class): Input lattice symbol (string): Symbol of species identifying sub-lattice Returns: list of lists: sub_lattice: Cartesia...
7e7748c31f7f082b2e5ec6f21d0a56f60d5ec06c
24,864
def make_url(connection_str): """ """ return _parse_rfc1738_args(connection_str)
2927b541399df8ab134688ae3a3a7274e0efb648
24,865
from typing import Union from typing import Tuple def get_graphs_within_cutoff(structure: Union[Structure, MEGNetMolecule, Molecule], cutoff: float = 5.0, numerical_tol: float = 1e-8) -> Tuple[np.ndarray]: """ Get graph representations from structure within cutoff Args: ...
a745808938160148ddaa345f0e5f8aa11b4a3a5f
24,866
def add_cals1(): """ Add nutrients to daily intake for products. """ if 'username' in session: food = request.form.get("keyword") pr = Product(food) lst = pr.get_products() for i in lst: lyst.append(i) if len(lst) != 0: return render_templa...
acdda46ad1fdce23baee8bae2018cf5e6510895f
24,867
def format_percent(percentage, pos): """ Formats percentages for the 'x' axis of a plot. :param percentage: The fraction between 0.0 and 1.0 :type percentage: float :param pos: The position argument :type pos: int :return: A formatted percentage string :rtype: str """ # pylint: ...
d8566ce36b21adb351141ac72413b927e0f02c11
24,868
import inspect def simple_repr(obj, attrs: tp.Optional[tp.Sequence[str]] = None, overrides: dict = {}): """ Return a simple representation string for `obj`. If `attrs` is not None, it should be a list of attributes to include. """ params = inspect.signature(obj.__class__).parameter...
4aaa3090a2a0fbb282cfc8403d365c562ae6c5d9
24,869
import torch def Gaussian_RadialBasis(basis_size: int, max_radius: float, min_radius=0., num_layers: int = 0, num_units: int = 0, activation_function='relu'): """ Note: based on e3nn.radial.GaussianRadialModel. :param basis_size: :param max_radius: :param min_radius: ...
f518e2706dcb672bf65f0ed9299c1579fec411a3
24,870
def _get_column_outliers_std(column, m=3): """ given a pandas Series representing a column in a dataframe returns pandas Series without the values which are further than m*std :param column: pandas Series representing a column in a dataframe :param m: num of std as of to remove outliers :return:...
b55dd119ce36cdae7f17bb91aae4257b2dfca29e
24,871
import requests def scrape_website(url): """Sends a GET request to a certain url and returns the Response object if status code is 200. Returns None if the server responds with a different code. """ result = requests.get(url) # if (True): # debugging if result.status_code == 200: ...
3b7eafa468ea19a93f2509aeb6120a2c463ae579
24,872
def set_filters(request, query, result, static_items=None): """ Sets filters in the query """ query_filters = query['filter']['and']['filters'] used_filters = {} if static_items is None: static_items = [] # Get query string items plus any static items, then extract all the fields ...
fcd4fdb6b804fdcf0dce6dac3d19f1945d858a12
24,873
def generate_random_initial_population(population_size, n_nodes, al): """ Randomly create an initial population :param population_size: population size :type population_size: int :param n_nodes: number of nodes :type n_nodes: int :param al: adjacency list :type al: list of lists :re...
0a219ee6de88f97fa099d5fbc0698cc6712c525f
24,874
def import_mlp_args(hyperparameters): """ Returns parsed config for MultiLayerPerceptron classifier from provided settings *Grid-search friendly """ types = { 'hidden_layer_sizes': make_tuple, 'activation': str, 'solver': str, 'alpha': float, 'batch_size': int...
0bfe7cdd4d85b8cfeee32d82f3dd189d60359690
24,875
from typing import List from typing import Optional import networkx def download_map( location: List[str], node_tags: Optional[List[str]] = None, edge_tags: Optional[List[str]] = None, api_key: Optional[str] = None, ) -> networkx.DiGraph: """ Download map from OSM for specific locations. "...
6873acae1dbfb6277abb5764e3783315433c4f29
24,876
import torch def getLayers(model): """ get each layer's name and its module :param model: :return: each layer's name and its module """ layers = [] def unfoldLayer(model): """ unfold each layer :param model: the given model or a single layer :param root: ro...
22565e786eb95e2b8996fad99778068ba15273ea
24,877
def get_config_pdf_version(config_version: str, max_input_version: str) -> str: """ From the PDF version as set in the configuration and the maximum version of all input files, checks for the best PDF output version. Logs a warning, if the version set in the configuration is lower than any of the input ...
6bb98c455a2b701d89c90576a958348f84344cb8
24,878
def threshold_otsu(hist): """Return threshold value based on Otsu's method. hist : array, or 2-tuple of arrays, optional Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. An alternative use of this function is to pass it onl...
ea55dd483b0b60f8428240a62720fb53d4e0e80c
24,879
def filter_options(v): """Disable option v""" iris = dataframe() return [ {"label": col, "value": col, "disabled": col == v} for col in iris.columns ]
54277b38d30389b302f1f962667bbb91f0999b4f
24,880
def scatter(x): """ matrix x x^t """ x1 = np.atleast_2d(x) xt = np.transpose(x1) s = np.dot(xt,x1) assert np.array_equal( np.shape(s), [len(x),len(x)] ) return s
9d68eba6d3ffde7fb15d21a5a0d09a775bef96e7
24,881
def get_owned_object_or_40x(klass, owner, include_staff=False, include_superuser=True, *args, **kwargs): """ Returns an object if it can be found (using get_object_or_404). If the object is not owned by the supplied owner a 403 will be raised. """ obj = get_object_or_404(...
7535aa0ce7c77c41823f45c89885b5e2c32ed252
24,882
def ampMeritFunction2(voltages,**kwargs): """Simple merit function calculator. voltages is 1D array of weights for the influence functions distortion is 2D array of distortion map ifuncs is 4D array of influence functions shade is 2D array shade mask Simply compute sum(ifuncs*voltages-distortion...
4443369f5424f536e839439c8deb479d09339e90
24,883
def get_transpose_graph(graph): """Get the transpose graph""" transpose = {node: set() for node in graph.keys()} for node, target_nodes in graph.items(): for target_node in target_nodes: transpose[target_node].add(node) return transpose
f7f8e083659e4214d79472961c7240778f37268d
24,884
import os def _game_data_path(game_id): """ Find the path to the data file for a given game. This fully trusts game_id, and is not safe on unsanitised input. """ return os.path.join(_DATA_STORES, "{}{}".format(game_id, _EXTENSION))
60acc44e94941a7fdbc2212b3cb56260756ba69a
24,885
def varimax(x, iteration=14): """ http://www.real-statistics.com/linear-algebra-matrix-topics/varimax/""" # TODO: set more intelligent angle evaluator # parameter: x np.array(m_features,c_factors) def _calculate_rotation_angle(x, y): u = np.square(x) - np.square(y) v = 2 * x * y ...
98706360f6ecb81796f8d20c3f11655e1c86a5a5
24,886
def inventory_to_kml_string( inventory, icon_url="https://maps.google.com/mapfiles/kml/shapes/triangle.png", icon_size=1.5, label_size=1.0, cmap="Paired", encoding="UTF-8", timespans=True, strip_far_future_end_times=True): """ Convert an :class:`~obspy.core.inventory.inventory.In...
3b10decafe34b006a41be01e44a5073c2d2d13fb
24,887
import torch def get_feature_embedding(config, data_loader, topk): """Iterate through all items in the data loader and maintain a list of top k highest entropy items and their embeddings topk - the max number of samples to keep. If None, don't bother with entropy, and just return embeddings for item...
820ccf9750e0fc10202caca05d1396e635630281
24,888
def extract_yelp_data(term, categories, price, location, limit, sort_by, attributes, yelp_api_key=yelp): """ This function takes search results (a dictionary) and obtains the name, zip code, address of the possible restaurant matches in the form of a pandas dataframe. Inputs:...
e57ca05265944a3971dfb0af7715e9764dd3112e
24,889
def collect_photo_info(api_key, tag, max_count): """Collects some interesting info about some photos from Flickr.com for a given tag """ photo_collection = [] url = "http://api.flickr.com/services/rest/?method=flickr.photos.search&tags=%s&format=json&nojsoncallback=1&api_key=%s" %(tag, api_key) resp = ...
26e9525639da658f9c9920b5356dd9af4753a1c5
24,890
def yolo_eval(yolo_outputs, image_shape=(720., 1280.), max_boxes=10, score_threshold=.6, iou_threshold=.5): """ Converts the output of YOLO encoding (a lot of boxes) to your predicted boxes along with their scores, box coordinates and classes. Arguments: yolo_outputs -- output of the encoding model (fo...
119524a2f850abba7ff9e1c1c1ca669e44f0a181
24,891
def task(name, required=None): """ A decorator for creating new tasks Args: name (str): Name of the task required (list): A list of required message keys that the task expects to be present """ def decorator(fn): @wraps(fn) def wrapper(...
e23961baac5ea9a7efdd3be308f73db968b15824
24,892
import torch def heterograph(g, max_level=4): """ Constructing hypergraph from homograph. Parameters ---------- g : `dgl.DGLGraph` Input graph. max_level : `int` (Default value = 4) Highest level of hypernodes. Returns ------- hg : `dgl.DGLHeteroGraph` ...
345ba6d883764f1c67b5bf2f092c504b857d7bc8
24,893
import re def check_date_mention(tweet): """Check the tweet to see if there is a valid date mention for the three dates of pyconopenspaces: 5/11, 5/12, 5/13. Quick fix to override SUTime defaulting to today's date and missing numeric info about event's date """ date_pat = re.compile("([5]{1}\/\d...
67c0de3beac5036d8b7aefa161b82a15257da04f
24,894
import argparse def parse(args): """[--starved <int>] [--control <int>] [--other <int>]""" parser = argparse.ArgumentParser() parser.add_argument('--control', metavar='level', type=int, default=2) parser.add_argument('--other', metavar='level', type=int, default=1) parser.add_argument('--starved'...
6e316e3337406a4b7918474a6497c8fa03d02696
24,895
def make_nointer_beta(): """Make two random non-intersecting triangles in R^3 that pass the beta test.""" # Corners of triangle B. b1, b2, b3 = np.random.random(3), np.random.random(3), np.random.random(3) # Two edges of B. p1 = b2 - b1 p2 = b3 - b1 n = np.cross(p1, p2) n /= np.linalg....
6502e5992f4fe959ec1fe87f3c5e849bfc428d30
24,896
def get_all_with_given_response(rdd, response='404'): """ Return a rdd only with those requests that received the response code entered. Default set to '404'. return type: pyspark.rdd.PipelinedRDD """ def status_iterator(ln): try: status = ln.split(' '...
8268095938bbc35a6418f557af033a458f041c89
24,897
from typing import Optional async def get_neighbourhood(postcode_like: PostCodeLike) -> Optional[Neighbourhood]: """ Gets a police neighbourhood from the database. Acts as a middleware between us and the API, caching results. :param postcode_like: The UK postcode to look up. :return: The Neighbour...
1cf2f0ebdc84b01560ba1103285198cd0390b6d0
24,898
def get_refl_weight(value, source_node): """Returns the reflection weight for Redshift Material :param value: :param source_node: :return: """ refl_color_map = source_node.ParameterBlock.texmap_reflection.Value refl_color_map_name = None try: refl_color_map_name = refl_color_map...
601f4be49c536e9efdac4873dddbc76726dc63ba
24,899