content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Union from typing import List def sym_to_elm(symbols: Union[str, List, np.ndarray], order: Union[np.ndarray, List[str]]): """Transform symbols to elements.""" if not isinstance(order, list): order = order.tolist() if not isinstance(symbols, (str, list)): s...
16e2a88b353556068e8c1a3fa7c831264fd9f3c5
8,269
def set_custom_field( custom_field_id: str = None, person_id: str = None, owner_id: str = None, term_id: str = None, value: str = None, option_index: str = None): """ Sets a custom field value for a particular person, organization, or donation. :param custom_...
3d9471c62644e8e19f7b6faa03f3b503d5db7673
8,270
def ixn_is_increases_activity(ixn: ChemGeneIxn): """Checks if the interaction results in the decrease of the activity of the protein of the gene :param pyctd.manager.models.ChemGeneIxn ixn: A chemical-gene interaction :rtype: bool """ return _ixn_is_changes_protein(ixn, 'increases^activity')
0b324a953ed2a90a9a357965ad4e5ef4a635c2df
8,271
def load(csv, sep=';'): """ Load data into dataframe :param csv: :param sep: :return: """ data = pd.read_csv(csv, sep=sep) return data
da988e31601b13a767178b4d6613d948100ddfc9
8,272
def count_lost_norm4(matrix): """calculate 4th lost points: Proportion of dark modules in entire symbol: 50 + (5 + k) or 50 - (5 + k), return k * 10 Args: matrix ([type]): [description] Returns: [int]: [description] """ dark_sum = np.sum(matrix) modules_num = matrix.size ...
ad05892952af5cfc5dbd8273bbc1357d31b1a295
8,274
def sumaDigits(s): """assumes s is a string and returns the sum of the decimal digits in s. For example if s is 'a2b3c' it returns 5""" suma = 0 for c in s: try: suma+=int(c) except ValueError: continue return suma
47b09476925d45741d97eca5362e736f83a8185d
8,275
def f5_list_policy_file_types_command(client: Client, policy_md5: str) -> CommandResults: """ Get a list of all policy file types. Args: client (Client): f5 client. policy_md5 (str): MD5 hash of the policy. """ result = client.list_policy_file_types(policy_md5) table_name = 'f5...
b2b57d281b0cc3ea0ff7430d2033255071761a46
8,276
def recurrent_layer(input, act=None, bias_attr=None, param_attr=None, name=None, reverse=False, layer_attr=None): """ Simple recurrent unit layer. It is just a fully connect layer through both...
b616d372a9324c11aa1bb524d96844ce1e8c47e5
8,277
def mean_center(X): """ @param X: 2-dimensional matrix of number data @type X: numpy array @return: Mean centered X (always has same dimensions as X) """ (rows, cols) = shape(X) new_X = zeros((rows, cols), float) _averages = average(X, 0) for row in rang...
54885596c95856b0ce0f7fe68d2922641e7a830a
8,278
import csv from io import StringIO def process_xlsform(xls, default_name): """ Process XLSForm file and return the survey dictionary for the XLSForm. """ # FLOW Results package is a JSON file. file_object = None if xls.name.endswith('csv'): # a csv file gets closed in pyxform, make a ...
af695bef6f063b2bfa7862e856e16ab42be2db96
8,280
def unflatten(X: np.ndarray, Y: np.ndarray, shape: tuple): """ Unflattens images with shape defined by list of tuples s X is an array (1D), unflattened to 2D Y is an array (1D) of flattened mask (flattened 2D label) array Not that X and Y are not compatible dimensions s denotes dimensions ...
7a1a79b165d44efd55c2e66936e072298cd5d648
8,281
from typing import Dict from typing import Any from typing import List import logging from pathlib import Path def collate_features(model_config: Dict[str, Any], dummy_features: List[str]) -> List[str]: """Saves and returns final list of simple and dummy features.""" simple_features = list(model_config.get("s...
e66e3aceb0b5bf093a4fc3165a30694875903b73
8,282
from typing import Type def new_dga(*, key_mo=None, pred=None, deg_diff=None) -> Type[DgaGb]: """Return a dynamically created subclass of GbDga. When key_mo=None, use revlex ordering by default.""" class_name = f"GbDga_{DgaGb._index_subclass}" DgaGb._index_subclass += 1 if deg_diff is not None: ...
32cfa58eec7512dd7b39b2298608df538a232ef9
8,283
def is_xarray(array): """Return True if array is a xarray.DataArray Parameters ---------- array : array-like Returns ------- test : bool """ return isinstance(array,xr.DataArray)
edf14a0c87e6590e6a583425ec830e51defe5fa1
8,284
from typing import Counter def _check_duplicate_gnames(block_id, block_dict, extra_args): """ Return False if any duplicate group names exist in /etc/group file, else return True """ gnames = _execute_shell_command("cat /etc/group | cut -f1 -d\":\"", python_shell=True).strip() gnames = gnames.spli...
2a181ca67f87f0f90eb97c1df0e7ae8db6ee2206
8,285
def join_nonempty(l): """ Join all of the nonempty string with a plus sign. >>> join_nonempty(('x1 + x2 + x1:x2', 'x3 + x4')) 'x1 + x2 + x1:x2 + x3 + x4' >>> join_nonempty(('abc', '', '123', '')) 'abc + 123' """ return ' + '.join(s for s in l if s != '')
041948f95caaef14cb96e761f08b4a84fba37d6e
8,286
import torch def correct_msa_restypes(protein): """Correct MSA restype to have the same order as rc.""" new_order_list = rc.MAP_HHBLITS_AATYPE_TO_OUR_AATYPE new_order = torch.tensor( [new_order_list] * protein["msa"].shape[1], device=protein["msa"].device, ).transpose(0, 1) protei...
881736333e3153c9c7713f7a54252eba705b7bb8
8,287
def plot_bootstrap_lr_grp(dfboot, df, grp='grp', prm='premium', clm='claim', title_add='', force_xlim=None): """ Plot bootstrapped loss ratio, grouped by grp """ count_txt_h_kws, mean_txt_kws, pest_mean_point_kws, mean_point_kws = _get_kws_styling() if dfboot[grp].dtypes != 'objec...
11a0276ab1eac233db537943b5af67f0452f89db
8,288
def ajax_user_search(request): """ returns the user search result. currently this is not used since search user feature changed to form post. """ if request.method=='POST': username=request.POST.get('username','') users=User.objects.filter(username__contains=username) try: ...
8318b881280e47ff28ea8db259df607b1e5bf7fb
8,289
def shortest_path(start, end): """ Using 2-way BFS, finds the shortest path from start_position to end_position. Returns a list of moves. You can use the rubik.quarter_twists move set. Each move can be applied using rubik.perm_apply """ if start == (7, 8, 6, 20, 18, 19, 3, 4, 5, 16, 17, 15...
c75b54b434c09f6d570f79c40453bd465a2a439b
8,290
def to_matrix_vector(transform): """ Code from nilearn module, available at: https://github.com/nilearn/nilearn/blob/master/nilearn/image/resampling.py Split an homogeneous transform into its matrix and vector components. The transformation must be represented in homogeneous coordinates. It is ...
b971f3b53199a16bbf2343ed544389cbc21f1644
8,292
def sieveEr(N): """ input: positive integer 'N' > 2 returns a list of prime numbers from 2 up to N. This function implements the algorithm called sieve of erathostenes. """ # precondition assert isinstance(N,int) and (N > 2), "'N' must been...
8d48d2a491341d5302307597ad64ac4a37b1abb8
8,293
def validate_fields(item, fields=None): """ Check that all requested fields were returned :param item: comment or submission :param fields: list[str] :return: list[str] """ actual_fields = item.d_.keys() if fields is None: requested_fields = actual_fields else: requ...
88bd6d20ba1cc04f8478128f7f32192ef680762b
8,294
import warnings def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees, verbose=0, class_weight=None, target_imbalance_ratio=None): """Private function used to fit a single tree in parallel.""" if verbose > 1: print("building tree %d of %d" % (tree_idx...
a5c027d96bd96522544e56bd427ae39a5075e6b8
8,295
from typing import Iterable def remove_nones(sequence: Iterable) -> list: """Removes elements where bool(x) evaluates to False. Examples -------- Normal usage:: remove_nones(['m', '', 'l', 0, 42, False, True]) # ['m', 'l', 42, True] """ # Note this is redundant with it.chain ...
975c0104b3cc05bb82fa211c1b85b49c7d3cb174
8,296
from typing import List import pathlib def retrieve(passed: List[str]) -> List[str]: """ Retrieves all items that are able to be converted, recursively, from the passed list. Parameters ---------- passed: List[str] The items to search. Returns ------- List[str]: A...
6789255e302caf9dc6e481df532acec20dfc6b3c
8,298
from typing import List from typing import Optional from typing import Dict from typing import Tuple from typing import Any def get_out_of_sample_best_point_acqf( model: Model, Xs: List[Tensor], X_observed: Tensor, objective_weights: Tensor, mc_samples: int = 512, fixed_features: Optional[Dict...
a6331759833b4715275fdb3ca7d19c237c2c7e55
8,299
def removeBots(gdf, bot_list): """ A Function for removing Twitter bots. Parameters ---------- gdf: <gpd.GeoDataFrame> A GeoDataFrame from which Twitter bots should be removed. bot_list: <list> Input either 'home_unique_days' or 'home_unique_weeks' ...
e938f46bcf5c87dfa81db96f127c88d948f061db
8,300
def getinput(prompt): """>> getinput <prompt> Get input, store it in '__input__'. """ local_dict = get_twill_glocals()[1] inp = input(prompt) local_dict['__input__'] = inp return inp
db26e8361518f1728edfb15c6417586f8c3ca73d
8,301
def update_trails(force=False, offline=False): """ Update trails from feeds """ success = False trails = {} duplicates = {} try: if not os.path.isdir(USERS_DIR): os.makedirs(USERS_DIR, 0755) except Exception, ex: exit("[!] something went wrong during creatio...
2ff83a3681899d6dffa8bdcedcbb7e9839bbc919
8,304
def bq_to_rows(rows): """Reformat BigQuery's output to regular pnguin LOD data Reformat BigQuery's output format so we can put it into a DataFrame Args: rows (dict): A nested list of key-value tuples that need to be converted into a list of dicts Returns: list: A list of dictionaries ...
9ff842d1c41d7ebe5c822d4c07b2f26b5524b0fe
8,305
def network_config(session, args): """network config functions""" cmd = pluginlib.exists(args, 'cmd') if not isinstance(cmd, basestring): msg = "invalid command '%s'" % str(cmd) raise pluginlib.PluginError(msg) return if cmd not in ALLOWED_NETWORK_CMDS: msg = "Dom0 execut...
d2a551166e7d5c445f1cba6404a3e526f4e7ecdd
8,306
def album_id(items, sp_album): """Iterate through results to find correct Discogs album id.""" try: artist = sp_album['artists'][0].lower().replace(" ", "") except IndexError: artist = "" owners = -1 discogs_id = -1 similarity = 0 title = sp_album['name'].lower().replace(" "...
1c8f0f870c1a0c6c71de115ae6a0d15cf235af6f
8,308
def css_defaults(name, css_dict): """Находит первое значение по-умолчанию background -> #FFF color -> #FFF content -> "" """ cur = css_dict.get(name) or css_dict.get(name[1:-1]) if cur is None: return None default = cur.get('default') if default is not None: return de...
8418af5e27dfc85a3ec70dea2e7416595ee86a1f
8,309
def yn_zeros(n,nt): """Compute nt zeros of the Bessel function Yn(x). """ return jnyn_zeros(n,nt)[2]
384ebc8fec6109de36d3c17d265b53c01a2195b6
8,310
def get_chebi_parents(chebi_ent): """ Get parents of ChEBI entity :param chebi_ent: :return: """ if hasattr(chebi_ent, 'OntologyParents'): return [ent.chebiId for ent in chebi_ent.OntologyParents if (ent.type == 'is a')] else: return []
bfdf3cbfae45c07a9f5f97a85f1c64f680ac49fc
8,311
def average_saccades_time(saccades_times): """ :param saccades_times: a list of tuples with (start_time_inclusive, end_time_exclusive) :return: returns the average time of saccades """ return sum([saccade_time[1] - saccade_time[0] for saccade_time in saccades_times]) / len(saccades...
a22a5d89ddd4317fa10ed6f5d920f17560028514
8,312
from typing import Optional from typing import List from typing import Tuple import logging def solve_tsp_local_search( distance_matrix: np.ndarray, x0: Optional[List[int]] = None, perturbation_scheme: str = "two_opt", max_processing_time: Optional[float] = None, log_file: Optional[str] = None, ) ...
f1b77b7fb3d1b83d18a7f2ba99d4a266e98f8462
8,313
def split(self, split_size_or_sections, dim=0, copy=True): """Return the split chunks along the given dimension. Parameters ---------- split_size_or_sections : Union[int, Sequence[int] The number or size of chunks. dim : int, optional, default=0 The dimension to split. copy : bo...
cd6725af62fc0f5cde758e23add206a2ddb7c0af
8,314
def HighFlowSingleInletTwoCompartmentGadoxetateModel(xData2DArray, Ve: float, Kbh: float, Khe: float, dummyVariable): """This function contains the algorithm for calculating how concentration varies with time ...
18684058926b9362b7a6b495cf1f48fd8c3188e4
8,315
import struct import numpy def read_cz_lsminfo(fh, byteorder, dtype, count, offsetsize): """Read CZ_LSMINFO tag from file and return as dict.""" assert byteorder == '<' magic_number, structure_size = struct.unpack('<II', fh.read(8)) if magic_number not in (50350412, 67127628): raise ValueError...
1bcf4d22315503e2f21fcbacd6a0797fc2fd16a7
8,316
def mi_alignment( alignment, mi_calculator=mi, null_value=DEFAULT_NULL_VALUE, excludes=DEFAULT_EXCLUDES, exclude_handler=None, ): """Calc mi over all position pairs in an alignment alignment: the full alignment object mi_calculator: a function which calculated MI from two entropies and ...
f576b8c4df018bba787c7c46091e52b70badd9de
8,317
def Jaccard3d(a, b): """ This will compute the Jaccard Similarity coefficient for two 3-dimensional volumes Volumes are expected to be of the same size. We are expecting binary masks - 0's are treated as background and anything else is counted as data Arguments: a {Numpy array} -- 3D array ...
a4452e523e484db50b99d36f9ee67c3508678ea6
8,318
def get_pod_obj(name, namespace=None): """ Returns the pod obj for the given pod Args: name (str): Name of the resources Returns: obj : A pod object """ ocp_obj = OCP(api_version='v1', kind=constants.POD, namespace=namespace) ocp_dict = ocp_obj.get(resource_name=name) p...
464aa15574ee65672f7963e6e5426753ff98ee72
8,319
def median_rank(PESSI_SORT, OPTI_SORT, A): """ Calculates the median rank of each action. :param PESSI_SORT: Dictionary containing the actions classified according to the pessimistic procedure. :param OPTI_SORT: Dictionary containing the actions classified according to the optimistic procedure. :pa...
7f760847ae2a69edf07a593a6ebfb84dce4c4103
8,322
from typing import Optional import json def get_token( event: ApiGatewayEvent, _context: LambdaContext, node_api: Optional[NodeApi] = None ) -> dict: """Get token details given a token uid. *IMPORTANT: Any changes on the parameters should be reflected on the `cacheKeyParameters` for this meth...
7be9e80aef60ad7f5befa3f21b597541eb79c4d0
8,323
import re def update_dictionary_entries(old_entries, need_to_add): """ Expects dictionary of species entries and unique list of species (as SMILES) that need to be added Creates new entries for the species that need to be added Returns old and new entries """ list(set(need_to_add)) fo...
9182c42349b76a7e72c3c1c134cb347ed0bd2a2d
8,324
def four_rooms(dims, doorway=1.): """ Args: dims: [dimx, dimy] dimensions of rectangle doorway: size of doorway Returns: adjmat: adjacency matrix xy: xy coordinates of each state for plotting labels: empty [] """ half_x, half_y = (dims[0]*.5, dims[1]*.5) quarter_x,...
0744ab4b38ab0b5d0b96c53d45c88dc1e37f932e
8,326
def get_verse_url(verse: str) -> str: """Creates a URL for the verse text.""" node = CONNECTIONS[verse] volume = scripture_graph.VOLUMES_SHORT[node['volume']].lower() if volume == 'bom': volume = 'bofm' elif volume == 'd&c': volume = 'dc-testament' elif volume == 'pogp': ...
37ce47aa6e18e3f550e9adacb3bf16affb6154f8
8,327
from typing import cast from typing import List def get_ws_dependency_annotation(state: GlobalState) -> WSDependencyAnnotation: """ Returns the world state annotation :param state: A global state object """ annotations = cast( List[WSDependencyAnnotation], list(state.world_state.get_...
ba44455594c4a1f63dac5adec95b2efe6a4b2af6
8,328
def get_gin_confg_strs(): """ Obtain both the operative and inoperative config strs from gin. The operative configuration consists of all parameter values used by configurable functions that are actually called during execution of the current program, and inoperative configuration consists of all p...
9f9081aafa6a4a43be37edd4002ee17ac518f5d4
8,329
def L(x, c, gamma): """Return c-centered Lorentzian line shape at x with HWHM gamma""" return gamma / (np.pi * ((x - c) ** 2 + gamma ** 2))
853ba2c978a50f9f43915342caebed2e3d5ead8d
8,330
import socket import logging def request_data_from_weather_station(): """ Send a command to the weather station to get current values. Returns ------- bytes received data, 0 if error occurred """ sock = socket.create_connection((WEATHER_HOST, WEATHER_PORT), GRAPHITE_TIMEOUT) s...
0bf28c3cf5db1f14446aa9866b9854b435378439
8,331
def solution2(arr): """improved solution1 #TLE """ if len(arr) == 1: return arr[0] max_sum = float('-inf') l = len(arr) for i in range(l): local_sum = arr[i] local_min = arr[i] max_sum = max(max_sum, local_sum) for j in range(i + 1, l): local_sum...
835240bb4f70e5b6425a6ac0d2a4210e2c8a0ad0
8,332
def hillas_parameters_4(pix_x, pix_y, image, recalculate_pixels=True): """Compute Hillas parameters for a given shower image. As for hillas_parameters_3 (old Whipple Fortran code), but more Pythonized MP: Parameters calculated as Whipple Reynolds et al 1993 paper: http://adsabs.harvard.edu/abs/1993ApJ...
87fa302b6e6b1b81b66d8e8fb7cc4e34da1583d9
8,333
from typing import List from typing import Optional def create_intrusion_set( name: str, aliases: List[str], author: Identity, primary_motivation: Optional[str], secondary_motivations: List[str], external_references: List[ExternalReference], object_marking_refs: List[MarkingDefinition], ) ...
be8df574ac1be08c724620cf20495922cff5918e
8,334
from ..core import Tensor def broadcast_to(tensor, shape): """Broadcast an tensor to a new shape. Parameters ---------- tensor : array_like The tensor to broadcast. shape : tuple The shape of the desired array. Returns ------- broadcast : Tensor Raises ------...
3c738227f98d4ca8a6b1c0cc98cea769b697a987
8,335
def admin_required(handler_method): """Require that a user be an admin. To use it, decorate your method like this:: @admin_required def get(self): ... """ @wraps(handler_method) def check_admin(*args, **kwargs): """Perform the check.""" if current_user....
03cc9e9cd32ab0b239f45c70fffcd85108b0173c
8,336
import requests def get(path): """Get.""" verify() resp = requests.get(f"{URL}{path}", headers=auth) try: resp.raise_for_status() except requests.exceptions.HTTPError as e: error_msg(str(e)) return return resp.json()
c1661ac0e07ff467f15a429fe6fbf09d53a34ef9
8,337
def combine_dataframes(dfs: [pd.DataFrame]) -> pd.DataFrame: """ Receives a list of DataFrames and concatenates them. They must all have the same header. :param dfs: List of DataFrames :return: Single concatenated DataFrame """ df = pd.concat(dfs, sort=False) return df
b7c1cd94870638a3a975ea7c4f9c284cbd4ee0a9
8,338
import numpy def _approx_sp(salt,pres): """Approximate TDl at SP. Approximate the temperature and liquid water density of sea-ice with the given salinity and pressure. :arg float salt: Salinity in kg/kg. :arg float pres: Pressure in Pa. :returns: Temperature and liquid water density ...
b45727ad6f08cead1eb32477c8691233c38e9387
8,342
def _get_connection_params(resource): """Extract connection and params from `resource`.""" args = resource.split(";") if len(args) > 1: return args[0], args[1:] else: return args[0], []
87cdb607027774d58d1c3bf97ac164c48c32395c
8,343
from typing import Union import requests from typing import List from typing import Dict from typing import Any from typing import Callable from typing import cast import operator def listdata( resp: Union[requests.Response, List[Dict[str, Any]]], *keys: Union[str, Callable[[], bool]], sort: Union[bool, s...
878df7c56f97a3fe2c92499955bb760888673bbc
8,345
def get_current_pkg(): """ Returns: パッケージ名 (str): 常に大文字表記で返ってくる """ return eval_foreign_vm_copy("(send *package* :name)")
16c768dace7a4e88f7d7eb21aab58ce917f2ce43
8,347
def _normalise_trigger(value: float) -> float: """ Helper function used to normalise the controller trigger values into a common range. :param value: Value to be normalised :raises: ValueError :return: Normalised value """ return _normalise(value, _HARDWARE_TRIGGER_MIN, _HARDWARE_TRIGGER_MA...
d5653da9f625896865a3fd9601d3f2707cba6e8c
8,348
def full_process(s): """Process string by -- removing all but letters and numbers -- trim whitespace -- force to lower case""" if s is None: return "" #Here we weill force a return of "" if it is of None, empty, or not valid #Merged from validate_string try: ...
071ba938708f170b914576895f7cab1aa8cb1cc3
8,349
import math def ldexp(space, x, i): """ldexp(x, i) -> x * (2**i) """ return math2(space, math.ldexp, x, i)
ef083d77ff36acbc7d7dfede0772e9e8bf34b17a
8,350
def menu(): """ Print a menu with all the functionalities. Returns: The choice of the user. """ print "=" * 33 + "\nMENU\n" + "=" * 33 descriptions = ["Load host from external file", "Add a new host", "Print selected hosts", "C...
29bdce7c50cea7d9bbc5a27b71c803db91fe4eef
8,351
from typing import Optional from typing import Container from typing import List async def objects_get(bucket: Optional[str] = None, index: Index = Depends(Provide[Container.index]), buckets: Buckets = Depends(Provide[Container.buckets])) -> List[Object]: """ search...
f6949922ac5c355469fbaf450758180ac422f33a
8,352
import json def thumbnail_create(request, repo_id): """create thumbnail from repo file list return thumbnail src """ content_type = 'application/json; charset=utf-8' result = {} repo = get_repo(repo_id) if not repo: err_msg = _(u"Library does not exist.") return HttpResp...
876f9af7d61336f0f91f0b7277943265fb6e7a35
8,353
import uvloop import asyncio def initialize_event_loop(): """Attempt to use uvloop.""" try: asyncio.set_event_loop_policy(uvloop.EventLoopPolicy()) except ImportError: pass return asyncio.get_event_loop()
cba229f5330bc89a60607f9523d3727b6db30094
8,354
def _setup_pgops(multi_actions=False, normalise_entropy=False, sequence_length=4, batch_size=2, num_mvn_actions=3, num_discrete_actions=5): """Setup polices, actions, policy_vars and (optionally) entropy_scale_op.""" t = sequence_l...
5d6ddc58db39496fed3c99c214c1f835ee49f2ea
8,355
async def definition_delete(hub, ctx, name, **kwargs): """ .. versionadded:: 1.0.0 Delete a policy definition. :param name: The name of the policy definition to delete. CLI Example: .. code-block:: bash azurerm.resource.policy.definition_delete testpolicy """ result = False...
7f3e6b2b3b6bbcea590a042b923fd797a56840ee
8,356
import optparse def parse_options(argv): """Parses and checks the command-line options. Returns: A tuple containing the options structure and a list of categories to be traced. """ usage = 'Usage: %prog [options] [category1 [category2 ...]]' desc = 'Example: %prog -b 32768 -t 15 gfx input view sche...
df6910fb6600f8c4573eced74dfcd8bc6ec1a5ad
8,357
def get_data_for_file(folder, ports): """Parses the pcap files in the specified folder, and outputs data for the specified ports """ # Load private keys and port->provider mappings keys, providers, nodes = read_keys(os.path.join(folder, 'keys')) print 'Loading packets' # Load packets with op...
be81404b54231bde3444d3b3545cafa1c836c074
8,358
async def create_channel_in_db( context: 'Context', game_config: 'GameConfig', channel_id: str, finished: bool = False ) -> Channel: """Utility function to create a channel in the database :param context: The Discord Context. :param game_config: The GameConfig to use for extra info. :pa...
a2ea09b436c4eeabd37c0c8220d791d89db3912f
8,359
def retry(times, func, *args, **kwargs): """Try to execute multiple times function mitigating exceptions. :param times: Amount of attempts to execute function :param func: Function that should be executed :param args: *args that are passed to func :param kwargs: **kwargs that are passed to func ...
7e9fd482a70409d62ea108ddaa83440fcd2b024f
8,360
def _apply_prediction(G, func, ebunch=None): """Applies the given function to each edge in the specified iterable of edges. `G` is an instance of :class:`networkx.Graph`. `ebunch` is an iterable of pairs of nodes. If not specified, all non-edges in the graph `G` will be used. """ if ebunc...
5e046bf7608337f6ed046a71b8a3983f53109d46
8,361
def import_class(class_object): """ Import a class given a string with its name in the format module.module.classname """ d = class_object.rfind(".") class_name = class_object[d + 1:len(class_object)] m = __import__(class_object[0:d], globals(), locals(), [class_name]) return getattr(m, clas...
82df3ed7d646bd423ccefacc00493e917f13c430
8,362
def anonymous_fun_0_(empty_closure_0_): """ empty_closure_0_: () """ def anonymous_fun_1_(par_map_input_1_): """ par_map_input_1_: Double """ def anonymous_fun_2_(par_map_input_0_): """ par_map_input_0_: Double """ def anonymous_fun_3_(fused_input_0_): """ ...
2ea827153fadc359d056f4b981dbb5d3bf3711ee
8,363
def get_examples(mode='train'): """ dataset[0][0] examples """ examples = { 'train': ({'id': '0a25cb4bc1ab6f474c699884e04601e4', 'title': '', 'context': '第35集雪见缓缓张开眼睛,景天又惊又喜之际,长卿和紫萱的仙船驶至,见众人无恙,' '也十分高兴。众人登船,用尽合力把自身的真气和水分输给她。雪见终于醒过来了,但却一脸木然,全无反应。众人向常胤求助,却发现人世界竟没有雪见的身世纪录。长卿询问清微的身世,...
0b5fb45bcac847cd3f7e7b3e5b264e350c891211
8,364
from IPython.core.display import HTML def display_tables(tables, max_rows=10, datetime_fmt='%Y-%m-%d %H:%M:%S', row=True): """Display mutiple tables side by side on a Jupyter Notebook. Args: tables (dict[str, DataFrame]): ``dict`` containing table names and pandas DataFrames. max_...
904a900e97aab4809ea5057025a5a7a075429942
8,365
def prepare_default_result_dict(key, done, nodes): """Prepares the default result `dict` using common values returned by any operation on the DHT. Returns: dict: with keys `(k, d, n)` for the key, done and nodes; `n` is a list of `dict` with keys `(i, a, x)` for id, address, and expirat...
420beb66352fee7b4d38f6b4cf628cbaa86a03df
8,367
def MatchScorer(match, mismatch): """Factory function that returns a score function set to match and mismatch. match and mismatch should both be numbers. Typically, match should be positive and mismatch should be negative. Resulting function has signature f(x,y) -> number. """ def scorer(x, y...
fe3829efc64cb4d9785e52b8af6949c147481902
8,368
import random def random_choice(context: RuntimeContext, *choices): """Template helper for random choices. Supports structures like this: random_choice: - a - b - <<c>> Or like this: random_choice: - choice: pick: A probability: 50% ...
cc74c4106e2263e4b46ef25ed5cb83839040bb5f
8,369
def _compute_paddings(height_pad_amt, width_pad_amt, patch_axes): """Convert the total pad amounts to the format needed by tf.pad().""" top_pad = height_pad_amt // 2 bottom_pad = height_pad_amt - top_pad left_pad = width_pad_amt // 2 right_pad = width_pad_amt - left_pad paddings = [[0, 0] for _ in range(4...
3a5154ba0fa6808bc6dc8e20fcb4203324762ba9
8,370
def tab_size(computer, name, value): """Compute the ``tab-size`` property.""" if isinstance(value, int): return value else: return length(computer, name, value)
f121cc308f4c88e021e240767ae03479a26a46f6
8,371
def match_complete(user_id=""): """Switch 'complete' to true in matches table for user, return tallies.""" print("match_complete", user_id) user = sm.get_user(user_id) # Note: 0/1 used for 'complete' b/c Booleans not allowed in SimpleObjects this_match, i = current_match_i(user) temp = this_match['complete'...
1af499c671f209ba8bc9333e372947c90b9a2b8c
8,372
def compute_range_map(flow, downsampling_factor=1, reduce_downsampling_bias=True, resize_output=True): """Count how often each coordinate is sampled. Counts are assigned to the integer coordinates around the sampled coordinates using weights from ...
fa73194435ae893dcd359f93f1488a6b654f8d31
8,373
from typing import List def get_wer(refs: List[str], hyps: List[str]): """ args: refs (list of str): reference texts hyps (list of str): hypothesis/prediction texts """ n_words, n_errors = 0, 0 for ref, hyp in zip(refs, hyps): ref, hyp = ref.split(), hyp.split() n_w...
fb142f4d048bffca1a1119e4a2e7c68e1effcbfc
8,374
def get_first(somelist, function): """ Returns the first item of somelist for which function(item) is True """ for item in somelist: if function(item): return item return None
81976910c46102d3b15803d215f3bf5a554f9beb
8,375
def np_cross(a, b): """ Simple numba compatible cross product of vectors """ return np.array([ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0], ])
0d19a1bfdf7bf5d6835203f61654edc8263b3bbd
8,376
import itertools def remove_duplicates(llist): """ Removes any and all duplicate entries in the specified list. This function is intended to be used during dataset merging and therefore must be able to handle list-of-lists. :param llist: The list to prune. :return: A list of unique elements ...
cbdf1a4db99a7a5fac37f25776cc1387ed8c54e0
8,379
def images_in_bbox(bbox: dict, **filters) -> str: """ Gets a complete list of images with custom filter within a BBox :param bbox: Bounding box coordinates Format:: >>> { ... 'west': 'BOUNDARY_FROM_WEST', ... 'south': 'BOUNDARY_FROM_SOUTH', ...
317554d0f666753cdfc8a3657f7f0b92d5af141d
8,380
def find_start_time_from_afl(project_base_dir): """ Finds the start time of a project from afl directories. This time is taken from the fuzzer_stats entry of the first config iteration's fuzzer. """ try: first_main_dir = main_dirs_for_proj(project_base_dir)[0] except: #if fu...
f8f21b65e1901615e16953da48ac39008dcb240b
8,381
def filter_none_values(d, recursive=True): """ Returns a filtered copy of a dict, with all keys associated with 'None' values removed. adapted from: http://stackoverflow.com/q/20558699 adapted from: http://stackoverflow.com/a/20558778 :param d: a dict-like object. :param recursive: If True, pe...
2a25ae331c99196c6f6eed7d5fe055f27583b1d2
8,382
def nonseq(): """ Return non sequence """ return 1
7c8f4a616a6761153226d961be02f6cf5b0cc54a
8,383
import io def load_image(path, color_space = None, target_size = None): """Loads an image as an numpy array Arguments: path: Path to image file target_size: Either, None (default to original size) or tuple of ints '(image height, image width)' """ img = io.imread(path)...
882210dff5dfa46596562483966b4a72c37aa7a8
8,384
def kubernetes_node_label_to_dict(node_label): """Load Kubernetes node label to Python dict.""" if node_label: label_name, value = node_label.split("=") return {label_name: value} return {}
c856d4e6d1f2169f7028ce842edc881cbca4e783
8,385
def get_category_user_problem(cat_name, username): """ 获取直接在指定目录下的用户AC的题目、尚未AC的题目和尚未做过的题目的情况 :param cat_name: :param username: :return: """ cat = __Category.objects.filter(name=cat_name).first() user = __User.objects.filter(username=username).first() if user is None or cat is None: ...
96e78d527f5bd0002345973eb085e04246e936ae
8,386