content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def test_Functor_subtype_register(): """Test registering a Functor subtype for value wrapping.""" test_value = object() with pytest.raises(ValueError): Functor.try_wrap(test_value) class TestFunctor(Functor): @classmethod def wrap(cls, value): if value is test_valu...
d576c03dcef3d13afb2f6038c3e58a619ddba1e7
41,900
import os import csv def import_results(): """ """ msoa_data = [] with open(os.path.join(INPUT_FILES, 'nga_availability.csv'), 'r', encoding='utf8', errors='replace') as system_file: reader = csv.reader(system_file) next(reader) #reader = [next(reader) for x in range(N)] ...
f1c564f115afc41dedd8f932d0291d5501b1667e
41,901
import matplotlib import experimental import experimental import time from pathlib import Path import os import imghdr import logging def main_function( mymodel: str, myinput: str, mypattern: str, mystate: str, myx_voxel_size: float, myy_voxel_size: float, myz_voxel_size: float, mywave...
49df7475a24761d0afed1850fc8facfe7d1ff52b
41,902
from typing import Union def _filter_class_and_zero_scores( scores: np.array, classes: np.array, filter_class: Union[int, None], confidence: float = 0.001, ) -> list: """Create a list of indices representing the filtered elements. :param scores: Numpy array containing scores of all detections....
5ba8c48412de15c820b6e46116f62ccb9e3659e6
41,903
def smart_resize(x, size, interpolation='bilinear'): """Resize images to a target size without aspect ratio distortion. Warning: `tf.keras.preprocessing.image.smart_resize` is not recommended for new code. Prefer `tf.keras.layers.Resizing`, which provides the same functionality as a preprocessing layer and add...
54f5b9c880dc37d84e07154d93c372bc1368b1f7
41,904
import sys def almosteq(a, b, tol=1e-8): """Almost-equality that supports several formats. The tolerance ``tol`` is used for the builtin ``float`` and ``mpmath.mpf``. For ``mpmath.mpf``, we just delegate to ``mpmath.almosteq``, with the given ``tol``. For ``float``, we use the strategy suggested in:...
5e2e0a50c542a29f6c64709a9210de9daa1c5eff
41,905
def layer_integrate(upper_contour, lower_contour, grid_obect, integrand = 'none', interp_method='none'): """!Integrate between two non-trivial surfaces, 'upper_contour' and 'lower_contour'. At the moment this only works if all the inputs are defined at the same grid location. The input array 'integra...
89df2c838efef7b1cb75f189fa44adbc26e5d975
41,906
def login(request, id=None, username=None, password=None, skip_authentication=False): """ Helper function to login a specific user, optionally skipping the authentication. :param HttpRequest request: The request object. :param int id: *Optional*. The user_id to log in. :param str username: *Opt...
1406c6d61a8ed63aa4e6a492019679a990c879de
41,907
def select(element, selector): """Syntactic sugar for element#cssselect that grabs the first match.""" matches = element.cssselect(selector) return matches[0]
a99c684073fe898bc297dd747cff4abf3c0cb524
41,908
def makeCamera(name, scene): """ Retruns a new camera, appropriate for rendering a cube face, linked into `scene`. """ cameraData = bpy.data.cameras.new(name) cameraData.lens_unit = "FOV" cameraData.angle = PI_OVER_2 camera = bpy.data.objects.new(name, cameraData) if BLENDER_LEGACY_V...
a5c0025ba66095a8ed3577206eba51515c22115c
41,909
import re def path_and_line(req): """Return the path and line number of the file from which an InstallRequirement came. """ path, line = (re.match(r'-r (.*) \(line (\d+)\)$', req.comes_from).groups()) return path, int(line)
54faa80fb0630f17fab836906e672886eedf3ad9
41,910
import sys def exception(message=None, module=None, exc_info=None): """Logs an error plus the current or given exc info.""" if exc_info is None: exc_info = sys.exc_info() try: logger = get_application().log except AttributeError: # no application, write the exception to stderr ...
72187c55e891a6f743eebf5e246e68b5ffaf789e
41,911
def taupericenter(t, e, f, n): """Compute the time of pericenter passage. Args: t (float): current time e (float): eccentricity f (float): true anomaly n (float): Keplerian mean motion Returns: float: time of pericenter passage """ E0 = ...
811e35b388c80af1250477621c850c9ac70bf1a5
41,912
import warnings def get_voronoi_neighbors(atoms, cutoff): """ atoms: ase.Atoms object cutoff: limits the neighbor search to |rj-ri| < cutoff, used only for faster search, it should be large enough so that the output doesn't depend on cutoff. returns: a list of VorNei objects ...
e28325a5c91dc951cf5fe1ff3c03158cdf4d9bfc
41,913
import traceback import pprint import sys def load_publications (graph, used, frags, out_buf, known_datasets, known_journals, known_authors, known_topics, full_graph): """ load publications, link to datasets, link to authors, then reshape the metadata as TTL """ seen = set([]) for partition, ...
73f4fd770e7b93d5fdede451541fb28c1a3ec97c
41,914
def autoencoder(x_hat, x, dim_img, dim_z, n_hidden, keep_prob): """Gateway""" # encoding mu, sigma = gaussian_MLP_encoder(x_hat, n_hidden, dim_z, keep_prob) # sampling by re-parameterization technique z = mu + sigma * tf.random_normal(tf.shape(mu), 0, 1, dtype=tf.float32) # decoding y = b...
f38898f308670e00f608be67dfea994c706a7d10
41,915
from typing import OrderedDict import re def leafelement(element, strip_cdata=False, compact=False, remove_blank_text=True): """ This function converts lowest level tree/etree element to dict structure. :param element: etree leaf-level object, :param strip_data: bool, whether to parse CDATA as pure te...
38bba2727c417dacd84c385335f4415cff50a4fb
41,916
def is_in_bbox(x, y, bbox): """ Answers True or Folse if the x, y is inside the BBOX. """ xMin, yMin, xMax, yMax = bbox if xMin <= x <= xMax and yMin <= y <= yMax: return True return False
911089af818c5e15e6ba857b1dd46f0182b1ea31
41,917
def convert_tuple_to_8_int(tuple_date): """ Converts a date tuple (Y,M,D) to 8-digit integer date (e.g. 20161231). """ return int('{0}{1:02}{2:02}'.format(*tuple_date))
8584bb9ade995e95d12c9d09c4a6d52f7df44f5d
41,918
def rule_Owner_default(x, world) : """We assume that the owner of an object is the first object which Has some object which in some chain of containment (containment optional). Returns None if no owner was found.""" poss_owner = world.query_relation(Has(Y, x), var=Y) if poss_owner : return ...
2bd2406679cd997bbc2ce30bd450513de368cc1b
41,919
def gpiod_line_is_requested(line: gpiod_line) -> bool: """ @brief Check if the calling user has ownership of this line. @param line: GPIO line object. @return True if given line was requested, false otherwise. """ return ( line.state == _LINE_REQUESTED_VALUES or line.state == _...
9ee9341e1e6cd193bd53258992f1907ffedb766f
41,920
def coord_lister(geom): """[summary] when given a geometry pandas geoseries, returns an exterior list of coordinates for all of the entries, given should Args: geom ([type]): [description] Returns: [type]: [description] """ coords = list(geom.exterior.coords) return (coords...
b9d28a32241bf8f2b13988ef149eb4cf05ffb315
41,921
def edgeCannotConnectInputAndOutputOfSameNode( inputSocket: Socket, outputSocket: Socket ) -> bool: """Edge is invalid if it connects the same node""" if inputSocket.node == outputSocket.node: printError("Connecting the same node") return False return True
c921b32409d1cec60c37a2be0d2bff9e398eddec
41,922
def bcnn(pretrained=False, **kwargs): """Constructs a BCNN model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = BCNN(**kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['bcnn'])) return model
cdcdc9258b492865d57cf227521e0c63fe9e2527
41,923
def get_dataframe_intersection(df, comparator1, comparator2): """ Return a dataframe with only the columns found in a comparative dataframe. Parameters ---------- comparator1: DataFrame DataFrame to preform comparison on. comparator2: DataFrame DataFrame to compare with. Re...
0180783601bc1be93b3a74cd5604c5f1cd1bc67b
41,924
import re def get_sanitized_endpoint(url): """ Sanitize an endpoint, as removing unneeded parameters """ # sanitize esri sanitized_url = url.rstrip() esri_string = '/rest/services' if esri_string in url: match = re.search(esri_string, sanitized_url) sanitized_url = url[0:(m...
3936efe81970ffb6b54ee308870e70a20c7a4c6c
41,925
def get_request_raw_header(request, name) : """ Return raw header value of request by header name """ name = name.lower() for header in request.raw_headers : if header[0].decode("utf-8").lower() == name: return header[1].decode("utf-8") return ""
37abaac86ae770354bacd6a96326d8b43f54999a
41,926
import os def readTimeStamp(fname,path): """reads an insight tstmp file and returns an array of the times at which photos were taken at relative to the begining of aquasition""" fname = os.path.join(os.path.abspath(path),fname) num_lines = sum(1 for line in open(fname)) f = open(fname) ...
b1145882bedf011eed599f2e873635df86c9145a
41,927
def sequence_loss(logits, targets, weights, average_across_timesteps=True, average_across_batch=True, softmax_loss_function=None, name=None): """Weighted cross-entropy loss for a sequence of logits, batch-collapsed. Args: logits: List of 2D Tensors of shape [batch_size x num...
5191deb86377125b67e5742f507b516ff52f9866
41,928
def scale_values_based_on_eich_peak(lead_list, gamma=0.5): """ scale values on the Y-axis :param lead_list: list of the value :param gamma: scaling factor :return: rescaled list """ new_lead_list = [] for xy_pair in lead_list: new_y_value = xy_pair[1] * gamma ...
34d2c79f07c23e4fe23ab0eee8642ce17e03dbb7
41,929
def signup(): """ Sign up as a friend, enter card info, etc. """ return jsonify(ok=True)
9164b983bc7a490bed415e2b16b0da7f5f24d442
41,930
def _must_find(cls, name): """Raises a NotFoundError if the given object doesn't exist in the datbase. Otherwise returns the object This is useful for most of the *_delete functions. Arguments: cls - the class of the object to query. name - the name of the object in question. Must be cal...
4552b52211ac2a23c10a44bf012ca37ef992545b
41,931
def import_class(class_path): """Imports a class using a type string. :param class_path: Type string of the class. :type class_path: str :rtype: type """ components = class_path.split('.') mod = __import__(components[0]) for comp in components[1:]: mod = getattr(mod, comp) ...
bcfeed25c2b5f6672df63e63a031cfa580c0e275
41,932
def Base_select(self, param): """ - name: select 1st select: id: element1 by_index: 1 - name: select by value select: id: element1 by_value: value1 - name: select by visible text select: id: element1 by_text: "text 1" """ elem = s...
4940c25abac8cb1682c2796a5725cd11cf5c5318
41,933
from typing import Sequence def peg_time_interval( twt_vol: xr.DataArray, depth_surf: xr.DataArray, twt_surf: xr.DataArray, mapping_dims: Sequence[str] = ("xline", "iline"), ) -> xr.Dataset: """Shifts twt_vol to create such that the depth conversion of `depth_surf` with `twt_vol` matches `twt_...
ce696048bae93011a44f52170ed0f270e4a8dbf2
41,934
def plotSeqAndFeatures(seq, X, createFiltAx=False, padBothSides=False, capYLim=1000): """plots the time series above the associated feature matrix""" plt.figure(figsize=(10, 8)) if createFiltAx: nRows = 4 nCols = 7 axSeq = plt.subplot2grid((nRows,nCols), (0,0), colspan=(nCols-1)) axSim = plt.subplot2grid((nR...
7c555191292945a5b59b77b644cfa5e2400be609
41,935
import subprocess def getYARNApplicationID(app_name): """Returns the YARN application ID.""" state = 'RUNNING,ACCEPTED,FINISHED,KILLED,FAILED' out = subprocess.check_output(["yarn","application","-list", "-appStates",state], stderr=subprocess.DEVNULL, universal_newlines=True) lines = [x for x in out.split("\n")] ...
f7b6f5a77c0e0fe6ed602455609fa1475108eeac
41,936
def reconstruction(capsule_mask, num_atoms, capsule_embedding, layer_sizes, num_pixels, reuse, image, balance_factor): """Adds the reconstruction loss and calculates the reconstructed image. Given the last capsule output layer as input of shape [batch, 10, num_atoms] add 3 fully connected laye...
4ef2239adf1155177ef6bde5d85271d842b1b159
41,937
import requests from bs4 import BeautifulSoup def fetch_events_ppe(base_url='https://ppe.sas.upenn.edu/events'): """ Fetch events from Philosophy Politics & Economics (PPE) """ events = [] html_page = requests.get(urljoin(base_url, '/events')) page_soup = BeautifulSoup(html_page.content, 'html...
69eac4ce6dc50d6fefbaaa69811bddea3405c1be
41,938
def convert_to_unicode(text): """ Converts `text` to Unicode (if it's not already), assuming utf-8 input. Args: text (str|bytes): Text to be converted to unicode. Returns: str: converted text. """ if isinstance(text, str): return text elif isinstance(text, bytes): ...
ea74f2738a23ddad3e429e60679d6fef98860590
41,939
def create_system_id(os_string, architecture): """ Create a system-ID by joining the OS-String and the architecture with a hyphen. Args: os_string (str): The Operating system string. architecture (str): The Architecture string. Returns: The System-ID str...
7ae682e2d57784ca771c1e50b7e980b56f631947
41,940
from typing import Counter def get_pairs(astring): """Takes a string and returns all pairs found in the string""" adict = Counter() for i in range(len(astring) - 1): pair = str(astring[i] + astring[i + 1]) adict[pair] += 1 return adict
599564b5ec2b253daeb94d832ee001e4867bb72a
41,941
def circular_array_rotation(a, k, queries): """Hackerrank Problem: https://www.hackerrank.com/challenges/circular-array-rotation/problem John Watson knows of an operation called a right circular rotation on an array of integers. One rotation operation moves the last array element to the first position and ...
940e193fec0ad1f78c499ee8604e418dd0261109
41,942
def get_roomUsageSchedule(buildingType, roomType, input_calendar={}): """ 時刻別のスケジュールを読み込む関数(空調、その他) """ if RoomUsageSchedule[buildingType][roomType]["空調運転パターン"] == None: # 非空調であれば roomScheduleRoom = np.zeros((365,24)) roomScheduleLight = np.zeros((365,24)) roomSchedulePerson =...
0e60732cc95409a4fb06297403e2cfde93f6906f
41,943
import pathlib import os def create(path: pathlib.Path, key_size: int = DEFAULT_MASTER_KEY_SIZE) -> bytes: """Create a random key with the lenght key_size, and store it in path Args: path (pathlib.Path): Path to store the key in key_size (int, optional): The size of the key to create in bytes...
30d4333d50e4a6a947c62dd87cc91acbcc61df24
41,944
def sim_multi_suj_ephy(modality="meeg", n_subjects=10, **kwargs): """Simulate electrophysiological data of multiple subjects. This function basically use :func:`sim_single_suj_ephy` under the hood to generate the data of multiple subjects. Parameters ---------- n_subjects : int | 10 Nu...
c6824ecc7cd3fc81c536457abf4d3bad5f0eaf2a
41,945
def get_all_completed_exp_ids(user_id): """Returns a list with the ids of all the explorations completed by the user. Args: user_id: str. The id of the user. Returns: list(str). A list of the ids of the explorations completed by the learner. """ completed_activities...
48c02300cc905f613ce09844ca299fef27ad86d0
41,946
def problem015(): """ Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. How many such routes are there through a 20×20 grid? p_015.gif This is a classic combinatorics problem. To...
60a6531653deab46d3a968d3dd354cdd585def50
41,947
import math def _get_v(b1_height: FloatType, b1_width: FloatType, b2_height: FloatType, b2_width: FloatType) -> tf.Tensor: """Get the consistency measurement of aspect ratio for ciou.""" @tf.custom_gradient def _get_grad_v(height, width): """backpropogate gradient.""" arctan = tf.atan(tf.mat...
4b0d60d3a5fc6d133aa7f59fb79a0121146d5ce3
41,948
def on(page, visit_page=False, url_params={}): """ Creates PageObject with current instance of the selenium_browser. Args: page (PageObject): PageObject class name. visit_page (boolean): Navigate to page. url_params (dictionary): url parameter object. Returns: ...
70510ea6b0cd5992beb0d38c1534e8fd3e11a836
41,949
import os import sys import shutil def create_home_dir(): """ Creates the w3af home directory, on linux: /home/user/.w3af/ :return: True if success. """ # Create .w3af inside home directory home_path = get_home_dir() if not os.path.exists(home_path): try: os.makedirs(ho...
ece3392599a611f5249597918b9f4250533c20ad
41,950
def bold(s): """Returns the string bold. Source: http://stackoverflow.com/a/16264094/2570866 :param s: :type s: str :return: :rtype: str """ return r'\textbf{' + s + '}'
b457fe063ef5554ee53df0a79894b3b6f43bccf4
41,951
def plot_lines(lines, color='#269df2', fig_size=(5,5), title=None): """plots lines in complelx plane.""" lines = np.array(lines) tuple_lines = cmplx_lines_to_tuples(lines) fig, ax = plt.subplots() fig.set_size_inches(fig_size) for line in tuple_lines: x, y = zip(*line) ax.plot...
6cb64a86221510e941dd43c0bd29676ce0961e0a
41,952
import typing def decode(obj: typing.Any) -> typing.Any: """Decodes previously encoded information. """ if isinstance(obj, PRIMITIVES): return obj if isinstance(obj, tuple): return tuple(map(decode, obj)) if isinstance(obj, list): return list(map(decode, obj)) i...
bd8607d2c051628b4c10fdf629f23e24cffe41a9
41,953
def face_distance(face_encodings, face_to_compare): """ 计算人脸距离 """ if len(face_encodings) == 0: return np.empty((0)) return np.linalg.norm(face_encodings - face_to_compare, axis=1)
506984373165806da0a5e6cee04c05b128768c81
41,954
from sympy.simplify import powdenest, simplify from re import S def _hyperexpand(ip, z, ops0=[], z0=Dummy('z0'), premult=1, chainmult=1): """ Try to find an expression for the hypergeometric function `ip.ap`, `ip.bq`. The result is expressed in terms of a dummy variable z0. Then it is multiplied ...
47cbd4fa20bf5e54779f6fd476b556557469f6a3
41,955
def tri_less_eq(v1, v2): """Returns True if the tristate v1 is less than or equal to the tristate v2, where "n", "m" and "y" are ordered from lowest to highest.""" return TRI_TO_INT[v1] <= TRI_TO_INT[v2]
2e3a5473b2cbb16ea662454c1db26eca171a2b45
41,956
import base64 def decode_base64_urlsafe(text): """Reverse operation of :func:`encode_base64_urlsafe`. **中文文档** 将base64字符串解码为原字符串。 """ return base64.urlsafe_b64decode(text.encode("utf-8")).decode("utf-8")
c90ebb246587a61885ac15e37a071721d87c036b
41,957
def init_figure(height=800): """Initialize a 3D figure.""" fig = go.Figure() fig.update_layout( height=height, scene_camera=dict( eye=dict(x=0., y=-.1, z=-2), up=dict(x=0, y=-1., z=0)), scene=dict( xaxis=dict(showbackground=False), yaxis=dict(showb...
da8ca9f02f66e10f1eba85e56089c88a53c81d09
41,958
import warnings def compute_indices(wires, n_block_wires): """Generate a list containing the wires for each block. Args: wires (Iterable): wires that the template acts on n_block_wires (int): number of wires per block Returns: layers (array): array of wire labels for each block ...
dbbc532ad01f365b9dd1139bd6cfe7b410c4ae80
41,959
def drop_distant(xy, r=6.0): """ Drops pedestrians more than r meters away from primary ped """ distance_2 = np.sum(np.square(xy - xy[:, 0:1]), axis=2) mask = np.nanmin(distance_2, axis=0) < r**2 return xy[:, mask], mask
33ef5241fe98a07f521a00e3d2ef8e317dacd292
41,960
from typing import Dict def normalize_score_dict(input_dict: Dict[str, float], exponent=1) -> Dict[str, float]: """Takes a dictionary of scores and applies L1-normalization (dividing each value by the sum). This is the simplest way of turning a collection of scores into a probability distribution. The e...
6a8d65d42d7f356b23a0e814841e8005f7daff30
41,961
def allreduce_ring_single_shard(xs, devices, reduction_fn_string="SUM"): """Compute the reduction of all Tensors and put the result everywhere. Performance-optimized for a ring of devices. Args: xs: a list of n tf.Tensors devices: a list of strings reduction_fn_string: "SUM" or "MAX" Returns: ...
53079ab91c9a8041a1312905573968a2c72ff790
41,962
def calcPrecision(data, modelName): #Update name to sensitivity """Calculates the prediction of the data using a single str or list of strings in the modelName argument. The modelName corresponds to the columns to be analyzed. Sensitivity Formula: True Predictions / All Prediction """ if isi...
428d3a72226c7f675f677f5cb8d245e83c502309
41,963
import tempfile import os def _tempfile_path(*args, **kwargs): """Generate a sure-to-be-free tempfile path. It's hacky but it works. """ fd, tmpfile = tempfile.mkstemp() # close and delete; we only want the path os.close(fd) os.remove(tmpfile) return tmpfile
f1460bafa8aa250202510e1cad4c860a3bbd0889
41,964
import sys import email def submitSolution(email_address, secret, output, partIdx): """Submits a solution to the server. Returns (result, string).""" if output == '': print ('') print ("== Submission failed: Please correct and resubmit.") sys.exit(1) else: output_64_msg = e...
faa31d6cf5933dd6004fe4db0636b97615527519
41,965
def bitwise_not(column): """ Computes bitwise NOT. """ return _with_expr(exprs.BitwiseNot, column)
1c231a7241851d259fe7d8a1d8f1217e65002c79
41,966
def ExecuteDownloadPins(pins, processes): """ 并发processes个线程下载所有pins """ pool = ThreadPool(processes=processes) data = pool.map(DownloadPinImg, pins) pool.close() pool.join() return data
ba8a3e675a70c889ff94207b176007209a953915
41,967
def load_raw_lattice(raw_lattice_path="/data/rawdata/sighan/lattice/", path_head="."): """ for flat dont care about para: 'path_head', only use for debugging """ train_source_path = path_head + raw_lattice_path + "train.src" train_target_path = path_head + raw_lattice_path + "train.tgt" vali...
10f3abecc27b8c83f13a49257efc5fdfaee0c687
41,968
def quaternion_ffn(x, dim, name='', activation=None, reuse=None): """ Implements quaternion feed-forward layer x is [bsz x features] tensor """ input_dim = x.get_shape().as_list()[1] // 4 with tf.compat.v1.variable_scope('Q{}'.format(name), reuse=reuse) as scope: kernel = glorot([input_dim, dim], na...
9c0b438dca8452237a0ef638b60bb1b71e379c72
41,969
def mfacebookToBasic(url): """Reformat a url to load mbasic facebook instead of regular facebook, return the same string if the url don't contains facebook""" if "m.facebook.com" in url: return url.replace("m.facebook.com", "mbasic.facebook.com") elif "www.facebook.com" in url: return u...
26b55c23048bd8febe6ef93f15b0c4bbfd434e36
41,970
import os import json import asyncio async def process_websites_to_fetch(request): """ This function processes the POST request and create an asyncio task calling the Driver()'s produce_metrics_for_websites method passing the provided list. :param request: :return: JSON """ try: d...
cc04cfb4308a2bad7ec01f77622a56b03582e555
41,971
import os def kernel_status(): """ :return: {'running': {'kernel-X.Y.Z'}, 'required': <'kernel-A.B.C' or None>} """ running_kernel = "kernel-%s" % AgentShell.try_run(["uname", "-r"]).strip() available_kernels = [ k for k in AgentShell.try_run(["rpm", "-q", "kernel"]).split("\n") if k ...
c766a57e26a9ccade0b9fc77b173d549412f0b8f
41,972
def prepareDataForClassification(dataset, start_test): """ generates categorical output column, attach to dataframe label the categories and split into train and test """ features = dataset.columns[0:-1] X = dataset[features] y = dataset.UpDown X_train = X[X.index < start_test] y_t...
88b42a8145b1f8da469337a8af214cc57c24848e
41,973
def get_new_skill_id(): """Returns a new skill id. Returns: str. A new skill id. """ return skill_models.SkillModel.get_new_id('')
8d1a61be90f47cc3dd6b0113e89026a2b1e66cdc
41,974
def generate_url_to_event_index(website_url): """Given URL to workshop's website, generate a URL to its raw `index.html` file in GitHub repository.""" template = ('https://raw.githubusercontent.com/{name}/{repo}' '/gh-pages/index.html') for regex in [Event.WEBSITE_REGEX, Event.REPO_REGE...
e8eb0974a870f2e8f65d7844d680813753e846e3
41,975
def tokenize(chars: str) -> ListType[str]: """Returns the program as a list of tokens (including parenthesis).""" return chars.replace("(", " ( ").replace(")", " ) ").split()
6d3a4e307b0e6215ac74116c9c10817e66509b98
41,976
def _make_coords(src_data_array, dst_affine, dst_width, dst_height): """Generate the coordinates of the new projected `xarray.DataArray`""" coords = _get_nonspatial_coords(src_data_array) new_coords = _warp_spatial_coords(src_data_array, dst_affine, dst_width, dst_height) new_coords.update(coords) r...
2e97052c67ee52e39024ad4157bf4d0bbb5b1117
41,977
def remove_ambiguous_solutions(fn_in, db_lines, strict=True, verbose=True): """ Removes features with identical solutions. During solving, some tags may be tightly coupled and solve to the same solution. In these cases, those solutions must be dropped until disambiguating information can be found. ...
59dc2de17c1311b1dc7096661dc6b39d0d8fc373
41,978
def fill_missing_values(df: pd.DataFrame): """Fill missing values with mean Args: df (pd.DataFrame): [Pandas DataFrame] Returns: [pd.DataFrame]: [Returns processed dataframe] """ filled_df = df.fillna(df.mean()) return filled_df
716bdcfa05d9838fa65a683ee072b96478a5f202
41,979
async def infer_env_add(self, engine, env1, env2): """Infer the return type of primitive `env_add`.""" return AbstractScalar({VALUE: ANYTHING, TYPE: xtype.EnvType})
61513621c70d71069a5be43dcb601400d5733db1
41,980
def residuals(fit, obs): """Calculate residuals for fit compared to observed data :fit: list of discrete fit data points :obs: list of observed data points :returns: fit minus observed data points """ return fit-obs
46c5eac3620ab8bce58502822aa7d8824bed0988
41,981
import sys def go_to_frame(vid, frame_pos, video_source, return_frame = False): """Jump to frame poisition in video Parameters ---------- vid : cv2.VideoCapture object Already opened video object. If empty, video from video_source is read. video_source : str path to video fil...
0ac5f727b1e97b63f87ee192c5e675236314fdae
41,982
def expected_traces(P, Γ, Λ, X): """The trace matrix for accumulating eligibility traces. That is, a matrix with the same shape as `X`, but where the i-th row corresponds to the expected value of the eligibility trace in the steady-state given that the current state is `i`. Parameters ---------...
03f26d41ada49712643b3961c5d1df19adf0a069
41,983
def test_nationality(root, printerror=False): """Verifies if there are problems with the nationalities in the Lattes CV parsed in the argument root. Args: root: the Lattes CV that has been parsed with the ElementTree language. flag: if 0, there are languages defined in the Lattes CV....
b1d3b56ecf70e50b4ff485cf644a6c758eb8283a
41,984
def publish_uploaded_video(resp): """Publish a uploaded video. Vid is pointted to the uploaded vidoe. <meta> args: query: - access_token - openid - title - tags - cat - desc ...
be3656861db65b9a046949ac765ea2d7bb8176be
41,985
def _hashable2val(val): """Undo _val2hashable() """ if isinstance(val, ReadOnlyDict): return dict(val) elif isinstance(val, tuple): return list(map(_hashable2val, val)) else: return val
35afe287e80df0871623b106cb4788d4f700afaa
41,986
import re def get_method_url_protocol(text): """Method to extract the Request Method, URL, and Protocol in a string surrounded by quotes""" match = re.search(r"\".+?\"", text) if match: match_string = match.group() # Note: match should now be a combination of the Request Method, URL, and Proto...
2dc2ce2ec8985c19ef01a11c7ada7758bdf8f2d4
41,987
def Make_Full_Trial_Index(Features, Offset: int, Tr_Length: int, Epoch_Len: int): """ Parameters: ----------- Features: list Features: list [Ch]->[Freq]->(Time Samples x Trials) Offset: int How much prior or after onset Tr_Length: int How many samples to use for ...
06c86da34d3eaa2f7df07235422b86d036663422
41,988
def cj_curve_fit(x, y): """ Determines least squares fit of parabolic data. This is a vectorized version of ``sdtoolbox.PostShock.LSQ_CJspeed`` using ``np.linalg.lstsq``. Parameters ---------- x : np.array Independent data points for curve fitting y : np.array Dependent data...
0e6d9a85eddf4d173648ba64a1da18f83db9e930
41,989
import torch def feature2embedding(model, feature, edge_index, edge_attr, args): """ Convert further learned features to node embeddings with pre-trained GCN model. :param model: an instance of GCN model. Remember to load the trained weights. :param feature: further learned features. :param edge_i...
b701c56a6dac1746f2c1d2e2b3ffcba0b29cc0a9
41,990
import logging def do_addexpression(**kwargs): """ Worker to add expression to profile profobj: Profile object expname: list of expression names to add return 0 if sucessful """ profobj = kwargs.get('profobj') expname = kwargs.get('expname') logger = logging.getLogger() existin...
3f0f57eb76a9272c437f48483a4a4071e9a8ba0d
41,991
def read_outputs(): """Reads all outputs and returns them as a list""" out_vals = [] for i in range(len(dfs)): userid_element = driver.find_element_by_xpath(dfs.iloc[i, 2]) out_vals.append(float(userid_element.text.rstrip("%"))) return out_vals
14304c4733c473fab143d680dac51e83b64bb16b
41,992
def _get_current_assets(): """Returns the current set of assets in the request stack. """ return getattr(_request_ctx_stack.top, 'current_assets', None)
1e9ff3e7137273748675be848ad534b6ae5a9b75
41,993
def send_action(action): """Sends `action` while processing func command.""" def decorator(func): @wraps(func) def command_func(*args, **kwargs): bot, update = args bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action) return func(bot, ...
69d31d5747d05012e6aa019f12b2584e18719e3b
41,994
def ipaddr_to_bin(num: str, t: int) -> list: """ Receives an IP address as a character string, converts it to a decimal number received as an argument for each octet, and returns it as a list. """ if num.count(".") != 3: usage("invalid arguments") ctype = "b" if t == 2 else "x" ...
14371538a68211595b3133ebbf7ec522f5ec6a6a
41,995
import copy def make_hash(o): """ Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). In the case where other kinds of objects (like classes) need to be hashed, pass in a collection of objec...
ea9efe7e87c902a8365024749186490c5dc57ae9
41,996
def make_reflection_patches(instr_cfg, tth_eta, ang_pixel_size, omega=None, tth_tol=0.2, eta_tol=1.0, rmat_c=np.eye(3), tvec_c=np.zeros((3, 1)), npdiv=1, quiet=False, compute_areas...
b53d1736802ddbb9322b2d37125aa92761a77267
41,997
from typing import List def list_ids(group_id: str) -> List[str]: """List all person ids in a specified `group_id`. :param group_id: ID of the group to be listed. `group_id` is created in `group.create`. :return: An array of person ids. """ if group_id is None: raise Value...
0ab3d8ad921dc50377d6167dc1165d2a34901d35
41,998
def deEmojify(inputString): """ Drop emojis :param inputString: :return: """ return inputString.encode('ascii', 'ignore').decode('ascii')
f0e2ad0ce597e74a133b37244a6bc047b90b1ecd
41,999