content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def fetch_BLESS(): """ Fetch Baroni and Marco categorization dataset Parameters ------- Returns ------- data : sklearn.datasets.base.Bunch dictionary-like object. Keys of interest: 'X': words 'y': cluster assignment References ---------- Baroni et al. "...
eec5be91c7ae5821264e229f22bf5eebccd7e2a8
81,456
def convolve(X, kernel, mode='same'): """ Parameters ---------- X : (データ数, 高さ, 幅, チャンネル)の4次元配列からなる入力データ Returns ------- col : 2次元配列 """ if X.ndim == 3: H, W, C = X.shape pad, stride = 1, 1 filter_h, filter_w = 3, 3 kernel = kernel.reshape([3, 3]) ...
1aa1858a651b8113c5d08d035772540bd63e7b00
81,457
def sign(x): """ Sign function """ return 1 if x >= 0 else -1
20d85cf36d183c96e75fa3b795bf7f05f558e3b8
81,458
def is_selection_within_a_line(view): """Returns true if the selection is within single line, but not zero-width.""" selection = view.sel() if len(selection) == 0: # Null selection return False # selection_coverage will be the region that covers all selections. selection_coverage = s...
441a964140db24040a3180975f9f7fd29a2299c2
81,459
def savings_flexible_product_position(self, asset: str, **kwargs): """Get Flexible Product Position (USER_DATA) GET /sapi/v1/lending/daily/token/position https://binance-docs.github.io/apidocs/spot/en/#get-flexible-product-position-user_data Args: asset (str) Keyword Args: recvWin...
a47d0032e6da7853960ed4cfa807c5793926e9c5
81,460
def redirecttargetsupported(ui, target): """Determine whether a redirect target entry is supported. ``target`` should come from the capabilities data structure emitted by the server. """ if target.get(b'protocol') not in SUPPORTED_REDIRECT_PROTOCOLS: ui.note( _(b'(remote redirec...
f3ff6c2ff5e1ae373914de9927315b9f96ec6b56
81,461
def reg_update_strlist(*args): """ reg_update_strlist(subkey, add, maxrecs, rem=None, ignorecase=False) Update list of strings associated with given key. @param subkey: key name (C++: const char *) @param add: string to be added to list, can be NULL (C++: const char *) @param maxrecs: lim...
c8d8944315ab0cf43461cefdc1330c223d0dc7be
81,462
def sorted_pearson_corr(data: pd.DataFrame) -> pd.DataFrame: """Calculate correlations between columns and sort them by absolute value. Calculate Pearson correlations between all pairs of distinct columns and sort them in descending order by their absolute value. Columns named 'time' or being constant ...
1d27070cea55a2d2d9ab1224e32cc5fe8af978bb
81,463
def get_publisher(): """get_publisher""" log.info("initializing publisher") pub = None auth_url = "" if FORWARD_ENDPOINT_TYPE == "redis": auth_url = FORWARD_BROKER_URL else: auth_url = FORWARD_BROKER_URL pub = Publisher(name="{}_{}".format(SOURCE, "-redis"), ...
82b65605b4e2830ce81c72a09efa0d0bc23397a9
81,465
def mesh_box(): """Box triangle mesh.""" points = np.array([[0., 0., 0.], [10., 0., 0.], [0., 20., 0.], [10., 20., 0.], [0., 0., 30.], [10., 0., 30.], [0., 20., 30.], [10., 20., 30.]]) cells = np.array([[0, 4, 6], [0, 6, 2], [5, 1, 3], [5, 3, 7], [0, 1, 5], ...
61f8c25abb75013edecafb87f376552e1a36b349
81,466
def create_train_test_data(datasize, host, port, imbalance_multiplier, test_size): """ Args: datasize: number of positively identified items to generate host: the host for the dataset (accidents) port: the port for the host imbalance_multiplier: Multiplier of the non-accident siz...
1ccd112f9f8f02ea84c122d9522d2e5aa4d419c8
81,467
import concurrent def blocking(params=None): """ Mark function for thread execution """ def wrapper(handler): logger.info(f"Wrap block {handler.__name__}") async def caller(*args, **kwargs): wrapped = partial(handler, *args, **kwargs) logger.info('Executing tas...
55edc16f7cd47954932a9d198addfdee6e4756d3
81,468
def _check_est(est): """Check if a given estimator is valid""" # Check estimator exist and return the correct function estimators = { 'cov': np.cov, 'scm': _scm, 'lwf': _lwf, 'oas': _oas, 'mcd': _mcd, 'sch': _sch, 'corr': np.corrcoef } if cal...
cc6f9a28808822d75164d21ca1b93d9f3b84733d
81,469
def NumProperties(): """(read-only) Number of Properties this Circuit Element.""" return lib.CktElement_Get_NumProperties()
f8260794b6a0bceec630429aa54c78ccfd67d02d
81,471
def unflatten_dataframe( data: np.ndarray, columns=None, index=None, num_rows=None, num_cols=None, index_name=None, columns_name=None, ) -> pd.DataFrame: """ Reverse a flatten_dataframe operation to reconstruct the original unflattened dataframe Args: data (np.ndarray): ...
dfa6f07ce2e15504b23882f44078ce6ee4082174
81,472
def subscribe_to_basket_action(newsletter): """Subscribe to Basket action.""" def subscribe_to_basket(modeladmin, request, queryset): """Subscribe to Basket or update details of already subscribed.""" ts = [(mozillians.users.tasks.update_basket_task .subtask(args=[userprofile.id,...
dabad4ae6068e27c9ab5ed0d2f2b7a2e79d7ec4f
81,473
def dict_hangman(num_of_tries): """ The function return the "photo" of the hangman. :param num_of_tries: the user's number of guessing :type num_of_tries: int :return: the photo of the hangman :rtype: string """ HANGMAN_PHOTHOS = { '1': """ x-------x""", '2': """ x-------x | | | | |""", '3': """ ...
3864d3072fa0fe9fea6c7e02733e466669335c80
81,474
import scipy def tocoo(X): """ Convert an array to a sparse COO array. If the input is already an `sparse.COO` object, this returns the object directly; otherwise it is converted. """ if isinstance(X, sp.COO): return X elif isinstance(X, sp.DOK): return sp.COO(X) elif scip...
4c3b0eb42ee094b3304bae4c0a33684b767ddcf2
81,476
from typing import OrderedDict from typing import Dict import torch def get_sample_scheme(n_agents, obs_spaces, act_spaces): """ get sample batch and buffer specifications specify how to encode experience in SampleBatch/EpisodeBatch use hierarchical keys: obs/agent_idx/obs_sub_fields """ ...
008ef294fdae1e3426dd027402e49f914fd6a755
81,477
def read_words(path): """ From a TIMIT file, reads the word info Parameters ---------- path : str path to file Returns ------- list of dicts each dict has spelling, begin, end """ output = [] sr = 16000 prev = None with open(path, 'r') as fi...
e3ad680e179ff07615d88503c614ee1a706d3bf5
81,478
def build_void(lines, start, end): """ Builds a void from the given parameters. Parameters ---------- lines : `list` of `str` The lines of the section. start : `int` The starting index of the void. end : `int` The void's last line's index +1. Returns -------...
25cad6592033f34a67a65be9d1c1b1c507d33ddd
81,480
from typing import Optional async def list_cameras(options: Optional[str] = ""): """ Returns the list of cameras managed by the processor. """ return { "cameras": get_cameras(options) }
85c57cc9bdb25abdb392ee29cda69ca06f5ad599
81,481
import json def loadDataset(): """ Loading and Spliting Dataset """ train, test, val = [], [], [] print("==> Loading Training Set") with open("./data/Batch_1_train_filter.json") as json_file: train = json.load(json_file) #train = pd.DataFrame(train_file) ...
1dd7602da719d2917202c312a3c0fef9fda36c64
81,482
def check_seq_len(tokens, mask): """ Warn user and shorten sequence if the tokens are too long, otherwise return original Args: tokens (List[List[str]]): List of token sequences mask (List[List[int]]): List of mask sequences Returns: tokens (List[List[str]]): List of token sequence...
a17125b6752d17be2a0f8079154d29d141a57b2a
81,483
def efficientnet_b2(pretrained=False, **kwargs): """ EfficientNet-B2 """ model = _gen_efficientnet(channel_multiplier=1.1, depth_multiplier=1.2, **kwargs) if pretrained: model.load_state_dict(load_state_dict_from_url(model_urls['efficientnet_b2'])) return model
2eb2073a46cb591048c4724faafd8431585b4dbf
81,484
def plot_ccfrv_servalrvc(data, shiftserval=True, title='', stats=['std', 'wstd'], **kwargs): """ stats : {'std', None} Show std of the parameter """ # Plot style if kwargs is None: kwargs = dict() kwargs['linestyle'] = kwargs.get('linestyle', 'None') kwargs['marker'] = kwarg...
000effbcc5311b44ed28ddaf4892403cd8468e70
81,485
import numpy as np def random_complex_matrix(matrix_size): """ Generate a random, square, complex matrix of size `matrix_size`. """ return (np.random.rand(matrix_size, matrix_size) + 1j * np.random.rand(matrix_size, matrix_size))
4f8f486ebe53b87115631783696715dff6fae92d
81,486
def service_operations_by_systemctl(dut, service, operation, skip_error_check=False): """ Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com) Function to do the service operations using systemctl :param dut: :param service: :param operation: :return: """ command = "systemctl...
e136a764024614843b43c01132e51263fcb611bd
81,487
def split_warnings_errors(output: str): """ Function which splits the given string into warning messages and error using W or E in the beginning of string For error messages that do not start with E , they will be returned as other. The output of a certain pack can both include: ...
aaf0ea05f5d32247f210ae1696ea58824629d075
81,488
def get_hourly_data_dict(csv_path): """ Generate a Pandas DataFrame containing hourly count data. Parameters ---------- csv_path: str Location of CSV containing hourly count data from NeuroPace. Returns ------- df_hour: pandas.DataFrame """ df_hour = pd.rea...
7b52c266807aed8d71b001d5117a35cff3a8b6b5
81,491
def bcut_from_rel(bvals, relbthresh=0.04): """ Given a sequence of b values and a relative b threshhold between "undiffusion weighted" and "diffusion weighted", return the absolute b corresponding to the threshhold. """ minb = np.min(bvals) maxb = np.max(bvals) return minb + relbthresh *...
6b8a85c0772d436bf33150af5a2c5146d9fbc5e7
81,493
def reverse_complement(x): """Return reverse complement.""" a = str() for i in x: a = base_complement(i)+a return a
5b66194e690d765bd50928ddc20fd13ccce340d2
81,494
def random_color() -> str: # type: () -> str """ Generates a random color in the form of string of RGB hex values. For example; `#ffffff`, `#123456`, `#a42c30`, etc. Returns: A random color in the form of string of RGB hex values. """ r = hex(np.random.randint(0, 256))[2:] g = hex(...
c55075c8fc28ee981a9af1f70d34413b0b970fff
81,495
def createCalibrationArrays(board, combinedCorners): """ Creates arrays from the chessboard and detected corners for solving camera properties. Args: board: 2D Chessboard Coordinate Array combinedCorners: Array of arrays of coordinates of detected chessboard corners Returns: im...
65c4993ac8de41d7b5144bfe19651b4af4b16f9f
81,497
def var_label(var, precision=3): """Return label of variable node.""" if var.name is not None: return var.name elif isinstance(var, gof.Constant): h = np.asarray(var.data) is_const = False if h.ndim == 0: is_const = True h = np.array([h]) dstr ...
1dd17043e7c931489347645e1cd994f3c8fe461c
81,498
import numpy def subtract_3_rasters( raster_path_a, raster_path_b, raster_path_c, target_path): """Calculate target = a-b-c and ignore nodata.""" a_nodata = pygeoprocessing.get_raster_info(raster_path_a)['nodata'][0] b_nodata = pygeoprocessing.get_raster_info(raster_path_b)['nodata'][0] c_noda...
ec1e03181cff2e3c37595a7246374f204c3a73f1
81,499
from xmodule.modulestore.django import modulestore def serialize_course(course_id): """ Serializes a course into py2neo Nodes and Relationships Args: course_id: CourseKey of the course we want to serialize Returns: nodes: a list of py2neo Node objects relationships: a list of ...
e034d188de47d35c2b70e15d3d7a33eee346210b
81,500
from typing import Type import json def json_load(cls: Type[C], fp) -> C: """Deserialize an instance of type 'cls' from JSON read from a read()- supporting object. This supports classes that use PEP-526 type annotations, and is meant to work especially well with classes that use [`@dataclass`], such ...
bd1c13eb624b092283c8d6186351eecf9ed3d2c4
81,501
def get_sensors_model_detail(sim, sensor_names: list) -> (np.array, np.array, np.array): """ Get the sensor ID, sensor ADR and sensor DIM of a list of sensor names as string Args: sim (MjSim): mujoco py simulation sensor_names (list): list with sensor names as strings, e.g. ['force_sensor',...
8b15d43e66016d2c6d393b7495a696ceb4c3765e
81,502
def pdf_with_params(rt, params): """Helper function that calls full_pdf and gets the parameters from the dict params. """ v = params['v'] V = params['sv'] z = params['z'] Z = params['sz'] t = params['t'] T = params['st'] a = params['a'] return hddm.wfpt.full_pdf(rt, v=v, V=V...
7b30efd46496616dba7700b55da82b1a022e7bc3
81,503
def neighbors_graph(ingraph, source, beamwidth=4, maxnodes=10, max_iter=100, tol=1e-4): """ Neighbors of source node in ingraph """ assert ingraph.is_directed(), "not implemented for undirected graphs" centrality = nx.eigenvector_centrality_numpy(ingraph, ...
424359092b13ae00e50d8c6768c14987f2065e89
81,504
def find_time_travelers(data_dir): """ Some edges cite forwards in time... """ case_metadata = pd.read_csv(data_dir + 'raw/case_metadata_master_r.csv', index_col='id') edgelist = pd.read_csv(data_dir + 'raw/edgelist_master_r.csv') # some edges travel forwards in...
d870c09c749ca1e57e771855bceb66581249ac50
81,505
import numpy def log_fbank(signal,samplerate=16000,win_length=0.025,win_step=0.01,filters_num=26,NFFT=512,low_freq=0,high_freq=None,pre_emphasis_coeff=0.97): """Calculate log of features. """ feat,energy=fbank(signal,samplerate,win_length,win_step,filters_num,NFFT,low_freq,high_freq,pre_emphasis_coeff) ...
d7f246e1efd83f26018dd3dbe5b72f17e215d032
81,506
from datetime import datetime def readall_msgs(boxid): """ Mark all messages in a box as read """ now = datetime.datetime.utcnow() q = Message.update(read=now).where(Message.read.is_null()).where(Message.receivedby == current_user.uid) q.where(Message.mtype == boxid).execute() socketio.emit('notif...
5fdc854b128e5163bc7ba82f33c7c6fce328a217
81,507
def negotiation_failed(err=None): """ Construct a template for SSH connection """ tpl = { 'ssh-event': 'negotiation-failed' } if err is not None: tpl['error'] = err return tpl
9f0b608ee0e062ce932ea0f2a22aab7cdc7156f8
81,509
import numpy as np from scipy.stats import rankdata def MI_basic(x, y, h_method = 'sturge', ranking = True): """This function calculates the mutual information between the time series x(t) and its delayed version x(t+tau) using equi-spaced partitions. The size of the partition is based on the desired bin siz...
44a160071b2c905ddb92215eb92044b1f63b0db7
81,510
def csv_add_gmt8(file_src,col_name,file_dest): """ add GMT8 time to CSV by re-format one column """ df = pd.read_csv(file_src) df[col_name + "GMT8"] = df[col_name].apply(date_to_gmt8) df_save=df.drop(['Unnamed: 0'], axis=1) df_save.to_csv(file_dest) return df_save
13abf6f305e85fa68c4fafbb585995f4ef216b99
81,511
async def list_by_server(hub, ctx, server_name, resource_group, **kwargs): """ .. versionadded:: 2.0.0 Gets a list of virtual network rules in a server. :param server_name: The name of the server. :param resource_group: The name of the resource group. The name is case insensitive. CLI Exampl...
53998fc4f1d48e159b90a575929d81da3263717c
81,512
def test_conf(request): """Fixture function for command-line option.""" return request.config.getoption('test_conf')
55eb956e75c3716a240987b69070be963d3bad21
81,513
def _get_type_and_value(entry): """Parse dmidecode entry and return key/value pair""" r = {} for l in entry.split('\n'): s = l.split(':') if len(s) != 2: continue r[s[0].strip()] = s[1].strip() return r
e6dd2068f10085c2dac233f1f71512e5874c5adc
81,514
def delete_personal_message(request, pk=None): """ Create a view that allows user to delete a personal message to him / her """ user = User.objects.get(email=request.user.email) contactuserposts = ContactUser.objects.all() contactuserpost = get_object_or_404(ContactUser, pk=pk) if request.me...
2fc933a189b244c6e25a33fb22dc2d0e9ee7fd63
81,515
import torch def qeuler(q, order, epsilon=0): """ Convert quaternion(s) q to Euler angles. Expects a tensor of shape (*, 4), where * denotes any number of dimensions. Returns a tensor of shape (*, 3). """ assert q.shape[-1] == 4 original_shape = list(q.shape) original_shape[-1] = 3 ...
1926af959690b397dcfe2b712e3ff04b19285eed
81,516
def action_greedy(state, actions_ctrl, height, width): """ when training, enemy is greedy policy """ state_copy = state.copy() board_width = state_copy['board_width'] board_height = state_copy['board_height'] beans_positions = state_copy[1] snakes_positions = {key: state_copy[key] for ke...
0e0de7abd7ea31f1d19fec68534b8999fde8843e
81,517
def tanh(z): """ An AlComplex compatible hyperbolic tangent function. Parameters ---------- z : Python numeric type or AlComplex Returns ------- AlComplex """ return AlComplex.from_python_complex(cm.tanh(z.to_python_complex()))
09e25f2fd4ecd4a9a7940b787624d1855d7165fc
81,519
import numpy import random def randomPairs(n_records: int, sample_size: int) -> IndicesIterator: """ Return random combinations of indices for a square matrix of size n records. For a discussion of how this works see http://stackoverflow.com/a/14839010/98080 """ n: int = n_records * (n_record...
40d5ae4eb117944971b2d0efe4ccbf7603f04dae
81,521
from google.cloud import kms def create_key_version(project_id, location_id, key_ring_id, key_id): """ Creates a new version of the given key. Args: project_id (string): Google Cloud project ID (e.g. 'my-project'). location_id (string): Cloud KMS location (e.g. 'us-east1'). key_ri...
d70306e786dfffad5c9f6e8da288488f7166ff1a
81,522
def parse_instance_envs(env_raws, instances): """ Replaces the values in the environment variables for values that exist in this infrastructure Supported: - role.PUBLIC_IP -> adds the public ip - role.PRIVATE_IP -> adds the first private ip retrieved by facts - r...
b2677af3641e2e4a0cef1d15c977afc230e61cfc
81,523
def GetAllData(fe_fd, csv_file, agg_num, hop): """ Input: Features folder(String), CSV file(String), agg_num(Integer), hop(Integer). Output: Loaded features(Numpy Array) and labels(Numpy Array). Loads all the features saved as pickle files. """ # read csv with open( csv_file, 'rb') as f: ...
da3f8b29b7e1216b46b290baabda3cfd23caab17
81,524
def ready() -> bool: """Checks if the storage system is ready. Returns ------- bool Whether or not the configured storage system is ready. """ return storage_ready()
a9c509d38f62727f2d43ffa71ad6f2dcb6ab5d40
81,525
import torch from operator import xor from operator import and_ from operator import not_ def sha256(message): """ h0 = expand_constant(num_to_32_bits(h0n)) h1 = expand_constant(num_to_32_bits(h1n)) h2 = expand_constant(num_to_32_bits(h2n)) h3 = expand_constant(num_to_32_bits(h3n)) h4 = expand...
09615149938f2922d463606af94edbf01c0e1430
81,526
def check_if_two_hsps_overlap(hsp_obj1, hsp_obj2): """Takes two HSP objects and returns True if their ranges overlap, and False if not. """ x = hsp_obj1.hit_range y = hsp_obj2.hit_range overlap = check_if_two_hsp_ranges_overlap([x, y]) return overlap
9f031a0e889c03c7662006cbeba23c4f17ab5304
81,527
import torch def make_identity(shape: torch.Size) -> torch.Tensor: """ :param shape: shape of the desired matrix :return: matrix which is zeroes everywhere and ones on diagonal """ result = torch.zeros(shape) for i in range(np.minimum(shape[0], shape[1])): result[i, i] = 1.0 ret...
a7339c9d20152e4fdfddce209716caeaf7704247
81,529
from sklearn.metrics import mutual_info_score def mi(x, y): """ Mutual Information (MI) between two images. """ return mutual_info_score(x.ravel(), y.ravel())
c31b45f60160d505f7a96d69a013c3fd0c5842f4
81,530
def _replace_strings(obj, old, new, inplace=False): """ Recursively replaces all strings in the given object. This function is specifically meant to help with saving and loading of config dictionaries and should not be considered a general tool. """ if not inplace: obj = obj.copy() ...
3f7661a53ab8cbb836eee68b1bb3d1df9e73c4a5
81,531
def symmetrize(input_df, source_col_name, dest_col_name, value_col_name=None, multi=False, symmetrize=True): """ Take a dataframe of source destination pairs along with associated values stored in a single GPU or distributed create a COO set of source destination pairs along with values w...
b8082a6b5e43d2da36112f92ae85cc0dbc693942
81,532
def slavic_findpeaks(data, spacing=1, limit=None): """ Searches for peaks in data History: -nov 2015: Janko Slavic, update -mar 2013: janko.slavic@fs.uni-lj.si Finds peaks in `data` which are of `spacing` width and >=`limit`. :param data: values :param spacing: minimum spacin...
8c3c9569bd69fa7fdbf1b6e125409e82d9fca510
81,533
def hello_world() -> str: """ Say something! """ return "Hello World!"
22deba02b863355d150653caf744a65950a2fec5
81,534
def test_control_flow_ref(): """ Feature: Control flow graph sinking scenarios. Description: If the return value of subgraph is Ref, should run graph mode with kernelbykernel. Expectation: No exception. """ class IFFuncNet(nn.Cell): def __init__(self): super().__init__() ...
c9fac191db1276ce8d86816a2a56b24478403873
81,535
import math def wshorten(text, width=80, placeholder='…', pos='right'): """Shorten the text to fit in the given width even if not all characters\ occupy only one column in a terminal. :param str text: the text :param int width: the width :param str placeholder: the placeholder :param str pos:...
962777e1b2b2e3393b334d0a2a2ab18c48732ddc
81,536
def authenticated_user_required(f): """ Декоратор проверки того, что к обращение к требуемому ресурсу системы производится аутентифицированным пользователем """ def action(request, *args, **kwargs): user = request.user if not user or not user.is_authenticated(): if reque...
abf8a85fd94ae75b06b928e6b1707ccdd329a842
81,537
def get_data(count): """ Use this function to generate data, returns a touple containing a list, a dictionary and a nested dictionary. """ l = [] d = {} nd = {} for i in range(count): d[lipsum(1)] = lipsum(10) l.append(lipsum(3)) nd[lipsum(1)] = {i: lipsum...
26104b4416a3161d194515cb3977dff73e1265a6
81,538
def normalise(imgs): """ Normalises the two images by taking their channel means: img = (img-mean)/255 Args: imgs: Returns: """ rgb_max = 255.0 rgb_mean = np.mean(imgs, axis=(0, 2, 3), keepdims=True) imgs = (imgs - rgb_mean) imgs /= rgb_max return imgs
e5f5ce7b81537aedb1d16a29240cceddf65bcf86
81,539
def compute_accuracy(predictions, y): """Computes the accuracy of predictions against the gold labels, y.""" predictions, y = predictions.to('cpu'), y.to('cpu') return np.mean(np.equal(predictions.numpy(), y.numpy()))
270fd5bd97c18b73285701af1c4173ab29c1612a
81,540
def range_geometric_row(number, d, r=1.1): """Returns a list of numbers with a certain relation to each other. The function divides one number into a list of d numbers [n0, n1, ...], such that their sum is number and the relation between the numbers is defined with n1 = n0 / r, n2 = n1 / r, n3 = n2 / r...
92e7f9f1b85011323cf5e90002d8f9151ae17e0e
81,541
def get_decks(df): """Search for the information of all decks inside a dataframe, given the feature 'Cabin' Parameters ---------- df : panda dataframe Returns ------- Original dataframe with a new feature called 'Deck' """ df['Deck'] = df['Cabin'].apply(get_deck) # Mod...
be613c8a6301ce1c81bcaa2147416c01161e1f8d
81,542
def delete(center, keys): """ Delete keys from all workers """ return IOLoop().run_sync(lambda: _delete(center, keys))
51cc3625ea2a0a91cc9fda72cf21e70f66021e59
81,543
import hashlib def getIdHash(id): """ Return md5 prefix based on id value""" m = hashlib.new('md5') m.update(id.encode('utf8')) hexdigest = m.hexdigest() return hexdigest[:5]
a9e8d67fae494cd2eaac41b6258be69ed10b667a
81,544
def compute_mean_std(arrays, axis=0, keepdims=False, dtype=np.float64, ddof=1): """ Computes the total mean and standard deviation of a set of arrays across a given axis or set of axes, using Welford's algorithm. """ kwargs = dict(axis=axis, keepdims=True, dtype=dtype) n = m = s = 0 for data...
55c55c44bfe5c4d3a7c2be1d06b15d32e23f5713
81,545
def page_index(): """the default homepage for Dalton""" return render_template('/dalton/index.html', page='')
121319a74d59e98dbcbdab75e035bdcabde1c608
81,546
import requests def load_url(url, nlp): """ Process url to get content for analysis. [WIP feature (see readme)] """ try: url_request = requests.get( url, headers={"User-agent": f"Espial/v0.1"}, ) except Exception: return False html_doc = Document...
3a621535c58a06f560b4de16f51a58448dfcce9d
81,547
from datetime import datetime def filter_on_times(df, start_time, end_time, reverse=False): """ Filter df keeping rows with index times in [start_time, end_times]. - reverse: reverse the filtering """ dbg.dassert_type_is(df, pd.DataFrame) dbg.dassert_type_is(start_time, datetime.time) dbg...
e72f5b10b772c4c562a8f69822a38b08be28bb46
81,548
def _SubTestsDictEntry(sub_test_paths, has_rows, deprecated): """Recursively gets an entry in a sub-tests dict.""" entry = { 'has_rows': has_rows, 'sub_tests': _SubTestsDict(sub_test_paths, deprecated) } if deprecated: entry['deprecated'] = True return entry
825f37da4ae4a57c485b49b7aa9a3ee15bbaa2b9
81,549
def reverse_and_collapse(in_str: str) -> str: """ Solution: Iterate backwards and copy chars to a new string if they don't equal the last char of that new string. Time: O(n) -> Iterate every char Space: O(n) -> Construct another string with max size = length of input string """ if not in_str: raise ValueError...
4d8c9224420a3bbe73ef6347cccaae0e20441943
81,550
import time def _get_selenium_webelements(parent, kwargs, min_elements, wait): """Get all Selenium elements matching the kwargs. Parameters ---------- parent : browser or element The browser or element. kwargs : dict Keyword arguments. min_elements : int, optional The ...
0a16c6a040d4dbabeabb2cf8c24a8141c2754931
81,551
def exists(_env): """Always activate this tool.""" return True
62ba86e515af9da467e7e3425e692c589b8c7fd8
81,552
def video_call_setup_teardown(log, ad_caller, ad_callee, ad_hangup=None, video_state=VT_STATE_BIDIRECTIONAL, verify_caller_func=None, verify...
f245350e60326bb7b52c921d164a68da5e97c91e
81,553
def AADT_splits(df_spl): """Calculates AADT per vehicle type. Args: df_spl, a pandas dataframe. Returns: df_spl, a pandas dataframe containing new columns: dir_aadt: directional aadt aadt_auto: auto aadt pct_auto, pct_bus, pct_truck : percentage mode splits of auto and bus. """ ...
d5a10dc8cf34093190ca0035b1cf9f256c841d1b
81,554
def split_train_test(ds): """ Given the dataset, split in two datasets: One is the Training set. Other is the Test set. The proportion is 80% to 20% Respectively Dataset -> Dataset, Dataset """ samples_train, samples_test, classes_train, classes_test = train_test_split(ds.data, ds.targ...
62a6f68809383fa65f059fdb951de7f3cde4a46b
81,555
import itertools def _pairwise(iterable): """s -> (s0,s1), (s1,s2), (s2, s3), ...""" a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
326b0cfe3374dcc5093dcb36d0f027921ac418c0
81,556
def normalize(s): """Removes all punctuation, whitespace, and accents. Converts to lowercase.""" return strip_accents(strip_non_alphanumerics(s)).lower()
9b06e754aa4cf459eb35c75daee996d8664150ca
81,557
from typing import List def findalldevs() -> List[str]: """Return a list of capture devices.""" devs = ct.POINTER(_pcap.pcap_if_t)() ebuf = ct.create_string_buffer(_pcap.PCAP_ERRBUF_SIZE) status = _pcap.findalldevs(ct.byref(devs), ebuf) if status: raise OSError(ebuf.value.decode("utf-8", "...
65ed4d1e2dff10d285ceda06453c1d59e1b248b2
81,559
def norm_layer_name(name): """Some heuristics to normalize a layer name from multiple sources. For example, some depictions of VGG-16 use use upper case; others use lower case. Some use hyphens; others use underscores. These heuristics are by no means complete, but they increase the likelihood that...
ec1d387010282178616c2e7a63b765ceea6078bc
81,560
from typing import Tuple def mask_2d_centres_from( shape_native: Tuple[int, int], pixel_scales: Tuple[float, float], centre: (float, float), ) -> (float, float): """ Returns the (y,x) scaled central coordinates of a mask from its shape, pixel-scales and centre. The coordinate system is define...
4d06a452833370be99464ce55a4192484fce828c
81,561
def union(mask_a, mask_b): """ This function ... :param args: :return: """ return mask_a + mask_b
f813cf9eeba22922b4146ac61bbe6a590d16d21f
81,562
def get_compensation(host, token, compensation_pk, method=METHOD['https']): """ GET a serialized Compensation instance compensation_pk (required) Returns a dictionary with keys: 'status': The HTTP response code 'reason': The HTTP response reason 'data': Dictionary represe...
0bcf2286670cdb29f929e3ba4acb24361b42d580
81,563
def square_dist(x, y, dim=1): """ """ return (x-y).pow(2).sum(dim=dim)
f42f1964b7da0ef4cafe5e7db475bf8f429377bc
81,564
import typing import joblib def _run_commands(commands, args): """コマンドの実行。""" results: list[CommandResult] = [] # run formatters (serial) for command in commands: if CONFIG[command] and ALL_COMMANDS[command]["type"] == "formatter": results.append(run_command(command, args)) #...
4cf03b0d12ae9536151c45c10e27a1f02daeb37d
81,566
def convert_list(element_list: list) -> list: """ Convert list of Python AST objects to cboost AST objects """ return [convert(e) for e in element_list]
c7c8571d053ed00f1044ba02c9cb59077a9e3ff7
81,568
import re def doesExecutableWork( exe_args: ExeArgs, check_regex: RunRegex, env_args: EnvArgs = EnvArgs(script="", args=None, do_source=False), ) -> str: """Checks if the given command line works. Tries to run the command with the given arguments (see `runCommand`) and parses the output of th...
fe8e97499228eab3692db3cfae977d1f426628c3
81,569
import fnmatch def get_s3_data_paths(s3, bucket_name, root, file_types=["*.jsonl"]): """ Get all paths to particular file types in a S3 root location s3: S3 boto3 resource bucket_name: The S3 bucket name root: The root folder to look for files in file_types: List of file types to look for, or...
3254565cafafaf8d11a35d8f3ffb44ba9f8c57b6
81,570