content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def remove_invalid_chars_from_passage(passage_text): """ Return a cleaned passage if the passage is invalid. If the passage is valid, return None """ # Check if any of the characters are invalid bad_chars = [c for c in passage_text if c in INVALID_PASSAGE_CHARACTERS] if bad_chars: for b in set(bad_chars): p...
5eeac3393477c45ac361fb2ccbae194c83e47f25
3,655,900
import locale def fallback_humanize(date, fallback_format=None, use_fallback=False): """ Format date with arrow and a fallback format """ # Convert to local timezone date = arrow.get(date).to('local') # Set default fallback format if not fallback_format: fallback_format = '%Y/%m/%d...
06a758cea23978d877d12cfead25b21140370094
3,655,901
import os import time from datetime import datetime import tarfile def questbackup(cfg, server): """Silly solution to a silly problem.""" if server not in cfg['servers']: log.warning(f'{server} has been misspelled or not configured!') elif 'worldname' not in cfg['servers'][server]: log.wa...
35406f7349665f36880f9ca1036f420a2035fb9d
3,655,902
import sys import os def find_file_in_pythonpath( filename, subfolder='miri', walkdir=False, path_only=False): """ Find a file matching the given name within the PYTHONPATH. :Parameters: filename: str The name of the file to be located. subfolder...
27dc5aebe74af45edeafdba4a3a43f844606e06e
3,655,903
from functools import reduce def min_column_widths(rows): """Computes the minimum column width for the table of strings. >>> min_column_widths([["some", "fields"], ["other", "line"]]) [5, 6] """ def lengths(row): return map(len, row) def maximums(row1, row2) : return map(max, row1, row2) ...
36722e4250dde561836c1ea3042b796ed7650986
3,655,904
def entities(address_book): """Get the entities utility.""" return zope.component.getUtility(IEntities)
6c64c5c8b8d0048425dcd91baf265134fbb2e96e
3,655,905
from renku.core.management.migrations.models.v9 import Project import pathlib def generate_dataset_file_url(client, filepath): """Generate url for DatasetFile.""" if not client: return try: if not client.project: return project = client.project except ValueError: ...
1aa3a97cfff523e0b7d7718c39dfb9935160e193
3,655,906
def _check_attrs(obj): """Checks that a periodic function/method has all the expected attributes. This will return the expected attributes that were **not** found. """ missing_attrs = [] for attr_name in _REQUIRED_ATTRS: if not hasattr(obj, attr_name): missing_attrs.append(attr_...
6a3326616aa5d1cd083f99a2e0f4c57f6f5a11c6
3,655,907
def TokenStartBlockElement(block): """ `TokenStartBlockElement` is used to denote that we are starting a new block element. Under most circumstances, this token will not render anything. """ return { "type": "SpaceCharacters", "data": "", "_md_type": mdTokenTypes["TokenStartB...
c7690b2ca7babc0cc5d6e36a8b8ecb33ad463294
3,655,908
import json def parse_json(json_path): """ Parse training params json file to python dictionary :param json_path: path to training params json file :return: python dict """ with open(json_path) as f: d = json.load(f) return d
c34b241813996a8245ea8c334de72f0fbffe8a31
3,655,909
from unittest.mock import call def cut_tails(fastq, out_dir, trimm_adapter, trimm_primer, hangF, hangR): """ The functuion ... Parameters ---------- reads : str path to ... out_dir : str path to ... hang1 : str Sequence ... hang2 : str Sequence ... R...
8e4ef0b24d5ecf22aa298a0e4e8cddeb7d681945
3,655,910
from typing import Callable from typing import Any from typing import Optional def incidentReports( draw: Callable[..., Any], new: bool = False, event: Optional[Event] = None, maxNumber: Optional[int] = None, beforeNow: bool = False, fromNow: bool = False, ) -> IncidentReport: """ Stra...
6f81cd1294543572605d6bb477e3955be6dc122d
3,655,911
def load_spelling(spell_file=SPELLING_FILE): """ Load the term_freq from spell_file """ with open(spell_file, encoding="utf-8") as f: tokens = f.read().split('\n') size = len(tokens) term_freq = {token: size - i for i, token in enumerate(tokens)} return term_freq
236cb5306632990e1eefcf308dea224890ccd035
3,655,912
def NotP8(): """ Return the matroid ``NotP8``. This is a matroid that is not `P_8`, found on page 512 of [Oxl1992]_ (the first edition). EXAMPLES:: sage: M = matroids.named_matroids.P8() sage: N = matroids.named_matroids.NotP8() sage: M.is_isomorphic(N) False ...
d475810244338532f4611b120aa15b4776bd2aeb
3,655,913
def eqv(var_inp): """Returns the von-mises stress of a Field or FieldContainer Returns ------- field : ansys.dpf.core.Field, ansys.dpf.core.FieldContainer The von-mises stress of this field. Output type will match input type. """ if isinstance(var_inp, dpf.core.Field): return _...
5977b1317fc5bfa43c796b95680a7b2a21ae4553
3,655,914
def sort(array: list[int]) -> list[int]: """Counting sort implementation. """ result: list[int] = [0, ] * len(array) low: int = min(array) high: int = max(array) count_array: list[int] = [0 for i in range(low, high + 1)] for i in array: count_array[i - low] += 1 for j in range(1,...
86864db6e012d5e6afcded3365d6f2ca35a5b94b
3,655,915
def build_updated_figures( df, colorscale_name ): """ Build all figures for dashboard Args: - df: census 2010 dataset (cudf.DataFrame) - colorscale_name Returns: tuple of figures in the following order (datashader_plot, education_histogram, income_histogram, ...
01dd0f298f662f40919170b4e37c533bd3ba443b
3,655,916
import os def sacct(): """ Wrapper around the slurm "sacct" command. Returns an object, and each property is the (unformatted) value according to sacct. Would also work with .e.g: # with open("/home/Desktop/sacct.txt", "r") as file: :return: SacctWrapper object, with attributes based on the ...
df87679b9448ff340d1113af1d4b157e09b777b8
3,655,917
from typing import Optional def get_or_else_optional(optional: Optional[_T], alt_value: _T) -> _T: """ General-purpose getter for `Optional`. If it's `None`, returns the `alt_value`. Otherwise, returns the contents of `optional`. """ if optional is None: return alt_value return optiona...
340fc67adc9e73d748e3c03bec9d20e1646e894c
3,655,918
def create_dic(udic): """ Create a glue dictionary from a universal dictionary """ return udic
aa854bb8f4d23da7e37aa74727446d7436524fe2
3,655,919
import sys def get_isotopes(loop): """ Given a text data loop, usually the very last one in the save frame, find and return the isotopes for naming. Example output: [ '15N', '1H' ] """ # = = = Catch random error in giving the saveFrame instead loop = loop_assert(loop, 'get_isotopes') # For...
22510e054def347cb0138d6a8f685afef666cb47
3,655,920
def select_user(query_message, mydb): """ Prompt the user to select from a list of all database users. Args: query_message - The messages to display in the prompt mydb - A connected MySQL connection """ questions = [ inquirer.List('u', message=query_messa...
8ab2adb27f73b5581bc48c8cc4cbc2888a21753f
3,655,921
import os import logging def runTool(plugin_name, config_dict=None, user=None, scheduled_id=None, caption=None, unique_output=True): """Runs a tool and stores this "run" in the :class:`evaluation_system.model.db.UserDB`. :type plugin_name: str :param plugin_name: name of the referred plugin. :typ...
66c48dcef414a453e9b07ea58330ab08e1bd94d5
3,655,922
from typing import Optional import hashlib def generate_abl_contract_for_lateral_stage( lateral_stage: LateralProgressionStage, parent_blinding_xkey: CCoinExtKey, start_block_num: int, creditor_control_asset: CreditorAsset, debtor_control_asset: DebtorAsset, bitcoin_asset: BitcoinAsset, fi...
2c9b47666c3fb5abf78b8a7d007d1258930f1068
3,655,923
import sqlite3 import os import time def create_connection(language): """ a function to create sqlite3 connections to db, it retries 100 times if connection returned an error Args: language: language Returns: sqlite3 connection if success otherwise False """ try: # re...
b1fc3ddf9217ad693246c1498e9c41cc7a7bb386
3,655,924
def force_norm(): """perform normalization simulation""" norm = meep.Simulation(cell_size=cell, boundary_layers=[pml], geometry=[], resolution=resolution) norm.init_fields() source(norm) flux_inc = meep_ext.add_flux_plane(norm,...
e5c9e6255568e52d0cb30504cd22f610b6f6e5d9
3,655,925
def search(coordinates): """Search for closest known locations to these coordinates """ gd = GeocodeData() return gd.query(coordinates)
c9191a06b085c61b547136166cb43a24789d95cb
3,655,926
from pathlib import Path def get_all_apis_router(_type: str, root_path: str) -> (Path, Path): """Return api files and definition files just put the file on folder swagger.""" swagger_path = Path(root_path) all_files = list(x.name for x in swagger_path.glob("**/*.yaml")) schemas_files = [x for x in al...
eab89c870447e3f1abd72529de37d645de3be612
3,655,927
def get_cached_patches(dataset_dir=None): """ Finds the cached patches (stored as images) from disk and returns their paths as a list of tuples :param dataset_dir: Path to the dataset folder :return: List of paths to patches as tuples (path_to_left, path_to_middle, path_to_right) """ if dataset...
7990b592ddc9b93e04b11c4ae65f410c6afc15d7
3,655,928
def complex_mse(y_true: tf.Tensor, y_pred: tf.Tensor): """ Args: y_true: The true labels, :math:`V \in \mathbb{C}^{B \\times N}` y_pred: The true labels, :math:`\\widehat{V} \in \mathbb{C}^{B \\times N}` Returns: The complex mean squared error :math:`\\boldsymbol{e} \in \mathbb{R}^...
9dc8699312926b379619e56a29529fe2762d68a9
3,655,929
def expand_not(tweets): """ DESCRIPTION: In informal speech, which is widely used in social media, it is common to use contractions of words (e.g., don't instead of do not). This may result in misinterpreting the meaning of a phrase especially in the case of negations. This f...
66f4ed5c7321fe7bf5ea0d350980394a235d99e6
3,655,930
def parse_filter_kw(filter_kw): """ Return a parsed filter keyword and boolean indicating if filter is a hashtag Args: :filter_kw: (str) filter keyword Returns: :is_hashtag: (bool) True, if 'filter_kw' is hashtag :parsed_kw: (str) parsed 'filter_kw' (lowercase, without '#', ......
253d7d5f1aaf6ab3838e7fb3ba395a919f29b70e
3,655,931
def get_branch_index(BRANCHES, branch_name): """ Get the place of the branch name in the array of BRANCHES so will know into which next branch to merge - the next one in array. """ i = 0 for branch in BRANCHES: if branch_name == branch: return i else: i = i + ...
c983bab67b3aa0cd1468c39f19732395c7e376f9
3,655,932
from bs4 import BeautifulSoup def prettify_save(soup_objects_list, output_file_name): """ Saves the results of get_soup() function to a text file. Parameters: ----------- soup_object_list: list of BeautifulSoup objects to be saved to the text file output_file_name: ente...
3de5b7df49837c24e89d2ded286c0098069945fd
3,655,933
def determine_required_bytes_signed_integer(value: int) -> int: """ Determines the number of bytes that are required to store value :param value: a SIGNED integer :return: 1, 2, 4, or 8 """ value = ensure_int(value) if value < 0: value *= -1 value -= 1 if (value >> 7) == ...
231e6f1fc239da5afe7f7600740ace846125e7f5
3,655,934
from bs4 import BeautifulSoup def scrape_cvs(): """Scrape and return CVS data.""" page_headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36", "accept": "text/html,application/xhtml+xml,applicatio...
2f2f59b3477297f475d1749ff2a35c2682361cfd
3,655,935
def _to_original(sequence, result): """ Cast result into the same type >>> _to_original([], ()) [] >>> _to_original((), []) () """ if isinstance(sequence, tuple): return tuple(result) if isinstance(sequence, list): return list(result) return result
7b9d8d1d2b119d61b43dde253d8d3c48bd0e45b8
3,655,936
import os def generate_oauth_service(): """Prepare the OAuth2Service that is used to make requests later.""" return OAuth2Service( client_id=os.environ.get('UBER_CLIENT_ID'), client_secret=os.environ.get('UBER_CLIENT_SECRET'), name=config.get('name'), authorize_url=config.get('...
dcffe4f283f45eacf52c5b01fc43c20c294b6d05
3,655,937
import os def is_relative_path(value): """Check if the given value is a relative path""" if urlparse(value).scheme in ('http', 'https', 'file'): return False return not os.path.isabs(value)
2b6865963f1335a17e5270fc9212426aa5d52536
3,655,938
def get_B_R(Rdot): """Get B_R from Q, Qdot""" return Rdot
696932b9bf423289bdcf91287b0d789007322852
3,655,939
def run_coroutine_with_span(span, coro, *args, **kwargs): """Wrap the execution of a Tornado coroutine func in a tracing span. This makes the span available through the get_current_span() function. :param span: The tracing span to expose. :param coro: Co-routine to execute in the scope of tracing span...
95672b0a1ecf7b8b86dff09835fa9b3c10f7fad2
3,655,940
def calc_bin_centre(bin_edges): """ Calculates the centre of a histogram bin from the bin edges. """ return bin_edges[:-1] + np.diff(bin_edges) / 2
780a02dc9372670ae53fb4d85e216458e7d83975
3,655,941
def to_matrix(dG, tG, d_mat, t_mat, label_mat, bridges): """ Parameters: tG: target graph dG: drug graph d_mat: drug feature matrix t_mat: target feature matrix label_mat: label matrix bridges: known links between drugs and targets Return: ...
54a8ad910f78eca383eba90bd5f6bf6088145630
3,655,942
def ensureList(obj): """ ensures that object is list """ if isinstance(obj, list): return obj # returns original lis elif hasattr(obj, '__iter__'): # for python 2.x check if obj is iterablet return list(obj) # converts to list else: return [obj]
f845658fda36a583ac54caed1e6493d331c910fa
3,655,943
import torch def gelu_impl(x): """OpenAI's gelu implementation.""" return 0.5 * x * (1.0 + torch.tanh(0.7978845608028654 * x * (1.0 + 0.044715 * x * x)))
15ced02b61d6e8c526bc60d2a5214f83183946c2
3,655,944
def get_shape(kind='line', x=None, y=None, x0=None, y0=None, x1=None, y1=None, span=0, color='red', dash='solid', width=1, fillcolor=None, fill=False, opacity=1, xref='x', yref='y'): """ Returns a plotly shape Parameters: ----------- kind : string Shape k...
b639869eca941d2c91d44549aa751c51e033fe00
3,655,945
from typing import List def clean_row(elements: List[Tag]) -> List[Tag]: """ Clean MathML row, removing children that should not be considered tokens or child symbols. One example of cleaning that should take place here is removing 'd' and 'δ' signs that are used as derivatives, instead of as identifi...
527cb06ddb19d9fb25e5805c49f903254813c4e8
3,655,946
def models(estimators, cv_search, transform_search): """ Grid search prediction workflows. Used by bll6_models, test_models, and product_models. Args: estimators: collection of steps, each of which constructs an estimator cv_search: dictionary of arguments to LeadCrossValidate to search over...
2a3044a9cc994f18e37337a7e58e9fb9e5ef05d1
3,655,947
from datetime import datetime import pytz def xml_timestamp(location='Europe/Prague'): """Method creates timestamp including time zone Args: location (str): time zone location Returns: str: timestamp """ return datetime.datetime.now(pytz.timezone(location)).isoformat()
a2883e269c8f9ae8ffd723b7b0205d931453e358
3,655,948
def transform_postorder(comp, func): """Traverses `comp` recursively postorder and replaces its constituents. For each element of `comp` viewed as an expression tree, the transformation `func` is applied first to building blocks it is parameterized by, then the element itself. The transformation `func` should ...
964e55dc33acf978cae3f058397c9b355cae9af7
3,655,949
def bytes_to_unicode_records(byte_string, delimiter, encoding): """ Convert a byte string to a tuple containing an array of unicode records and any remainder to be used as a prefix next time. """ string = byte_string.decode(encoding) records = string.split(delimiter) return (records[:-1], records[-1...
ccc3591551a6b316843cc8eafb33e45627eac752
3,655,950
def administrator(): """Returns a :class:`t_system.administration.Administrator` instance.""" return Administrator()
e473ee2e86f66f96a5cf3e09ac4a052e32a279b9
3,655,951
import numpy def ocr(path, lang='eng'): """Optical Character Recognition function. Parameters ---------- path : str Image path. lang : str, optional Decoding language. Default english. Returns ------- """ image = Image.open(path) vectorized_image = numpy.asa...
9b484779a34d65bb25e57baeaa371205c65d2dc6
3,655,952
import subprocess def get_rpd_vars(): """Read RPD variables set by calling and parsing output from init """ cmd = get_init_call() cmd = ' '.join(cmd) + ' && set | grep "^RPD_"' try: res = subprocess.check_output(cmd, shell=True, stderr=subprocess.STDOUT) except subprocess.CalledProces...
c7ac35b81eab03ab71469e42a3e3858c7dbb0f2c
3,655,953
import os def which(filename): """ Emulates the UNIX `which` command in Python. Raises an IOError if no result is found. """ locations = os.environ.get("PATH").split(os.pathsep) candidates = [] for location in locations: candidate = os.path.join(location, filename) if os.p...
33cdbea19e9d9300bd4983efb7d2bc37a2d38fc1
3,655,954
def _GetAllHypervisorParameters(cluster, instances): """Compute the set of all hypervisor parameters. @type cluster: L{objects.Cluster} @param cluster: the cluster object @param instances: list of L{objects.Instance} @param instances: additional instances from which to obtain parameters @rtype: list of (or...
8ad0479fd87bc9ad17d993772046c1a2fd1bb7a5
3,655,955
def is_solution(system, point): """ Checks whether the point is the solution for a given constraints system. """ a = np.array(system) # get the left part left = a[:, :-1] * point left = sum(left.T) # get the right part right = (-1) * a[:, -1] return np.all(left <= right)
774987f22a57f3a6d68b5d51f7b3a42d945a1eff
3,655,956
def git_config_bool(option: str) -> bool: """ Return a boolean git config value, defaulting to False. """ return git_config(option) == "true"
1ed48faa3c6de43fc8a732aed2fde1a81bc75949
3,655,957
def read_configs(paths): """ Read yaml files and merged dict. """ eths = dict() vlans = dict() bonds = dict() for path in paths: cfg = read_config(path) ifaces = cfg.get("network", dict()) if "ethernets" in ifaces: eths.update(ifaces["ethernets"]) ...
998c75b9d75e4d6404c265a67c31bb88b9b7d435
3,655,958
import json def get_client(): """ generates API client with personalized API key """ with open("api_key.json") as json_file: apikey_data = json.load(json_file) api_key = apikey_data['perspective_key'] # Generates API client object dynamically based on service name and version. perspective = discovery.bu...
be68eeeedf9c3dcf3f3991b70db18cd3032d2218
3,655,959
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ settings['route_patterns'] = { 'villages': '/geography.cfm', 'parameters': '/thesaurus.cfm', 'sources': '/bibliography.cfm', 'languages': '/languages.cfm', 'florafauna': '/f...
52779856e4eeecb9673707b707d51322decda729
3,655,960
def overrides(pattern, norminput): """Split a date subfield into beginning date and ending date. Needed for fields with multiple hyphens. Args: pattern: date pattern norminput: normalized date string Returns: start date portion of pattern start date portion of norminput ...
5e005b0537d123607225ed82163cac07f578a755
3,655,961
def defaultPolynomialLoad(): """ pytest fixture that returns a default PolynomialLoad object :return: PolynomialLoad object initialized with default values """ return PolynomialStaticLoad()
75b989dc80e7ccf4e9a091de2dcdeb8758b465b3
3,655,962
def calc_pi(iteration_count, cores_usage): """ We calculate pi using Ulam's Monte Carlo method. See the module documentation. The calculated value of pi is returned. We use a process pool to offer the option of spreading the calculation across more then one core. iteration_count is the num...
7b4db8f0936995f46a42fedb4d5539cd3057eb01
3,655,963
import requests def send_postatus_errors(): """Looks at postatus file and sends an email with errors""" # Gah! Don't do this on stage! if settings.STAGE: return def new_section(line): return (line.startswith('dennis ') or line.startswith('Totals') or l...
8eadab8bce8155d18b805ee04668cb90a400659c
3,655,964
def pair_range_from_to(x): # cpdef pair_range(np.ndarray[long,ndim=1] x): """ Returns a list of half-cycle-amplitudes x: Peak-Trough sequence (integer list of local minima and maxima) This routine is implemented according to "Recommended Practices for Wind Turbine Testing - 3. Fatigue Loads", 2. ...
96d86079b971bda58fd2d0af440feecc8fa4c1fd
3,655,965
def serialize_action( action: RetroReaction, molecule_store: MoleculeSerializer ) -> StrDict: """ Serialize a retrosynthesis action :param action: the (re)action to serialize :param molecule_store: the molecule serialization object :return: the action as a dictionary """ dict_ = action....
f35c0a34cc6778a39c991edafdda6bd30aea4886
3,655,966
def convert(obj, totype, debug=False, **kwargs): """Converto object obj to type totype. The converter is chosen from gna.converters dictionary based on the type(obj) or one of it's base classes. :obj: object to convert :totype: the target type Order: 1. Set type to type(obj). 2. Try to...
b63d35b193833ef9432cb9752c87257f35cf0210
3,655,967
import string def complement(s): """ Return complement of 's'. """ c = string.translate(s, __complementTranslation) return c
7dab43db51bc5a3bb7321deebdb8122792f08d86
3,655,968
import copy def get_state_transitions(actions): """ get the next state @param actions: @return: tuple (current_state, action, nextstate) """ state_transition_pairs = [] for action in actions: current_state = action[0] id = action[1][0] next_path = action[1][1] ...
bbed37ed6469f5635fbc65fa07195114b4bb3dac
3,655,969
import struct def parse_pascal_string(characterset, data): """ Read a Pascal string from a byte array using the given character set. :param characterset: Character set to use to decode the string :param data: binary data :return: tuple containing string and number of bytes consumed """ str...
eabdfe1f6fb864eead1345016495f64c5457727e
3,655,970
def folder(initial=None, title='Select Folder'): """Request to select an existing folder or to create a new folder. Parameters ---------- initial : :class:`str`, optional The initial directory to start in. title : :class:`str`, optional The text to display in the title bar of the di...
60331e1a89241595e09e746901fff656f8d4365a
3,655,971
from typing import Sequence import scipy def build_clusters( metadata: pd.DataFrame, ipm_regions: Sequence[str], min_capacity: float = None, max_clusters: int = None, ) -> pd.DataFrame: """Build resource clusters.""" if max_clusters is None: max_clusters = np.inf if max_clusters < ...
32e527760c8a06799a41f3cfce0ed5ba27df5b8b
3,655,972
import tqdm from typing import Any from typing import Optional def tqdm_hook(t: tqdm) -> Any: """Progressbar to visualisation downloading progress.""" last_b = [0] def update_to(b: int = 1, bsize: int = 1, t_size: Optional[int] = None) -> None: if t_size is not None: t.total = t_s...
ff075a946ea9cf2d124d9d5e93fb83d31f2e0623
3,655,973
def check_regular_timestamps( time_series: TimeSeries, time_tolerance_decimals: int = 9, gb_severity_threshold: float = 1.0 ): """If the TimeSeries uses timestamps, check if they are regular (i.e., they have a constant rate).""" if ( time_series.timestamps is not None and len(time_series.tim...
0c44f2b26a71e76b658180e1817cc3dfbeb375e0
3,655,974
def test_device_bypass(monkeypatch): """Test setting the bypass status of a device.""" _was_called = False def _call_bypass(url, body, **kwargs): nonlocal _was_called assert url == "/appservices/v6/orgs/Z100/device_actions" assert body == {"action_type": "BYPASS", "device_id": [6023...
17e2a2f1f7c8ef1a7ef32e8aacb40f8f7fe16c53
3,655,975
import re import importlib def import_config_module( cfg_file ): """ Returns valid imported config module. """ cfg_file = re.sub( r'\.py$', '', cfg_file ) cfg_file = re.sub( r'-', '_', cfg_file ) mod_name = 'config.' + cfg_file cfg_mod = importlib.import_module( mod_name ) if not hasattr(...
4cb25a56df0f26f0f3c4917aad2ca4cd40e4797f
3,655,976
import multiprocessing def process_batches(args, batches): """Runs a set of batches, and merges the resulting output files if more than one batch is included. """ nbatches = min(args.nbatches, len(batches)) pool = multiprocessing.Pool(nbatches, init_worker_thread) try: batches = pool....
dbd893773e6a5fed1d68a48c875741e4ce963ae6
3,655,977
def tripledes_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts 3DES ciphertext in CBC mode using either the 2 or 3 key variant (16 or 24 byte long key) and PKCS#5 padding. :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The ciphertext...
bf6d7efaade2cb7ce2f6abf7cea89a04fdbb3897
3,655,978
def kruskal_chi2_test(data=None, alpha=0.05, precision=4): """ col = 要比較的 target row = data for each target """ if type(data) == pd.DataFrame: data = data.copy().to_numpy() alldata = np.concatenate(data.copy()) else: alldata = np.concatenate(data.copy()) k = data.sha...
3b89e14e7072cbb6375b0c1ead8320c5643aacd1
3,655,979
def add_new_action(action, object_types, preferred, analyst): """ Add a new action to CRITs. :param action: The action to add to CRITs. :type action: str :param object_types: The TLOs this is for. :type object_types: list :param preferred: The TLOs this is preferred for. :type preferred...
2b54c3766d9793a1c6598402bf7a5b1103bb324b
3,655,980
import multiprocessing import asyncio def test_PipeJsonRpcSendAsync_5(): """ Specia test case. Two messages: the first message times out, the second message is send before the response from the first message is received. Verify that the result returned in response to the second message is received...
a1939e03f4c9992d84ac52a35b975f20077a2161
3,655,981
from typing import Collection import os import json def RACEDataset(race_type): """ Loads a RACE dataset given the type (see the RACEType enum). Any error during reading will generate an exception. Returns a Pandas DataFrame with 5 columns: * 'article': string * 'question': string * 'answ...
84407168b73ccdb954dc441a95117fbadf6a0ed1
3,655,982
import re def tpc(fastas, **kw): """ Function to generate tpc encoding for protein sequences :param fastas: :param kw: :return: """ AA = kw['order'] if kw['order'] is not None else 'ACDEFGHIKLMNPQRSTVWY' encodings = [] triPeptides = [aa1 + aa2 + aa3 for aa1 in AA for aa2 in AA for ...
b8017356980b266d78d85a867aee97c0d79ec5e5
3,655,983
def _uninstall_flocker_centos7(): """ Return an ``Effect`` for uninstalling the Flocker package from a CentOS 7 machine. """ return sequence([ run_from_args([ b"yum", b"erase", b"-y", b"clusterhq-python-flocker", ]), run_from_args([ b"yum", b"erase", b...
0d8f068857cbc25743b644d067fe70efffb644f0
3,655,984
import logging import os import sys def get_memory_banks_per_run(coreAssignment, cgroups): """Get an assignment of memory banks to runs that fits to the given coreAssignment, i.e., no run is allowed to use memory that is not local (on the same NUMA node) to one of its CPU cores.""" try: # read...
607d55889e3c792c24a1976a75b28f24b9adea3d
3,655,985
import requests def authenticate(username, password): """Authenticate with the API and get a token.""" API_AUTH = "https://api2.xlink.cn/v2/user_auth" auth_data = {'corp_id': "1007d2ad150c4000", 'email': username, 'password': password} r = requests.post(API_AUTH, json=auth_data, timeo...
9675227b5ff4f58d79bafffc0407366a26d638bd
3,655,986
def filter_hashtags_users(DATAPATH, th, city): """ cleans target_hashtags by removing hashtags that are used by less than 2 users replaces hahstags by ht_id and saves to idhashtags.csv creates entropy for each ht_id and saves to hashtag_id_entropies.csv prints std output :param DATAPATH: :pa...
60e0b02f9bbdccae32958717fd8608aa1932386e
3,655,987
def cluster_set_state(connection: 'Connection', state: int, query_id=None) -> 'APIResult': """ Set cluster state. :param connection: Connection to use, :param state: State to set, :param query_id: (optional) a value generated by client and returned as-is in response.query_id. When the paramete...
88b05a617e17574961e44d5a88bec1ac4da0be95
3,655,988
def get_all(data, path): """Returns a list with all values in data matching the given JsonPath.""" return [x for x in iterate(data, path)]
592fee87b3b4be171d4e4a19b013b99551768f75
3,655,989
def extract_information_from_blomap(oneLetterCodes): """ extracts isoelectric point (iep) and hydrophobicity from blomap for each aminoacid Parameters ---------- oneLetterCodes : list of Strings/Chars contains oneLetterCode for each aminoacid Returns ------- float, float ...
d36e16a0e35d744f1001752c98d09035b3e581c6
3,655,990
def partitions(n): """ Return a sequence of lists Each element is a list of integers which sum to n - a partition n. The elements of each partition are in descending order and the sequence of partitions is in descending lex order. >>> list(partitions(4)) [[3,...
042759c97031baee7c958d59b3a432b52111a696
3,655,991
def create_request_element(channel_id, file_info, data_id, annotation): """ create dataset item from datalake file :param channel_id: :param file_id: :param file_info: :param label_metadata_key: :return: """ data_uri = 'datalake://{}/{}'.format(channel_id, file_info.file_id) da...
9fad37428e2608d47b2d0d57d075c0fbd9292b46
3,655,992
from typing import Mapping from typing import Iterable def _categorise(obj, _regex_adapter=RegexAdapter): """ Check type of the object """ if obj is Absent: return Category.ABSENT obj_t = type(obj) if issubclass(obj_t, NATIVE_TYPES): return Category.VALUE elif callable(ob...
549f21bee43f619fea7c2a09940cda1ce03e4e8c
3,655,993
def remove_key(d, key): """Safely remove the `key` from the dictionary. Safely remove the `key` from the dictionary `d` by first making a copy of dictionary. Return the new dictionary together with the value stored for the `key`. Parameters ---------- d : dict The dictionary from w...
5695b18675b52f4ca8bc3cba1ed0104425e7a04f
3,655,994
import csv import six def tasks_file_to_task_descriptors(tasks, retries, input_file_param_util, output_file_param_util): """Parses task parameters from a TSV. Args: tasks: Dict containing the path to a TSV file and task numbers to run variables, input, and output parame...
7c195e8c09b439d39fca105fa3303f74c43538c1
3,655,995
import os import torch def load_model(filename, folder=None): """ Load a model from a file. :param filename: name of the file to load the model from :param folder: name of the subdirectory folder. If given, the model will be loaded from the subdirectory. :return: model from the file """ ...
b4319796de4b05bf83d657c29d31124016dd9070
3,655,996
def spreadplayers(self: Client, x: RelativeFloat, y: RelativeFloat, spread_distance: float, max_range: float, victim: str) -> str: """Spreads players.""" return self.run('spreadplayers', x, y, spread_distance, max_range, victim)
6577d7209d19a142ae9e02804b84af921df3224c
3,655,997
def get_version(): """Returns single integer number with the serialization version""" return 2
f25ad858441fcbb3b5353202a53f6ebaa8874e4d
3,655,998
def format_result(func): """包装结果格式返回给调用者""" @wraps(func) def wrapper(*args, **kwargs): ret = {} try: data = func(*args, **kwargs) if type(data) is Response: return data ret['data'] = data ret['success'] = True ret['m...
53109217a9fe6fbc00250a7b8dfd6b295e47e12b
3,655,999