content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import re
def getTerms(Document):
""" This returns the stemmed terms after removing the stopwords
in the documents"""
line = Document.lower()
line=re.sub(r'[^a-z0-9 ]',' ',line) #put spaces instead of non-alphanumeric characters characters
line=line.split()
sw = stopwords.words('english')
... | f59c662e13135be171275dd066c6b81ab91c3c68 | 80,748 |
from typing import Optional
from datetime import datetime
import dateutil
def format_infraction_with_duration(
date_to: Optional[str],
date_from: Optional[datetime.datetime] = None,
max_units: int = 2,
absolute: bool = True,
) -> Optional[str]:
"""
Return `date_to` formatted as... | 7390c521ee737fb1f64ef24fdeb207ee34499e12 | 80,749 |
def get_assume_poset(A):
"""
input : A - a list of assumptions
output: R - an ordering relation (non reflexive, not transistively reduced)
"""
n = len(A)
R = np.zeros((n,n),dtype=bool)
for i in range(n):
a = set(A[i])
for j in range(n):
b = set(A[j])
i... | d69aee531d0cd10611b7a14e70e6ae5934c51c23 | 80,751 |
import time
def last_push(f):
"""
Once a push function has been executed, perform an update on the last push time,
last push function, and the local function name for the master user.
"""
@wraps(f)
def set_last_push(self, *args, **kwargs):
def parse_push_args_func_addr(push_args):
... | 20becf04683f527cc49612212de0ab68789e3c0c | 80,752 |
def ProcCSV(lst):
"""
Processes lst for delimiters and sorts them into a multi-dimensional array
"""
OutList = []
MegaList = []
for element in lst:
for item in element.split(",,"):
OutList.append(item.strip("\n"))
for item in OutList:
MegaList.append(item.split(",... | 09a5e5d69dd56ae35b62fb6e32dbef86fa6b1556 | 80,753 |
def getminmax_linear_search(arr):
""" Linear method
Initialize values of min and max as minimum and maximum of the first two elements
respectively. Starting from 3rd, compare each element with max and min, and
change max and min accordingly
"""
if len(arr) == 0:
return None, ... | 6c2f19b7a4d12e45b570b89ea40b28aa9239a8fe | 80,754 |
def get_edge_points(mesh):
""" returns: edge_points (#E x 4) tensor, with four vertex ids per edge
for example: edge_points[edge_id, 0] and edge_points[edge_id, 1] are the two vertices which define edge_id
each adjacent face to edge_id has another vertex, which is edge_points[edge_id, 2] or edge_poi... | b3ce217b61609152d771017ec68ded05d97d4cc5 | 80,755 |
def get_scaled_unsup_weight_max(num_labels, X_train_shape, unsup_weight_max=100.0):
"""Use to calculate the coefficient of ppmiloss"""
return unsup_weight_max * 1.0 * num_labels / X_train_shape | c2f59409464ea9f0a3eab620ecc3749fd69a6fab | 80,757 |
import unittest
def makeTestSuiteV201111():
"""Set up test suite using v201111.
Returns:
TestSuite test suite using v201111.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(CreativeTemplateServiceTestV201111))
return suite | 892f03ed8153f0dba9ef14dcd852cb3e5e963f80 | 80,758 |
def mesh(X, boundary_improvement=False):
"""Mesh
======
Creates a Delaunay triangulation of a 2D point cloud. Useful for visualizations.
Parameters
----------
X : (n,d) numpy array
Numpy array of \\(n\\) points in dimension \\(d\\). If \\(d\\geq 3\\), only
first 2 coordintes... | 9ef851f896e109fb5e3532b838907a9d717e1447 | 80,759 |
import struct
def EncodeAscendBinary(str):
"""
Format: List of type=value pairs sperated by spaces.
Example: 'family=ipv4 action=discard direction=in dst=10.10.255.254/32'
Type:
family ipv4(default) or ipv6
action discard(default) or accept
direction in(default) o... | 78ee7f9f1a8c2cdb664c4a6f21d245361f9a6694 | 80,760 |
import requests
import urllib
def get_wechat_pay_url(order_id, total_fee, product_id,body,spbill_create_ip,redirect_url=conf.task_redirect_url):
"""
返回手机支付链接
"""
nonce_str = random_str() # 拼接出随机的字符串即可,我这里是用 时间+随机数字+5个随机字母
params = {
'appid': conf.appid, # APPID 公众平台
'mch_id': co... | 560ac99b2266667a93c1eee21ce6359be937b7f9 | 80,761 |
def symmetric_part(A):
"""Symmetric part of A"""
A = np.asarray(A)
assert A.shape in ((6,), (9,), (3,3))
if A.shape == (6,):
return A
elif A.shape == (9,):
A = A.reshape((3,3))
symA = .5 * (A + A.T)
return symA[([0,1,2,0,1,0],[0,1,2,1,2,2])] | a4de839e52f2e5609d20d3439c8f0237315f1c3e | 80,762 |
def prepare_filter_query(dates, tags, mode):
"""Query to get filtered tasks data from database."""
if mode == "OR":
return 'SELECT id, name, total_time, description, ' \
'creation_date FROM tasks JOIN activity ' \
'ON activity.task_id=tasks.id JOIN tasks_tags ' \
... | 914daa4440347909d3bcaa61eaf3db12a4033c66 | 80,763 |
def uncompress_gzip(location, target_dir):
"""
Uncompress a gzip compressed file at location in the target_dir.
Return a warnings mapping of path -> warning.
"""
return uncompress(location, target_dir, GzipFileWithTrailing) | d96aa97427932064f88218432c557f1c3bae0c1b | 80,764 |
from typing import List
def generate_state_tomography_experiment(program: Program, qubits: List[int]):
"""Generate a (pyQuil) TomographyExperiment containing the experimental settings required
to characterize a quantum state.
To collect data, try::
from pyquil.operator_estimation import measure_... | ebab1143218b3d476f3d019e78e2bdfee7a82b30 | 80,766 |
def parse_file(bbox_dir, filename):
"""Parse an individual XML file and grab the relevant elements.
Args:
----
bbox_dir: str
filename: str
Output:
------
output_lst: list of lists
"""
tree = ET.parse(bbox_dir + filename)
root = tree.getroot()
output_lst = ... | d3376ddcba8163c2af3ac51761fef681af76563b | 80,767 |
def char_errors(reference, hypothesis, ignore_case=False, remove_space=False):
"""Compute the levenshtein distance between reference sequence and
hypothesis sequence in char-level.
:param reference: The reference sentence.
:type reference: basestring
:param hypothesis: The hypothesis sentence.
:... | f77c00476c4b8eb2ff8a525dd9892303c982e793 | 80,769 |
def PyUnicode_InternFromString(space, s):
"""A combination of PyUnicode_FromString() and
PyUnicode_InternInPlace(), returning either a new unicode string
object that has been interned, or a new ("owned") reference to an
earlier interned string object with the same value.
"""
w_str = space.newtex... | c34400fe3a91e9c723d89ea7e604df414536a461 | 80,771 |
import geopandas as gpd
import shapely
from shapely.geometry import Point
def dataframe2geo(pddf, x_field='X', y_field='Y', epsg=4326):
"""
Converts a Pandas DataFrame to a GeoPandas DataFrame
Args:
pddf (Pandas DataFrame)
x_field (str)
y_field (str)
epsg (int)
"""
... | e802d9f35b321b9c1612d0a00a7ffe86c8a50317 | 80,772 |
def elapsed_time(seconds, suffixes=['y','w','d','h','m','s'], add_s=False, separator=' '):
"""
Takes an amount of seconds and turns it into a human-readable amount of time.
"""
# the formatted time string to be returned
time = []
# the pieces of time to iterate over (days, hours, minutes, etc)... | 6ea9fc170e6353e8896356865ec26744d23e31e6 | 80,773 |
def determine_whether_step_is_charging(step_dataframe):
"""
Helper function to determine whether a given dataframe corresponding
to a single cycle_index/step is charging or discharging, only intended
to be used with a dataframe for single step/cycle
Args:
step_dataframe (pandas.DataFrame):... | 03520634a0fa0ea8c25d75d6f2065cdb189c43ea | 80,776 |
def find_empty_cells(board):
"""Returns the empty cells of the board."""
return [x for x in board if x in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]] | b7a976f910710f7e10f1ad60804a6d7e22550da1 | 80,777 |
def make_minibatch(arg, start, stop):
""" Does not handle off-size minibatches """
if len(arg.shape) == 3:
return [arg[:, start:stop]]
else:
return [arg[start:stop]] | 64a1fd2b1acb1eaa3f352ee01494bf554e05a38c | 80,778 |
import base64
def to_b64(bytestring):
"""" return a base64 encoded string"""
return base64.b64encode(bytestring).decode('utf8') | 1ab2eeef3d4ba28f763b353ca0efda5f755e576c | 80,780 |
def detect_edges_better(img: Image, thresh: int = 0,
disp: bool = True, save: bool = False):
""" Return an image with the edge detects.
Written by Anthony Luo (#101145222)
:param img: Image to detect edges on
:param thresh: Threshold value for detection
:param disp: Whether o... | f49b4ea3ed4d87980d6cc88f124724baea3ce72a | 80,781 |
def read_xml_no_truncated(img_path):
"""Read bounding box from xml with no truncated
Args:
img_path: path to image
Return list of bounding boxes
"""
anno_path = img_path.split('.')[0] + '.xml'
tree = ET.ElementTree(file=anno_path)
root = tree.getroot()
ObjectSet = root.findall('o... | 018f5aec79df2189a7c9b35cacaaa6473433d1be | 80,783 |
import torch
import math
def gelu(x):
""" Original Implementation of the gelu activation function in Google Bert repo when initially created.
For information: OpenAI GPT's gelu is slightly different (and gives slightly different results):
0.5 * x * (1 + torch.tanh(math.sqrt(2 / math.pi) * (x + 0.0... | 025c5f830103d251f6d7014acbcc9b382ccdc4d5 | 80,784 |
def conv_decay_b_a(decay_b):
"""Converts a fractionnal decay constant dictionnary to an absolute decay constant dictionnary (fractionnal decay dictionnary stores decay constant as fraction over total decay constant, absolute decay dictionnary stores absolute values of decay constants).
**Note**: Library must ... | bb0f60563024e974d36c63db18c0d10f65f67277 | 80,785 |
from typing import List
from typing import Optional
from typing import Union
from typing import Generator
def cone_search(center: astropy.coordinates.SkyCoord,
radius: astropy.coordinates.Angle,
columns: List[str],
objectIds: Optional[list] = None,
forma... | 595db2fbb2f5309e5fed1576233eed99aa8ac81b | 80,786 |
def aboutus(request):
""" About page """
return render(request, "about.html", {"title": "About"}) | 3c07cdd4a59e51278b23da8f00963bbcbc468405 | 80,787 |
import logging
def vms_stop(access_token, vm_serial_number):
"""Stop FlexVM Virtual Machines"""
logging.info("--> Stop FlexVM Virtual Machines...")
uri = FLEXVM_API_BASE_URI + "vms/stop"
headers = COMMON_HEADERS.copy()
headers["Authorization"] = f"Bearer {access_token}"
body = {"serialNumber... | b390fae361e853fea5bf80bacd1aa191ba2206d8 | 80,788 |
def is_set_nickname(string, nickname):
"""
Test if this is a nickname setting message
"""
if string.startswith(f"{nickname} set the nickname for "):
return True
if string.startswith(f"{nickname} set his own nickname to"):
return True
if string.startswith(f"{nickname} se... | aec4909f3c4d3dea689383cc73d26623a16dfd85 | 80,789 |
def reof(stack: xr.DataArray, variance_threshold: float = 0.727, n_modes: int = 4) -> xr.Dataset:
"""Function to perform rotated empirical othogonal function (eof) on a spatial timeseries
args:
stack (xr.DataArray): DataArray of spatial temporal values with coord order of (t,y,x)
variance_thres... | dc29b10a6a19b3100faf8132ab2b81920a6db4e9 | 80,790 |
def gram_status(subject: Subject) -> str:
"""
Given an instance of Subject, return the gram status of isolated organisms.
Where multiple organisms are found, if gram status differs amongst orgs, returns 'mixed'
Parameters
----------
subject: Subject
Returns
--------
str
Str... | 04b1f22ffb17ab2dda235f1d26cfe65a6277b9b8 | 80,792 |
import itertools
def _get_aps_claims(namespace):
""" Get claims in a list with paragraphs separated by newlines.
Parameters
----------
namespace : uspto_parsing_tools.aps.NameSpace
Namespace to parse.
Returns
-------
list[str]
"""
claims = list()
start_i = 0
while... | baf907cc14654d8c9817fc18bb9e489411b8252e | 80,793 |
def nodalAveraged(odbInstance,Frame,StressType,timestep):
"""
For a given solution step, timestep, and stress type
this function will return 100% nodal averaged results
sorted by node number. (Note that the element set is
hardcoded.)
"""
# Get number of nodes
Field = Frame[timestep... | d568229742a52ac26d137e0c40a63ab824b92398 | 80,794 |
def timings_out(reps, func, *args, **kw):
"""timings_out(reps, func, *args, **kw) -> (t_total, t_per_call, result)
Args:
reps: Function execution times.
func: The function to be executed.
*args, **kw: Function parameter.
Return:
Total execution time, average execution time,... | 834106f95d8ae8a55cf0e9b4f7d151c5c5aef67e | 80,795 |
def read_excel(path, names, usecols):
"""Read Impex Excel file
:param path: filepath
:param names: column names
:returns: single sheet - dataframe
many sheets - dictionary of dataframes
"""
return pd.read_excel(
path,
sheet_name=None, # load all shee... | bfb444a46ad9d131e9d8d4c44bc79acc5b81cc02 | 80,796 |
import itertools
import re
def check_symbol(InputSet):
"""
Check the symbol line in POSCAR and write corresponding POTCAR file
Note: there are two ways to write the magmom:
site_properties: magmom or other properties?
run the after self.write_input, then all the thing is writte... | fbdeb644cfad18560fa36d5c32956ebe6a24f50e | 80,797 |
def chunks(l, n):
"""Yield successive n-sized chunks from l.
Args:
l:``list``
list of data
n:``int``
n-sized
Return:
list of list: [[]]
"""
temp_l = []
for i in range(0, len(l), n):
temp_l.append(l[i : i + n])
return te... | 75e3e987bab8ea1f5f5aada5851fc0692ea69ccc | 80,798 |
from typing import Union
from pathlib import Path
import textwrap
import time
def server_html_link_get_str(
s: Union[Path, str],
image=False,
name=None,
display_height=None,
display_width=None,
units="px",
):
"""Given a filepath, return an html <img> or a download link
For images, ret... | 1f1a22b7c844126b95d8fe683ccd8f1cd431cbf8 | 80,799 |
def standard_cl_params(items):
"""Shared command line parameters for GATK programs.
Handles no removal of duplicate reads for amplicon or
non mark duplicate experiments. If we have pre-aligned inputs we
ignore the value or mark duplicates (since they may already be
marked in the input BAM).
"""... | 01919e7595202e550f3615da6862a6d72f7a0d12 | 80,800 |
import requests
def get_user_from_keycloak(auth_data):
"""Get a user object from the keycloak server"""
config = get_keycloak_config(is_private=True)
response = requests.get(
config["user_url"], headers={"Authorization": "Bearer " + auth_data["access_token"]}
)
if response.status_code == 2... | 7c1a02e11a82ab8a6656ad281dd138045723fa0f | 80,801 |
def connect_host(host,log_route,log_name):
"""连接主机"""
host_error = False
hostname, port, username, password = host
client = paramiko.SSHClient() # 创建客户端
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, port, username, password, timeout=3)
... | 2d681c9b56861f1b030c2a5b665b029e386551ec | 80,802 |
def get_password_hash(user):
"""
Gets the hashed password of the given user.
:param user: The name of the user to get the hashed password of.
:return: The hashed password of the given user.
"""
return User.query.filter_by(username=user).first().password | 88612bc8dbf9fb7055f44fd615c090933aa23e75 | 80,803 |
import re
def IdleTimeoutToDuration(value):
"""Convert valid idle timeout argument to a Duration value of seconds.
Args:
value: A string in the form Xm or Xs
Returns:
Duration value of the given argument.
Raises:
ValueError: if the given value isn't parseable.
"""
if not re.compile(appinfo.... | 0b3f1eeefefd08564b948cff8f70df01f1eba926 | 80,804 |
def delete_movie(request, id):
"""
Delete movie by id
"""
try:
movie_object = Movie.objects.get(id = id)
movie_object.delete()
HttpResponse.status_code = status.HTTP_200_OK
return JsonResponse({'message': "Movie deleted successfully"})
except Movie.DoesNotExist as e:
HttpResponse.status_code = status.... | d1e627b2368b5989243799245fa864b0258aba4c | 80,805 |
from pycls.models import effnet
import torch
def load_efficientnet(init_args):
"""Load pretrained EfficientNet models released by FAIR."""
model_name = init_args["model_name"]
# We will use pycls from FAIR to load EfficientNet models.
# See prepare_efficientnet.sh for instructions to install this lib... | 106f0373f1d725176c5c8260c828d3d6417e233c | 80,806 |
import textwrap
import re
def shorten_comment(line, newline, max_line_length):
"""Return trimmed or split long comment line."""
assert len(line) > max_line_length
line = line.rstrip()
# PEP 8 recommends 72 characters for comment text.
indentation = _get_indentation(line) + '# '
max_line_lengt... | df4fd66f7aa35784be1ef5c89acbd6b966c69a9d | 80,807 |
def euckr(source):
"""Convert euc-cn string to cp949"""
result = decoder.cp949(encoder.euccn(source))
return result | a7530d822fdd7499c632807334ec07e5ea44ffcb | 80,809 |
def search(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
s = 0
e = len(nums)-1
while s <= e:
m = s + (e - s)//2
if target == nums[m]:
return m
if target > nums[m]:
s = m + 1
else:
e = m - 1
... | 2ad08b154fc6dbc3179e0a34cc7e48da3c8f8aaa | 80,810 |
def GetVJDStatus(rID):
"""Get the status of a given vJoy Device"""
return _vj.GetVJDStatus(rID) | 6d0c15280116459096d727be84768fc6fcb40526 | 80,811 |
def plot_vector(c, color='k', start=0, linestyle='-'):
"""Plotting complex number as vector
Notebook: PCP_exp.ipynb
Args:
c: Complex number
color: Vector color (Default value = 'k')
start: Start of vector (Default value = 0)
linestyle: Line Style of vector (Default value = ... | fb5bd87e28549f8ebf5d3d2031b5884b075d0b76 | 80,813 |
import random
def generate_tests(paths, mode='singlepath', seed=None):
"""
Return a list of probing tests given a probing-path dictionary.
Each test is a list of paths to probe as part of the test.
Supported modes have been tested for reproducibility given a seed.
:param paths: Path dictionary
... | 7adecb58efcd29e4ac1f2896f184d11510ff8337 | 80,814 |
def formMaskForSource(source_file_name, mask_file_name, name, startTimeandFrame=(0, 1), stopTimeandFrame=None):
"""
BUild a mask from file from a source video file.
Non-Zero values = selected.
:param source_file_name:
:param mask_file_name:
:param name:
:param startTimeandFrame:
:param s... | c8887bf38c631e61742a2fc7e15db8deb1ee32a3 | 80,815 |
def k2xyf(kx, ky, kz, z0):
"""Convert comoving k-space coordinates to spatial-frequency coordinates.
Parameters
----------
kx : ndarray
Array of kx [h/Mpc].
ky : ndarray
Array of ky [h/Mpc].
kz : ndarray
Array of kz [h/Mpc].
z0 : float
Reference redsh... | 7fbfd964f63985e8bba158eb7a0d51a9121bec53 | 80,816 |
def query_to_dataframe(query, connection=None, columns=None, **kwargs):
"""Load a Pandas dataframe from an SQLAlchemy query.
:param query: the query to be executed
:type query: sqlalchemy.orm.query.Query
:param connection: the connection to use to execute the query. By default
the method will create a new ... | 89895cccd85c59948b23e2227e1705ea75b12342 | 80,817 |
def team_detail_api(request, team_id):
"""
Endpoint class: CommonTeamRoster(), TeamPlayerDashboard(), TeamInfoCommon()
'players' Endpoint fields:
PLAYER, NUM, POSITION, HEIGHT, WEIGHT, BIRTH_DATE, AGE, EXP, SCHOOL,
PLAYER_ID
'coaches' Endpoint fields:
COACH_NAME, COACH_TYPE
... | 6c8aec721429acd956eca053c31354f0ed261ea1 | 80,818 |
def cosine_rampdown(current, rampdown_length):
"""Cosine rampdown from https://arxiv.org/abs/1608.03983"""
assert 0 <= current <= rampdown_length
return float(.5 * (np.cos(np.pi * current / rampdown_length) + 1)) | 1578d465adf985de7d559ea6121c017380bca221 | 80,819 |
import time
import json
def getValidPoi(indexerId, subgraphHash, start_epoch):
"""Get's the POI for an Allocation on one subgraph for a Indexer.
Returns
-------
list
With subgraphIpfsHash, epoch of POI, startBlock of Epoch, start Hash of Block, POI
"""
# get startblock and startHash f... | a1e60949cf61370d1b145bcf0d7e25d820795d42 | 80,820 |
import copy
def getCombinedAnalyticalReprs(aRepList,copyObjs=True):
""" Gets an object that represents the additive combination of AnalyticalIntRepr functions
Args:
aRepList: List of individual objects with AnalyticalIntRepr interface
copyObjs (Bool): If true the returned object contains deep copies of input ... | cfe83dd0ea42491797f9934f55e5499466885974 | 80,821 |
def app_factory(global_settings, **local_settings): # pylint: disable=W0613
"""
Default factory for creating a WSGI application using the everest
configurator and root factory.
:param dict global_settings: Global settings extracted from an ini file.
Not used in this default app factory.
:pa... | 4bdeb8cc561fb52e9edcc1aac24daae2d9899e79 | 80,822 |
def containerise(
name, namespace, members, context, loader, current_containers=None
):
"""Add new container to metadata.
Args:
name (str): Container name.
namespace (str): Container namespace.
members (list): List of members that were loaded and belongs
to the container... | 0d0aa4406afda85ffe1c3565ddfcff36cb891ec6 | 80,823 |
from pathlib import Path
import pickle
import json
def load_saved(in_path: Path, file_format: str = "pickle"):
"""
Load saved pickle/json file.
"""
if file_format == "pickle":
with open(in_path, "rb") as f:
data = pickle.load(f)
elif file_format == "json":
with open(in... | ba068ae1538c01ce5ca4174868784b4c845d2b88 | 80,825 |
def compute_iou3d(gt_annos, pred_annos, split_parts, with_heading):
"""
Compute iou3d of all samples by parts
Args:
with_heading: filter with heading
gt_annos: list of dicts for each sample
pred_annos:
split_parts: for part-based iou computation
Returns:
ious: l... | a40ea2029b547ffad9396708ac4cc8ce0159231b | 80,826 |
async def update_life(game_id:int, state: ScoreUpdate, context: Context = Depends()):
"""
Used to manage each player or team's health throughout a game.
This method uses the increment parameter by default, absolute value
will be ignored if increment is used.
"""
try:
gam... | 3d60d040adb52a1e81972f911e1b2f170797533c | 80,827 |
from datetime import datetime
def post_too_old(post):
"""check that a bump is within the last two hours, to avoid old bumps reappearing"""
check_date = datetime.now()-timedelta(hours=2)
post_date = datetime.strptime(post.get('bump_time'), '%d %b %Y, %H:%M')
return check_date > post_date | 7966834557e561cfbd2451024384d5e6175fd15e | 80,828 |
def leastSquareSolution(A, b):
"""
return the least squares solution x for the system Ax = b
A is a list of list while b is a list
"""
m = len(A)
if m == 0:
return []
n = len(A[0])
if n > m:
s = solveWithForwardReplacement(A, b)
else:
s = solveWithBackwardRe... | e1e26d57066df1faccc075e24f623d2d2663bd14 | 80,829 |
def get_GAIA_data(coord, radius):
"""Query Gaia database.
Parameters
----------
coord : SkyCoord
Position to search.
radius : float
Radius of search cone.
Returns
-------
objects
table with the objects including the following info: ra (deg), ra_error (milliarcs... | 46fc45da5775737b8dc97a60794c5ae3d486074e | 80,830 |
def normalize_min_max(df):
"""
Uses min-max normalization to scale passed `pd.DataFrame` of values. Returns
`pd.DataFrame` of transformed values with original row and column labels.
"""
cols = df.columns
inds = df.index
arr = MinMaxScaler().fit_transform(df)
return pd.DataFrame(arr, col... | 00cf3d900611b42c3dc1593fb0ace50e5b6ed812 | 80,831 |
def get_identifier_from_recipe_file(filename):
"""Attempts to read filename and get the
identifier. Otherwise, returns None."""
recipe_dict = recipe_from_file(filename)
return get_identifier(recipe_dict) | 8d50d33228c08979d67b9e39bb475cf3f81c6d46 | 80,832 |
import stat
import math
import bisect
def line_discrepancy(net_sample, red_points, red_weights, blue_points, blue_weights, disc=stat):
"""
:param big_samp:
:param small_samp:
:param weights:
:param pt_num:
:param n: The sub-sampling size of the small sample.
:return:
"""
#net_sampl... | 28d52f8ce9fe81b72066f67556743df98035ce66 | 80,833 |
def FakeConduitCall(arc_root, conduit_name, json_input={}):
"""Returns a hard-coded value for any conduit-call we need."""
if conduit_name == 'user.query':
return [
{
"phid": "PHID-USER-00000000000000000000",
"userName": "csilvers",
"realName":... | 54f1a212363873cfe010b4a251856378c38d926e | 80,834 |
def format_phone(
row: pd.Series,
col: str,
output_format: str,
fix_missing: str,
split: bool,
errors: str,
) -> pd.Series:
"""
Function to transform a phone number instance into the
desired format.
"""
# pylint: disable=too-many-arguments,too-many-branches
country_code, ... | cb4916963aa5ed8ced9021396a6114f572584924 | 80,835 |
import bisect
def find_top_distances(x_l, x_r, ids, k_size=None):
"""
Return the top-k distances with ids from x_l to x_r
:param x_l: feature vector for main class
:param x_r: feature vector x_l of other class it is compared to
:param ids: list with ids of x_l with same length
:param k_size: h... | 5faa5f133c352b3d38f9d26a14250094558e1735 | 80,837 |
def parse_result_packets(packets):
"""
Parse a blob of one or more result packets
"""
resultPackets = []
# parse the first result packet
(responseName, counter, length, data, remainingData) = parse_result_packet(packets)
if responseName and responseName != '':
resultPackets.append... | 03a5567df08f5341b3458c4613cbd030852cdad2 | 80,838 |
def nearest():
"""**Flask POST rule.**
Create a new spatial file sorted by the nearest geometries.
---
post:
summary: Find the nearest geometries.
description: Create a new spatial file sorted by the nearest geometries. A new column *distance* is added to the attribute table with the di... | c69d21b2a75f5f1876bd52c0a615a532e16945bc | 80,839 |
def freq_to_pc(freq, include_octave):
"""
converts frequency to pitch class name
pitch class spec - [note name][s|f|n][octave]
examples: b4, cs5, af8, an3
include_octave adds octave number to ret'd string
"""
return midi_note_to_pc(freq_to_midi_note(freq), include_octave) | cc437c77a9203a2f3d89f582c5d10402e743cc72 | 80,840 |
def cmd_status(opts, args):
"""check status of merge/clang"""
def _get_size(pn):
if pn is None or not os.path.exists(pn):
return 0
return os.stat(pn).st_size
for fs in fsop.get_all_fs():
one = _get_merged_file(fs)
fss = _get_fss_file(fs)
print "%-10s %1... | ad3a7c011c32fd6de38790982d1697cfa26b81c3 | 80,841 |
def checkGoalSet(graph):
"""Check if there are any nodes in the goal set
Input arguments:
graph = graph which is to be checked
"""
dictNodes = nx.get_node_attributes(graph,'goalSet')
goalNodes = list(dictNodes.keys())
if not goalNodes:
return False
return True | f28ac90436f1c4c7560f683e4876468d5c41c335 | 80,842 |
def load_covid_data(covid_filepath, dropdate, base_geo):
"""Load in and set up denominator data.
Args:
covid_filepath: path to the aggregated covid data
dropdate: data drop date (datetime object)
base_geo: base geographic unit before aggregation ('fips')
Returns:
cleaned de... | f9d86209da30b1677a693f2b156f64d464d5207d | 80,843 |
def QA_fetch_account(message={}, db=DATABASE):
"""get the account
Arguments:
query_mes {[type]} -- [description]
Keyword Arguments:
collection {[type]} -- [description] (default: {DATABASE})
Returns:
[type] -- [description]
"""
collection = DATABASE.account
return ... | bcbe5bcd4003c4788488d791b51f2bd869899141 | 80,844 |
def mixin_class(cls):
"""Decorator to register a mixin class
Fills in any known behaviors based on class inheritance
"""
name = cls.__name__
awkward1.behavior[name] = type(name + "Record", (cls, awkward1.Record), {})
awkward1.behavior["*", name] = type(name + "Array", (cls, awkward1.Array), {})... | cb429cef8223b1c91c91cc656dfaa83b5c968763 | 80,845 |
def MaxPool(parent, pool_size=[2, 2], strides=[2, 2], padding="none", name=""):
"""\
Perform Max pooling.
:param parent: parent layer
:param pool_size: size of the max pooling windows
:param strides: factor by which to downscale
:param padding: one of "none", "valid" or "same"
:param name: ... | 711efc2777fa47869eb6d2fe085b22ce15863af1 | 80,846 |
def types_like(array: jax.ShapedArray) -> tf.TensorSpec:
"""Converts the nested tree input to `ArrayAlias` types.
Can be used to check expected spec:
```
assert j3d.types_like(out) == f32[1, 28, 28, 3]
```
Args:
array: Nested tree of arrays,...
Returns:
Nested tree of `jnp.zeros` matching the ... | 6bc3b0eb4c744b2fcdb0c520710061441b726bca | 80,847 |
def fee(request):
"""
Definition of the /fee endpoint, in accordance with SEP-0006.
See: https://github.com/stellar/stellar-protocol/blob/master/ecosystem/sep-0006.md#fee
"""
# Verify that the asset code exists in our database:
asset_code = request.GET.get("asset_code")
if not asset_code or... | 7500bd55cc050cb0dfa93117cb693965b9ac367a | 80,848 |
import inspect
def generateGroupConfigManagementMethods(**kwargs):
""" Generate UI-visible config management methods for Group config objects.
(i.e. config objects which have multiple instances)
"""
def add(self, itemname=None, params=None):
"""
Add and configure [%(description)... | 102c6490f47fca30042d5be22fababa4b92e0a1b | 80,849 |
import yaml
import time
import copy
def qupath_polygon(data_config):
"""Build DSA annotation json from Qupath polygon geojson
Args:
data_config (string): path to your data config file that includes input/output parameters.
input (string): path to Qupath polygon geojson
output_folder ... | 7e8775e6fa2b894114bdfa6a76a5cd4b84ab5f0c | 80,850 |
def slice_and_stitch_func(values):
"""
This function creates a partial function of slice_and_stitch to be used by the model.
:param values: list or dict. a sequence of all values a subject in the population can have
:return: a partial function f(subject1, subject2) => (new_subject1, new_subject2)
"... | 64cb7859fda71aea18bfe6fb8f0510f64c5839f8 | 80,851 |
def decay_every_scheduler(step, steps_per_decay, decay_factor):
"""Gives a scaling factor based on scheduling with a decay every n-steps.
Args:
step: int; Current step.
steps_per_decay: int; How often to decay.
decay_factor: float; The amount to decay.
Returns:
Scaling factor applied to the lear... | 1a7a0f333cebfbc6851111f9cd83156b72fecc3d | 80,852 |
def l2_regularization(W, reg_strength):
"""
Computes L2 regularization loss on weights and its gradient
Arguments:
W: np array, weights
reg_strength: float value
Returns:
loss: single value - l2 regularization loss
gradient: np.array same shape as W - gradient of weight by l2 l... | cf086bf19083612941659ccfdd8631146285c20e | 80,853 |
def table_to_jinja(table):
"""
Convert to jinja-template
Zip/Transpose the columns/data so easier to iterate in jinja template
:type Table
:param table:
:return:
"""
nvalues = len(table.columns[0].values)
headers = [c.id for c in table.columns]
items = []
for c in table.c... | a884f9094bb08aa2ac54798bb6aa5ddbae9d9cd0 | 80,854 |
def filter_ctrl_pert(gse_gsm_info):
"""
Filter the GSE that do not contain both control and perturbation samples
Args:
gse_gsm_info: the GSE and GSM info tuple
Returns:
True if there are both control and perturbation samples, False otherwise
"""
gse_id, gsm_info = gse_gsm_info
... | 491fd23723a026ddf68fe3a56d98e097a0732e63 | 80,855 |
def deduce_alpha_implications(implications):
"""deduce all implications
Description by example
----------------------
given set of logic rules:
a -> b
b -> c
we deduce all possible rules:
a -> b, c
b -> c
implications: [] of (a,b)
... | 85741f4e0e79a5cd2fa3df8b7b20b3c6805aab7c | 80,856 |
def _replace_yamlfiles_in_sql(sql_query):
""" replace file pathing in sql """
# file.yaml is valid is sqlite but removing them in ext
for afile in _get_files_in_sql(sql_query):
table_name = yaml2sql.get_table_name(afile)
sql_query = sql_query.replace(afile,table_name)
return sql_query | a85c0fd8c5d9e93f6553779e1908294ccbb2d86d | 80,857 |
def makelaglist(lagstart, lagend, lagstep):
"""
Parameters
----------
lagstart
lagend
lagstep
Returns
-------
"""
numsteps = int((lagend - lagstart) // lagstep + 1)
lagend = lagstart + lagstep * (numsteps - 1)
print(
"creating list of ",
numsteps,
... | f31f39895eb5740f1d6c77626aff6f9fd11e47c2 | 80,858 |
from typing import Callable
from typing import List
from typing import Dict
def ft(theta: np.ndarray, f: Callable, T: int, x_0: np.ndarray=None,
xi_1_0: np.ndarray=None, P_1_0: np.ndarray=None,
force_diffuse: List[bool]=None, is_warning: bool=True,
const_M_type: str='simple') -> Dict:
"... | c9e620b53592d11a97658796793258d9b33c33a5 | 80,859 |
def identifiers(self, key, value):
"""Translate identifiers."""
_identifiers = self.get("identifiers", [])
if "a" in value:
isbn = {
"scheme": "ISBN",
"value": clean_val("a", value, str, req=True),
}
if isbn not in _identifiers:
_identifiers.append... | 13142727ef3d9356d99fefefd193ace57d3e6677 | 80,860 |
def isSoluble(c, *numbers):
"""
Check if the diophantine equation a1 * x1 + a2 * x2 + ... + an * xn = c is
soluble
Parameters
----------
c: int
integer c of the equation a1 * x1 + a2 * x2 + ... + an * xn = c
a1, a2, a3,..., an: ints
coefficients a1, a2, ..., an of the equati... | 98069367fe7c7bb558a1d5f18c4c85947aa5b2f5 | 80,861 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.