content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def rowNormCMatrix(partition): """ Calculate squared row norm of C factor matrices """ ret = [] rows = list(partition) # dalia for row in rows: label = row[0] Xi = row[1] Ki = Xi.shape[0] Ci = np.zeros((Ki,R)) ZiTZic = tensorOps.ZTZ(A, B) XiZic = np.dot(unfold(Xi, 0), khatri_rao([Ci...
72b3ee89305deac69badae8ce92d80a3f62f9481
3,600,300
def versions_to_sync(gh_releases, releases): """ :param gh_releases: github release objects from atom. :param releases: the db releases. """ # Because many projects might have existing ones on pygame, # but not have them on github, we don't delete ones unless # they came originally from gi...
209e34d3883dc35f3f6eba13e392b05930448c5d
3,600,301
def test_mapping_column_list() -> None: """ Perform a simple mapping over a series of expressions. """ def replace_col(e: Expression) -> Expression: if isinstance(e, Column) and e.column_name == "c2": return FunctionCall(None, "f", (e,)) return e column1 = Column(None, ...
1bd1103b485fce5fd39e2539d8c63d76385c90bf
3,600,302
import itertools def get_common_base(files): """Find the common parent base path for a list of files. For example, ``["/usr/src/app", "/usr/src/tests", "/usr/src/app2"]`` would return ``"/usr/src"``. :param files: files to scan. :type files: ``iterable`` :return: Common parent path. :rty...
bb6c7fde6a9e2f9c620febf52047b547cf24e602
3,600,303
def magic_dir(tmp_path_factory): """Provides a temporary directory for testing copy/working directory behavior.""" magic = tmp_path_factory.mktemp('build_magic') return magic
c891b0e7e8dbf2d23d380ce316fb80b6d78d1ec7
3,600,304
def comment(src_line: str) -> list: """Returns an empty list.""" return []
c7e584811b899ae4a17ba4c9fd0debbc97e0a5cc
3,600,305
def create_form(party_id, erroneous_form=None): """Show form to create a tourney.""" party = _get_party_or_404(party_id) form = erroneous_form if erroneous_form else CreateForm() form.set_category_choices(party.id) return { 'party': party, 'form': form, }
33c1ccf1633d45b21b7a316fbb69f7d8638f8099
3,600,306
def setup_shift_of_ray_bundle(seq_model, start_offset): """ compute transformation for rays "start_offset" from 1st surface Args: seq_model: the sequential model start_offset: z distance rays should start wrt first surface. positive if to left of first surface Returns:...
87a1c6c8761bc64339a75a06385390f9b91a646f
3,600,307
def ancestors(G, source): """Returns all nodes having a path to `source` in `G`. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) source : node in `G` Returns ------- set() The ancestors of source in G """ if not G.has_node(source): ...
152518fbc731bfa94a1d317e7eb16fe4ce80421e
3,600,308
def avo_attributes(horizon_data: str, near_stack: DataArray, far_stack: DataArray, theta_near: int, theta_far: int, TWT_slice: tuple, XL_slice: tuple, inline: int, well_XL=None, well_display=True, robust=True, interpolation='spline16', add_colorbar=True, cmap='je...
52e74efcd0df352b1d9ebf7d84a3710bd9608f87
3,600,309
def tensor_scatter_np_benchmark(np_func, input_x, indices, updates): """ Feature: benchmark to generate result. Description: benchmark function to generate result. Expectation: match to tensor scatter binary op. """ result = input_x.copy() benchmark_func = np_benchmark_func_map.get(np_func) ...
05bdf89dfeee3aab9c2f04ac72ea2d29d0f45431
3,600,310
import os import json import re def load(model_name, species): """ model_name: str Name of the folder containing the model species: str Species name. either 'homo_sapiens' or 'mus_musculus' """ # First load Genes top_dir = os.path.join(MODEL_DIR, model_name) model_dir = o...
08c449621d84dbbe233682397c7166c074d0ca45
3,600,311
import torch def train_nn1(x_train, y_train, h_0=100, cv_err_thresh=0.05, err_thresh=0.05): """ This function trains the single layer MLP using the Adams optimizer and cross entropy loss. K-fold cross validation is also implemented to help prevent overfitting of the model. Parameters: x_train...
ee041a7fd2752b8d4d597797dab2de4175ba521e
3,600,312
import numpy as np def mask_ccf_near_RV(rv,ccf,RVp,hw): """ This mask a region in the ccf near a the velocity RVp, typically for the purpose of masking velocities that are close to the expected velocity of the planet (hence RVp). RVp should be a list or array-like object with the same number of elemen...
d074183960dc6d665f905b592cb820a3eabf349c
3,600,313
from typing import Any def create_course( *, db: Session = Depends(depends.get_db), course_in: schemas.CourseCreateAPI, ) -> Any: """ Create Course """ # extract base information inside a course base_info_of_new_course = schemas.CourseCreate(**dict(course_in)) course_orm_obj = crud.course...
3a82f608511a484ce2d1fadb3616ba5f1cc8b776
3,600,314
def get_time(direction, day, driver): """ Returns the time of departure of a given trip. :param direction: "Salita" or "Discesa". :param day: A day spanning the whole work week ("Lunedì"-"Venerdì"). :param driver: The chat_id of the driver. :return: A string representing the departure time, form...
0be7b0a100a3e105e2cce97aa4ea8e58e7a827ac
3,600,315
from typing import Union def global_mean(local_value: tc.Tensor, world_size: int, item: bool = False) -> Union[tc.Tensor, float]: """ Takes the global mean of a tensor across processes. Args: local_value (torch.Tensor): Torch tensor containing a metric. wor...
37792a76a177b7b5964d060798ed2a531461e898
3,600,316
def is_regex_url(url, regexp): """ Wrapper method to search URL for different properties based on regex :param url: URL :type url: `str` :param regexp: Regular expression for the property :type url: `str` :return: True/False :rtype: `bool` """ return len(regexp.findall(url)) > 0
8e5de88e8201805b95d91001067a7756749be048
3,600,317
def hidden_loc(obj, name): """ Generate the location of a hidden attribute. Importantly deals with attributes beginning with an underscore. """ return ("_" + obj.__class__.__name__ + "__" + name).replace("___", "__")
5a8c3d066cb96cf282c1b8814ac1302bd68111c0
3,600,318
def get_num_accessions(session, batch): """ The total number of accession records in the batch :param session: the Session in which to perform the query :param batch: the name of the batch to limit the search to :return: the total number of accession records in the batch """ return get_acce...
b88bde02292172003eb9b950b27111542f40ebdf
3,600,319
def map_to_zero_one(vector): """ Mapping linearly the values in a 2 dimesion vector to [0,1] interval. Parameters: ----------- vector: 2d numpy Return: ------- scaled_vector: numpy an array with the same size of vector, that its values are mapped between [0, 1] ...
5c67a411dd63ee048ebeccea7df4dc564ca151c8
3,600,320
def get_point_image_feature(img_feature, image_v): """ Get Image info img_feature: [h, w, c] image_v: [n, 2], x, y location for each """ points_num = image_v.shape[0] channels = img_feature.shape[-1] return_feature = np.zeros((points_num, channels), dtype=img_feature.dtype) heigh...
c2d8098f8e286dbc5614e7fcc81937ae89dd5303
3,600,321
import json def _load_cluster_config(input_file_path): """ Load queues_info and add information used to render templates. :return: queues_info containing id for first queue, head_node_hostname and queue_name """ with open(input_file_path) as input_file: return json.load(input_file)
b86f163da96be1f831da7997872825e852439f84
3,600,322
def PIT_training_function(loaded_file, i): """ :param loaded_file: file output from operant box :param i: number of days analyzing :return: data frame of all analysis extracted from file (one animal) """ (timecode, eventcode) = extract_info_from_file(loaded_file, 500) (A_dur_individual, A_d...
12a938a5b4bf36e9ce1eb1b27686f6976dbf53be
3,600,323
def svn_repos_load_fs4(*args): """svn_repos_load_fs4(svn_repos_t * repos, svn_stream_t * dumpstream, svn_revnum_t start_rev, svn_revnum_t end_rev, enum svn_repos_load_uuid uuid_action, char const * parent_dir, svn_boolean_t use_pre_commit_hook, svn_boolean_t use_post_commit_hook, svn_boolean_t validate_props, svn_r...
e5a47b2865d4d012dceded24be3756413e118df3
3,600,324
def compose_official_address(company): """ :returns: the most official address for the given company as an object with the following properties: line_1 line_2 town county postcode country The values come from registered address if defined or from the addr...
5c6b4bf5ff5c59382f00644bc19a61f4629dd174
3,600,325
import re def divide_into_parts(text): """делим документ на части по паттернам""" begin_pattern = to_bound_pattern(["УСТАНОВИЛ"]) end_pattern = to_bound_pattern(["ПРИГОВОРИЛ", "ПОСТАНОВИЛ", "РЕШИЛ"]) begin, main_part = re.split(begin_pattern, text, 1) main_part, end = re.split(end_pattern, main_pa...
eab82e8d06424c39e882982a24ab98bac3caeba1
3,600,326
def ExtendedBinaryGolayCode(): """ ExtendedBinaryGolayCode() returns the extended binary Golay code. This is a perfect [24,12,8] code. This code is self-dual. EXAMPLES:: sage: C = codes.ExtendedBinaryGolayCode() sage: C Linear code of length 24, dimension 12 over Finite Field o...
ba657d85bf0008dd104f975f8095759abb673cd9
3,600,327
from typing import IO def autoOne_cmd(file: IO[str], interactionId: int = 0, where: Range = None, expr: str = ''): """Automatic proof search, find proofs, specific hole. """ return ('autoOne', {'file': file, 'expr': expr, 'interactionId': interactionId, 'where': where})
e650f6d5f22fded1974d130ed3ca3c2e95a1d5b2
3,600,328
def find_neighbors_hexagonal_grid(map_coordinates: list, current_position: tuple) -> list: """Finds the set of adjacent positions of coordinates 'current_position' in a hexagonal grid. Args: map_coordinates (list): List of map coordinates. current_position (tuple): Current position of the hexag...
2a6071d59a69b828eb252504508fa3f706969e1b
3,600,329
from typing import List from typing import Tuple def _address_balances() -> List[Tuple[str, Decimal]]: """ Calculate the balance for each address in ``internal['addresses']`` based on stored transactions. """ balances = {} for tx in internal['transactions']: addr = tx['address'] ...
c859f151db19cec60b6b97a15a19d02577351e93
3,600,330
def Pose_2_ABB(H): """Converts a pose to an ABB target (using quaternion representation). :param H: pose :type H: :class:`.Mat` .. seealso:: :class:`.Mat`, :func:`~robodk.TxyzRxyz_2_Pose`, :func:`~robodk.Pose_2_TxyzRxyz`, :func:`~robodk.Pose_2_ABB`, :func:`~robodk.Pose_2_Adept`, :func:`~robodk.Pose_2_...
b4d0f6111d19ffe20c520cad0adf1f9a4b6a00f1
3,600,331
def create_encounter( service_account_json, base_url, project_id, cloud_region, dataset_id, fhir_store_id, patient_id, ): """Creates a new Encounter resource in a FHIR store based on a Patient.""" url = "{}/projects/{}/locations/{}".format(base_url, project_id, cloud_region) fhi...
9ad6f2ea0a9b8d2356be55dc0d8a8a79a35dd362
3,600,332
def find_first(pattern: str, path: str) -> str: """ Finds first file in ``path`` whose filename matches ``pattern`` (via :func:`fnmatch.fnmatch`), or raises :exc:`IndexError`. """ try: return find(pattern, path)[0] except IndexError: log.critical('''Couldn't find "{}" in "{}"''',...
b130cc09276f943bae967e639dcd8753cdeefc57
3,600,333
import pyarrow as pa def ST_Contains(left, right): """ Check whether a geometry contain another geometry. For every (left, right) pair with the same offset value in left and right, check if left_geometry "contains" right_geometry. Left "contains" right means no points of right_geometry lie in the...
af24efee790ec50e6b766c0a188fb3a580242436
3,600,334
import re import json def compileMorphemicAnalysis_(form, morpheme_delimiters=None, **kwargs): """Generate values fo the morphological analysis-related attributes of a form model. :param form: the form model for which the morphological values are to be generated. :param list valid_delimiters: morpheme de...
f6d578c80acb11bcc0bc873fe194cc5c464294be
3,600,335
import toml def load_config_from_string(): """returns a function that loads a configuration dictionary from a string""" def load(s): return bridge.config.ConfigSchema().load(toml.loads(s)) return load
10cce745dcd386f920064abe27fc65e5430b5daf
3,600,336
def set_multindex_dtype(df: pd.DataFrame, dtype: str = 'str') -> pd.DataFrame: """set the dtype of all levels of a multi-index, by default to string""" new_index = [df.index.get_level_values(idx).astype(dtype) for idx in range(len(df.index.levels))] df.index = new_index return df
6ef0f545a861aea051e374f238b001dd7a625155
3,600,337
def image_id(identifier): """Redirect a plain image id""" return flask.redirect(flask.url_for('image_info', identifier=identifier), code=303)
813a6e66da5ee25b69245b7c1db301f224bf7d32
3,600,338
from pathlib import Path def openW2wFile(path, mode): """ Helper function to read/write all files with same encoding and line endings :param str|Path path: full path to file :param str mode: open mode: 'r' - read, 'w' - write, 'a' - append :return TextIO: """ if isinstance(path, Path): ...
6e42a26d2262ed10d15e19292e7b32fffd14aeb8
3,600,339
def get_temperature ( year=None, latitude=None, longitude=None, \ fname="/data/geospatial_20/ucfajlg/meteo/temp_2m.tif" ): """This function grabs the temperature for a given year (or all of them if set ``year`` is set to ``None``, for the whole globe or for a given location. """ # These are fact...
576ce3672c1835a140c7cac5ef6e43ab57f165a7
3,600,340
from typing import Callable from re import T def capture_action(bound_method: Callable[P, T]) -> Callable[P, T]: """A decorator for `Pet`'s methods that captures actions when in battle so that the battle manager can control ability cast order.""" @wraps(bound_method) def _impl(self, *args: P.args, **k...
4ca3aebd70cddd2d030081fa139d2ef4897e4664
3,600,341
from GPy.models import GPClassification, GPRegression, SparseGPClassification, SparseGPRegression def make_model_builder(Y, num_inducing=None, name=None, sparse=False): """ This is a helper for creating several models. It returns a function which takes data and makes a GPy model out of it, with the sp...
797734a99a9fd4a8122137db05bbe7e4c5ae913e
3,600,342
def th_nearest_interp3d(input, coords): """ 2d nearest neighbor interpolation th.Tensor """ # take clamp of coords so they're in the image bounds coords[:,0] = th.clamp(coords[:,0], 0, input.size(1)-1).round() coords[:,1] = th.clamp(coords[:,1], 0, input.size(2)-1).round() coords[:,2] = th.c...
44b3d3a1b69aad75c8818605e596eea090d1decc
3,600,343
def ugly_numbers(n: int) -> int: """ Returns the nth ugly number. >>> ugly_numbers(100) 1536 >>> ugly_numbers(0) 1 >>> ugly_numbers(20) 36 >>> ugly_numbers(-5) 1 >>> ugly_numbers(-5.5) Traceback (most recent call last): ... TypeError: 'float' object cannot be ...
69c92c8eea98b6d8d869f0725c49d6b164d24480
3,600,344
def populate_single_page(args, count, images, pagenos): """ Return a generator that scales all supplied images to fit on fixed number of pages.""" def _try_it(): builder = make_builder(args, images) page_count, incomplete = builder.get_page_count(pagenos) return (page_count, incomplete) ...
dd58870a708b3013b44ef6d2078358a7635ef6f5
3,600,345
from typing import Any from typing import Callable from typing import Pattern def pattern_from_transform( step_structure: tree.Structure[Any], transform: Callable[[ReferenceStep], Pattern]) -> Pattern: """Creates a pattern by invoking a transform from step to output structures. ```python def my_transf...
6121f5dd5930a2aa514e468f9619d0d83c244d31
3,600,346
def update_grid( old_grid: Grid, acceptable: str = ".L#", min_occupied_to_switch: int = 4 ) -> Grid: """Update the grid""" new_grid = [""] * len(old_grid) for i, row in enumerate(old_grid): for j, seat in enumerate(row): occupied = get_num_occupied(i, j, old_grid, acceptable) ...
cbee446da34b3c3544a558b740a29ed7760efa90
3,600,347
import torch def prepare_device(n_gpu: int, keep_reproducibility=False): """ Choose to use CPU or GPU depend on the value of "n_gpu". Args: n_gpu(int): the number of GPUs used in the experiment. if n_gpu == 0, use CPU; if n_gpu >= 1, use GPU. keep_reproducibility (bool): if we need to cons...
ed67768949a842b135798137d01dd40e50fdf47f
3,600,348
def send_self(use_proxy): """ A decorator which sends a generator a reference to itself. The first yield statement will emit the reference. Useful for creating generators that can leverage callback-based functions in a linear style, by passing their 'send' method as callbacks. Note that by def...
8e64c875f7fcc1132d2a01d08a2fc67ef1eff25b
3,600,349
from typing import Optional from typing import List from typing import Dict def get_request_preview_queries( *, db: Session = Depends(deps.get_db), dataset_keys: Optional[List[str]] = Body(None), ) -> List[DryRunDatasetResponse]: """Returns dry run queries given a list of dataset ids""" dataset_co...
00a5c6a1a5157fcf1f33b286eb7a6154d893fefb
3,600,350
def get_cz_exp(q0, q1, a): """Exponent of entangling CZ building_block.""" return linear_algebra.Graph(linear_algebra.cond_rotate_z(exponent=a)(q0, q1))
d9fcd6775d740c1c4a8f54cfcb357250ac05b87e
3,600,351
def get_event_by_id(event_id): """ :Route: /id/<event_id> :Description: Returns GeoJSON of singular event matching event ID :param str event_id: ID string to search database for exact match """ search_dict = {'id': event_id} return event_collector.find_events_in_database(search_dict, True...
18c7dcc995b40f5c7c27ab3f24629ffbb4cdbd95
3,600,352
import os def _get_file_from_blob( connection_string, metadata, saltenv, container, path, cached_file_path ): """ .. versionadded:: 3001 Downloads the entire contents of an Azure storage container to the local filesystem. :param connection_string: The connection string to use to access the speci...
7888be0a6cb0c494393b6fe4fe50dadfa77b658a
3,600,353
from typing import Iterable def make_conda_description(summary: str, conda_channels: Iterable[str] = ()) -> str: """ Create a description for the Conda package from its summary and a list of channels required to install it. The description will look like:: This is my fancy Conda package. Hope you like it 😉. ...
b275e3bfcb67da33a4c7a34d7801a0cb4144527a
3,600,354
import hashlib def sha1(text): """ Calculate the SHA1 fingerprint of text. :param text: The text to fingerprint (a string). :returns: The fingerprint of the text (a string). """ context = hashlib.sha1() context.update(text.encode('utf-8')) return context.hexdigest()
43473e9cc22b6cbe072170244b56b831f0cc88ee
3,600,355
def picks_pair_to_idx(raw, sd_pairs, on_missing='error'): """ Return a list of picks for specified source detector pairs. If multiple channel have the same source detector pair, for example if there are multiple wavelengths or chromaphore, then all channels matching the requested sources and detect...
f9e69eb4fde1e84633ef85f6c9d1d2473554a0c1
3,600,356
import time import logging import requests def post_to_slack(webhook, text=" ", attachment=None, payload={}): """Post a message to the slack channel.""" global RETRY_AFTER global RATE_LIMITED if time.time() <= RETRY_AFTER: logging.error("Slack: HTTP 429 Too Many Requests.") return Fal...
ecd592f16ec3ddac449c4e245384bc419777c67f
3,600,357
import os import re import struct def CreateSeqDirFromIr( folder_ir: str, vocab: vocabulary.VocabularyZipFile ) -> str: """Transform a folder of raw IR into trainable data to be used as input data in tasks. Args: folder_ir: The folder of LLVM IR to read. Must end in '_ir'. vocab: The vocabulary to us...
1600b69c67ab7981a58d4e0ca5f84754bae75ba3
3,600,358
def get_xy_subset(x, y, xmin, xmax): """Get a subset of values from two array given xmin and xmax. The array must be sorted in ascending or descending order. Parameters ---------- x: np.ndarray The first array to get the subset from, set by xmin and xmax. y: np.ndarray The seco...
6dc076d570496ee651234fd98abb7cdbadf086a3
3,600,359
from typing import Iterable def new(convention_spec: str, user_paths: Iterable[str] = None): """Returns a new registry based on the `convention_spec` and `user_paths`. The registry contains all the environments generated by the named convention when passed the `user_paths`. The `convention_spec` is ...
adf283f169f8891a0b935416215e332d6a6c0741
3,600,360
def _binned_haplotype_matrix_from_ts( ts: tskit.TreeSequence, *, num_samples: int, num_loci: int, maf_thresh: int, ) -> np.ndarray: """ Non-vector implementation of BinnedHaplotypeMatrix.from_ts(). Assumes the data are phased. """ assert ts.num_samples == num_samples assert ...
b9ca7d9227719cc306522971be05c9302d8b4e0e
3,600,361
import logging import pprint def parse_cbgp(srt, name, adj=None): """ Parse the routing table received from C-BGP :param srt: Source routing table :param name: Name of the router :param adj: Adjacency information :return: Routing table as pandas dataframe """ logger = logging.getLogger...
05d7770b288a64f35727bdabcaf8bc5ea035e4be
3,600,362
def query_handler(): """Build query_handler test fixture.""" class QueryGetter: def __init__(self): self.query_handler = QueryHandler() def search(self, query_str, keyed=False, incl='', excl=''): return self.query_handler.search(query_str=query_str, keyed=keyed, ...
7c6dae48f6ebb5f212a8164fda15d04c84aec9b9
3,600,363
def create_scatter_indices(updates, dim2known_indices): """Create scatter indices.""" updates_expanded = tf.expand_dims(updates, -1) # [Ro, S, 1] or [Ro, S, C, 1] target_shape = tf.shape(updates_expanded) n_dims = len(tf.shape(updates)) # 2 or 3 dim_indices_list = [] for dim in range(n_dims): indices...
d00b8611c64dd16e42294868c829bebd2cd7e854
3,600,364
import json def add_deduplicated(triple, list_json_triples): """Adds a triple to a list, only if it is not there. Return list and bool indicating whether an addition was made""" addition = False sorted_triple = dict(sorted(triple.items())) triple_as_json = json.dumps(triple_to_json(triple)) if t...
2cd46e85689a5c6bd3d2c88a7ea116c76a205e7c
3,600,365
import os import torch def get_statistics( args, split_path, train_loader, atomref, divide_by_atoms=False, logging=None ): """ Get statistics for molecular properties. Use split file if possible. Parameters ---------- args : argparse.Namespace parsed script arguments split_path : ...
bf39cd1b9a19bc2e2e89dd5fe6687936e6858377
3,600,366
def get_T_strain_2d(theta): """ returns a 2d strain transformation matrix that transforms a global strain vector to a strain vector in fiber coordinates with a normal orientation perpendicular to the fiber orientation. Theta defines the angle to the perpendicular orientation in the laminate plane. ...
afdbde7f5563419da406350ed373fc298dbd2fb7
3,600,367
import re def is_valid_url(value): """Return whether or not given value is a valid URL. Args: value(str): URL address string to validate """ regex = re.compile( r'^(?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' r...
056c79091df6ca10e67071e048e023a88876305c
3,600,368
from typing import OrderedDict def _make_intent_from_args(args): """ Create an intent type for a given set of arguments. :param args: a dict with keys as the names of arguments and values as :class:`argument`s. :returns: A new type that can hold all of the data to call a function that ...
df484850916b96f183e0be862960faf6526074c8
3,600,369
def message(request, message, to=None, sender=None, action=None, methods='POST', media=None, status_callback=None): """ See: https://www.twilio.com/docs/api/twiml/sms/message Usage:: # urls.py urlpatterns = patterns('', # ... url(r'^sms/$', 'django_twili...
9bc918af2eb65047fb46c75f28a8af2ea27656f5
3,600,370
from typing import Dict def _sop_common_handler( event: Event ) -> Dict[UID, "SOPClassCommonExtendedNegotiation"]: """Default handler for when one or more SOP Class Common Extended Negotiation items are included in the association request. See _handlers.doc_handle_sop_common for detailed documentatio...
a4c5afc9c11ea27feb44360ec89078e3f02c354c
3,600,371
def insert_node(graph, node): """ """ if 'properties' not in node: node['properties'] = {} if 'name' in node: node['properties']['name'] = node['name'] if 'hostname' in node: node['properties']['hostname'] = node['hostname'] node_g = util.create_object(graph, node['type'...
1985c7b57f0c21c7003e7b2ba9b045cf46b3d187
3,600,372
import os import pickle def simulate_community_hawkes(params=None, network_name=None, load_if_exists=False, verbose=False): """ Simulates or loads a CHIP model based on the passed parameters. :param params: (dict) optional. Check variable `default_params` in the function for a list of parameters to chang...
95c4ca137092e92957aff96ee0122c8b7b8d8563
3,600,373
def ifirst_is_not(l, v): """ Return index of first item in list which is not the specified value. If the list is empty or if all items are the specified value, raise a ValueError exception. Parameters ---------- l : sequence The list of elements to be inspected. v : object ...
fef5ae1a512772cf4df75a294057330280047f88
3,600,374
import arrow import typing def render_category_path(category: str, template: typing.Optional[str]): """ Renders the actual category by path """ if category: # See if there's any entries for the view... if not model.Entry.select(lambda e: (e.category == category ...
28aabf4cd5d1cd869277f59ae19fc38c30f76031
3,600,375
def group_access_check(message): """Access to function only from certain chat""" return message.chat.id in allowed_chats
ee54c3f1642406d8f10076ceb19c3d76957a011b
3,600,376
import requests def get_data(ticker, start_date=None, end_date=None, index_as_date=True, interval="1d"): """Downloads historical stock price data into a pandas data frame. Interval must be "1d", "1wk", "1mo", or "1m" for daily, weekly, monthly, or minute data. Intraday minute data is limited to 7 days. ...
6627e1ad66a368aa7b9f1c843fcc006a99f1de46
3,600,377
def get_calls(mock_observer_func): """Given a mock IPluginObserver method, returns the plugins that caused its methods to be called, so basically a list of plugins that loaded/unloaded""" return [call_tuple[0][0].name for call_tuple in mock_observer_func.calls]
41360429df5e71da47946f75f8207f985959528f
3,600,378
def format_date_ihme(date_in): """ Formats "m/d/yyy" to "yyyymmdd" """ try: month, day, year = date_in.split('/') return '%s%02i%02i' % (year, int(month), int(day)) except: return date_in.replace('-', '')
166739b2245833c6dddf35fcde87433648697277
3,600,379
def pi(num): """weird way to multiply p by a number""" return np.pi * num
99877b47ab565ea529db99a811df3ed57670f22e
3,600,380
def days_to_weekday(wkdy_src: int, wkdy_dest: int) -> int: """ Calculate the days to a specific destination weekday. Notes ----- Weekday enumeration based on the `datetime` standard library. Parameters ---------- wkdy_src : int Source :class:`~scheduler.util.Weekday` intege...
3fd47aa796bf71d726f25d7b9e3d2c0b9a986ac4
3,600,381
def _cdot(left, right): """ Function corresponding to "|" operation. Parameters ---------- left, right : `astropy.modeling.Model` or ndarray If input is of an array, it is the output of `coord_matrix`. Returns ------- result : ndarray Result from this operation. """...
1e251721b0d5968de737434ee18fb937a69f6a41
3,600,382
def catch_exceptions(view_function) -> APIResponse: """ Catch exceptions and return them as a valid APIResponse """ if settings.DEBUG: return view_function else: def wrapped_view(*args, **kwargs): try: return view_function(*args, **kwargs) exc...
068c41c88795813c34e872d42aa5356cedce772d
3,600,383
async def get_instances(aws_access_key_id, aws_secret_access_key, regions): """Gets a list of all instances on AWS for a list of regions.""" instances = [] session = aiobotocore.get_session() for region in regions: async with session.create_client("ec2", ...
e098762dccc685727b1369de5e27c4114643238e
3,600,384
from typing import Union import httpx def get_client( proxies: Union[str, dict] = None, verify: bool = False, headers: dict = None ) -> httpx.Client: """Gen and cache a httpx.Client. Args: proxies: setup and persistant """ # url = "https://translate.google.cn" if headers is None: ...
519868043162c5da9e0bb3fd579e600aecb13f4d
3,600,385
def calculate_vertical_speed(altitude, time, *, min_time=0.5): """ Calculate the vertical speed in feet per minute given the altitude and time. Parameters ---------- altitude: float The altitude [feet]. time: float The time [Seconds]. min_time: float The minimum ti...
1370926d8d6494f58431f1067fb07df3690fe0e2
3,600,386
def absorption_onset_shift(sp1, sp2, intensity_threshold): """ Shift spectrum 2 with respect to spectrum 1 using the difference between two spectra's onset of absorption. The onset is determined by ascertaining the lowest incident energy at which the spectra's absorption intensity reaches the 'inten...
15c06104b051592d404571d8a45816b955a1491d
3,600,387
import sys def make_data(src_file, tgt_file, src_dicts): """ """ src, tgt = [], [] sizes = [] count = 0 print('Processing %s & %s ...' % (src_file, tgt_file)) srcF = open(src_file, 'r') tgtF = open(tgt_file, 'r') while True: sline = srcF.readline() tline = tgtF.re...
f9a7c3ee928af9444d06962f8a46df4c7f38f1aa
3,600,388
def persian_letter(value, **options): """ normalize persian letters. :param str value: value to be normalized. :keyword bool strip: strip spaces from both ends of value. defaults to True if not provided. :keyword bool normalize_none: specifies that if given value is None,...
c2e13c86fde76e3e12cc4c89e74e018ab40ae318
3,600,389
def patient_ECG_trace_list(MRI_number): """Receive the 'GET' request for getting a selected patient's timestamps of ECG images(except the latest one). The list contains strings as elements, each of which indicates the info of timestamp for every ECG image The 'GET' request is send by a client, targetin...
08d8fc463072a3973bad407abe9e3cbd32469d70
3,600,390
def remove_deleted(loc_id): """ Delete permanently record of given ID from safe_deleted list. :param loc_id: ID of the record to restore :return: 200 on success, 404 if not found """ location = Geolocation.query.filter(Geolocation.visible == 0).filter_by( id=loc_id).one_o...
5a44ef93913a0f767fe26f791367bdc2e2ca2566
3,600,391
import time def add_delete_sampler(kernel, s_init, nb_it_max=10, T_max=10): """ MCMC sampler for generic DPP(kernel), it performs local moves by removing/adding one element at a time. :param kernel: Kernel martrix :type kernel: array_type :param s_init: Initial sample. :type s_init: list :param nb_it...
952419fea389377827e39c978f42a7edd53cac67
3,600,392
from mmdet.models.dense_heads import YOLOV3Head def get_yolov3_head_model(): """yolov3 Head Config.""" test_cfg = mmcv.Config( dict( nms_pre=1000, min_bbox_size=0, score_thr=0.05, conf_thr=0.005, nms=dict(type='nms', iou_threshold=0.45), ...
464901b8d1a57339edee1fc2270b91fe18c68996
3,600,393
def reverse_map(dict_of_sets): """Reverse a map of one-to-many. So the map:: { 'A': {'B', 'C'}, 'B': {'C'}, } becomes { 'B': {'A'}, 'C': {'A', 'B'}, } Args: dict_of_sets (dict[set]): A dictionary of sets, mapping one value ...
87b0679a0ebd00c3dbdcafc89fd2644b21ecbc85
3,600,394
from datetime import datetime import sys def write_xml(xml, agent_name, data_dir="/var/spool/pandora/data_in/"): """Creates a agent .data file in the specified data_dir folder\n Args: - xml (str): XML string to be written in the file. - agent_name (str): agent name for the xml and file name. - dat...
dbe5714bfdd97f94673c3a09b02671e3ee3991dc
3,600,395
def get_class_name(env, obj): """ Return the class name of an object. :param env: the JNIEnv environment :param obj: a Java object instance :return: a Python string name of the Java object class """ class1 = env.GetObjectClass(obj) mid_get_class = env.GetMethodID(class1, 'getClass', '()...
dfaa850c0cd88473f3eb42d029d6edbf699498e9
3,600,396
def angle_between(v1, v2): """ Returns the angle in radians between vectors 'v1' and 'v2':: angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 angle_between((1, 0, 0), (1, 0, 0)) 0.0 angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 ...
9aa2f3766c9be92d69d06ea2140583d15df27b17
3,600,397
from typing import List import itertools def _enumerate_all_from_stabilizer_bases( stabilizer_basis: List[cirq.DensePauliString], n_qubits: int): """ Given a stabilizer basis, creates the exhaustive list of Pauli states that are spanned by the basis. Args: stabilizer_basis: A list of ...
bb08c1dbeaa00db6fc3bb5c7dcbc3bff863a1d29
3,600,398
def get_iemocap_emotion(session_file_name, turn_name): """gets the assigned evaluated iemocap emotion for a given turn name in a given session dialogue""" r = open(session_file_name, 'r') lines = r.readlines() for e, l in enumerate(lines): emo_info = l.split('\t') if len(emo_info) == 4 ...
e82576633632e0f3cffd8d4187607e955dade594
3,600,399