content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
import itertools
def filter(iterator, field, value):
"""
Takes an iterator and returns only the docs that have a field == value.
The field can be a nested field like a.b.c and it will descend into the
embedded documents.
"""
return itertools.ifilter(lambda x: _deep_get(x, field) == value, it... | c9f7a1a60c2add295e547144b63146c8d957d2b4 | 3,602,900 |
def progress(iter, **kwargs):
"""
프로그래스 bar
for i in progress(10):
print i
for i in progress(iter):
print i
"""
if isinstance(iter, int):
iter = xrange(iter)
if hasattr(iter, '__len__') or 'target' in kwargs:
cls = Progress
else:
cls = ProgressBas... | 296f9f2574b939d57e583742f7833817eebefdd7 | 3,602,901 |
import sklearn
def auc_roc(yhat, ytrue):
"""
Class wise AUC ROC.
:param yhat:
:param ytrue:
:return:
"""
auc_roc = np.array([
sklearn.metrics.roc_auc_score(y_true=ytrue[:, i], y_score=yhat[:, i])
for i in range(ytrue.shape[0])
])
return auc_roc | 44a30350aa9aa0eff5cc6d947932dedd901da3e1 | 3,602,902 |
def keV_to_kelvin(temperature):
"""Convert from temperature expressed in keV to a temperature
expressed in Kelvin"""
return temperature * (con.e / con.k * 1000.0) | b7888babed588be952308a3c2821d57eba43f778 | 3,602,903 |
def extract_text(tweet):
"""Gets the full text from a tweet if it's short or long (extended)."""
def get_available_text(t):
if t['truncated'] and 'extended_tweet' in t:
# if a tweet is retreived in 'compatible' mode, it may be
# truncated _without_ the associated extended_tweet
... | 41660b71e3b020bc25309821b46471e88d79aa49 | 3,602,904 |
def search_linearf(a, x):
"""
Returns the index of x in a if present, None elsewhere.
"""
for i in range(len(a)):
if a[i] == x:
return i
return None | 949cb93218381a1a45002be03c6b8ca4d00092bf | 3,602,905 |
def update_posterior(n: np.ndarray, alpha: np.ndarray) -> np.ndarray:
"""
Updates posterior distribution.
Parameters
----------
n : np.ndarray
Amount to update posterior distribution parameter by.
alpha : np.ndarray
Posterior distribution parameter.
Returns
-------
... | fa9f69c0dddb8c819982485d411cf76b88b7f53e | 3,602,906 |
def from_xml(xml):
"""Deserialize XML to a dictionary."""
if xml is None:
return None
deserializer = XmlDeserializer()
return deserializer(xml) | 61ee1ce93e427ca405542d5b46853466b9db3a00 | 3,602,907 |
import networkx
import itertools
def primes2stg(Primes, Update, InitialStates=lambda x: True):
"""
Creates the state transition graph (STG) of a network defined by *Primes* and *Update*.
The *InitialStates* are either a list of states (in *dict* or *str* representation),
a function that flags states t... | caba25a6b11fa6e5a80c217de7d8592d9697fb32 | 3,602,908 |
def autoprops_override_decorate(func, # type: Callable
attribute=None, # type: str
is_getter=True # type: bool
):
# type: (...) -> Callable
"""
Used to decorate a function as an overridden getter or... | 80ac64ead677d0b84d1a86f6cff38839d564d3bb | 3,602,909 |
import logging
def fetch_from_landing_page(landing_url):
"""Returns a tuple of (pdf_link, summary_text)."""
add_pdf = False
skip = False
page = utils.beautifulsoup_from_url(landing_url)
report_tables = page.select('table[summary~="reports"]')
# in the rare case that doesn't work, have faith
if len(rep... | 9e02f0525921596909af00fdf5b08e08c7b22eb4 | 3,602,910 |
import requests
def get_user_contribs(username):
""" Fetch user contributions via MediaWiki API's Usercontribs module """
params = {
"action": "query",
"format": "json",
"list": "usercontribs",
"ucprop": "user|ids|title|sizediff",
"ucuser": username,
"uclimit": ... | d59810b6ac87e0dba28c9b21be9a21de6f878e80 | 3,602,911 |
import os
def get_npy_files(outputdir):
"""
List npy files
:param str outputdir: location of npy files
:returns: npy_files
:rtype: list
"""
npy_files = os.listdir(outputdir)
npy_files = list(filter(is_npy, npy_files))
npy_files.sort()
return npy_files | f064b078586608ec1bc47d844b5d845a6ac4ecdc | 3,602,912 |
def max_pool(x: Tensor, kernel_size: tuple, stride: tuple=None, padding: tuple=(0, 0)):
"""
Performs max pooling.
## Parameters
x: `Tensor` - input tensor
kernel_size: `tuple` - shape of the kernel
stride: `tuple` - stride, if not set default shape is same as kernel_size
padding: `tuple`... | ed87b5902341f7ec9caff1b7e94e125fd899ff63 | 3,602,913 |
def create(holmes, user=None):
"""# Create BoletoHolmes
Send a list of BoletoHolmes objects for creation in the Stark Bank API
## Parameters (required):
- holmes [list of BoletoHolmes objects]: list of BoletoHolmes objects to be created in the API
## Parameters (optional):
- user [Organization/P... | abc5c51f6ab05195340f5bbbcb4d88270043e1e6 | 3,602,914 |
import subprocess
def get_service_status():
"""
Determine whether the service is running and it's PID. Return the 2 tuple
containing a status string and PID. If the service is not running, PID is
None
"""
try:
output = subprocess.check_output([VMDK_OPSD, "status"]).split()
if o... | f97e1e9dcc163efa2e4aa5febcedc38516689062 | 3,602,915 |
import re
def generate_history_diff(collection, identifier=None):
"""
Returns a list of revisions for a record, showing fields that changed in each revision.
collection: a list of Version objects (django-reversion)
identifier: optional description of the object being edited (e.g. 'Geoexchange Driller... | 8915c76c6b7eee7c027dc83ba0e37ad3083c414e | 3,602,916 |
def sans_checksum(data):
"""Verify checksums and remove them from data"""
_LOGGER.debug("data: %s (%d)", data.hex(), len(data))
csum_len = 2
head_len = 9
body_len = data[0] - head_len
remainder = body_len % 16
times = int((body_len - remainder) / 16)
times += 1 if remainder > 0 else 0
... | cafc5ff6465efd4a76a48bd353fe91a0b05e4a35 | 3,602,917 |
def modules():
"""Entry point for getting the pyxll modules.
Returns a list of module names."""
return [
__name__
] | 2f53cd00387c7533404b8e97a8da34fb3c5811e9 | 3,602,918 |
def render_new_card(self, h, comp, *args):
"""Render card creator minified"""
h << h.a(h.strong('+'), h.span(_('Add a card')),
class_='link-small').action(comp.becomes, model='add')
if self.needs_refresh:
h << h.script('increase_version();')
self.toggle_refresh()
return h.ro... | 5ba03707e47e51a79c8fd51489d4224e35437a05 | 3,602,919 |
def gamma_corr(clip, gamma):
""" Gamma-correction of a video clip """
def fl(im):
corrected = 255 * (1.0 * im / 255) ** gamma
return corrected.astype("uint8")
return clip.fl_image(fl) | d98d411c63d932b068d80bef63d42289cb0d8468 | 3,602,920 |
def _segment_labels(Yi):
"""Segmenting the labels for segmental edit score
"""
idxs = [0] + (np.nonzero(np.diff(Yi))[0]+1).tolist() + [len(Yi)]
Yi_split = np.array([Yi[idxs[i]] for i in range(len(idxs)-1)])
return Yi_split | 902f187be828f649f99a53cfa72ccf79016f9630 | 3,602,921 |
def connected_components(graph):
"""
Given an undirected graph (a 2d array of indices), return a set of
connected components, each connected component being an (arbitrarily
ordered) array of indices which are connected either directly or indirectly.
"""
def add_neighbors(el, seen=[]):
''... | e8299cc024dd27414a287ee0afa302ea64c18b68 | 3,602,922 |
def remove_reference_syntax(definition):
"""
Definitions in English may contain references to Chinese words. The reference syntax contains
vertical bar-separated Han characters as well as a pronunciation enclosed in brackets,
as in "Jiajiang county in Leshan 樂山|乐山[Le4 shan1]".
Remove the reference ... | 91f973a17558881cdaa2da96239cd8c87e103807 | 3,602,923 |
from datetime import datetime
def library():
"""
Create a 4-column, 6-row dataset with numbers and text.
"""
ds = xport.Dataset(
data={
'VIT_STAT': ['ALIVE'] * 3 + ['DEAD'] * 3,
'ECON': ['POOR', 'NOT', 'UNK'] * 2,
'COUNT': [1216, 1761, 2517, 254, 60, 137],
... | 46ca6c05a83c0c8cf03063c1a19f155698f1f589 | 3,602,924 |
def get_segment_point_intersect(seg, pt):
"""Returns the intersection of a segment and point.
Parameters
----------
seg : libpysal.cg.LineSegment
A segment to check for an intersection.
pt : libpysal.cg.Point
A point to check ``seg`` for an intersection.
Returns
-------
... | 9f5c030ab7b995416c3918b853206eb64ebb11c4 | 3,602,925 |
import torch
def log_like_internal(pt_sum_compressed, data, x_m_ary, x_m_sum):
""" Non-Poissonian likelihood for single template, given x_m and x_m_sum
"""
k_max = torch.max(data) + 1
npixROI = int(pt_sum_compressed.size(0))
f0_ary = -(pt_sum_compressed + x_m_sum)
f1_ary = pt_sum_compressed ... | 939fbc1ed070ee0183150cfc01d92d77b1a09fc7 | 3,602,926 |
def generateCards(numberOfSymb):
"""
Source: https://fr.wikipedia.org/wiki/Dobble
"""
nbSymByCard = numberOfSymb
nbCards = (nbSymByCard ** 2) - nbSymByCard + 1
cards = []
n = nbSymByCard - 1
t = []
t.append([[(i + 1) + (j * n) for i in range(n)] for j in range(n)])
for ti in range(n... | 5cf56864675668213f593395978fa511d0ed3784 | 3,602,927 |
def keep_exit_with_descr(descr, router, guard):
"""Checks that the router is not a bad exit, is not down, is stable,
is valid, does not run an old TOR's version, has an available ed25519
identity key and has an 'accept' exit policy
:param descr: descriptor of the exit candidate.
:params router: the ... | 4766bb038499d6bd45e71bd98122514936bd8da0 | 3,602,928 |
def _GetAndroidGnOutputLocale(line):
"""Check a GN list, and return its Android locale if it is an output .xml"""
m = _RE_GN_VALUES_LIST_LINE.match(line)
if not m:
return None
if m.group(1): # First group is optional and contains group 2.
return m.group(2)
return resource_utils.ToAndroidLocaleName(... | 2d784b2c8bb9e548b61d3d7a106c572f1bbe80fe | 3,602,929 |
from typing import Tuple
def cost_sparse(n: int, lam: float, d: int, dE: float, chi: int,
stps: int) -> Tuple[int, int, int]:
""" Determine fault-tolerant costs using sparse decomposition in quantum
chemistry
Args:
n (int) - the number of spin-orbitals
lam (float) - th... | ee013800bae43e66b417ec42fa3380e356b98bd8 | 3,602,930 |
def get_final_sorted_cavs(dict_all_info, filtered_cavities):
"""
Uses dict_all_info to rank cavities for further exploitation (FP, export as PDB...)
and exclude few more cavities
"""
# scores will contain the scores of filtered cavities
scores = []
# ori_order will contain the original indices of the cavities
... | 01513b4e5c55c7f9ec1e48274103044d92ed2fd5 | 3,602,931 |
import http
import os
import logging
def browse_files(instance, sandbox_dir, path):
"""
Calls the files/browse endpoint on the Mesos agent corresponding to
the given instance, and for the provided sandbox directory and path
"""
agent_url = mesos.instance_to_agent_url(instance)
resp = http.__ge... | 8433bb0590ffba93782aef8a8fc1b3a309545750 | 3,602,932 |
def create_model_four_conv(input_shape):
"""
CNN Keras model with 4 convolutions.
:param input_shape: input shape, generally X_train.shape[1:]
:return: Keras model, RMS prop optimizer
"""
model = Sequential()
model.add(Conv2D(32, (3, 3), padding="same", input_shape=input_shape))
model.ad... | 81bcca89d130f6b5e42493b8a73ea0332e951bc9 | 3,602,933 |
def svn_repos_fs_revision_proplist(*args):
"""
svn_repos_fs_revision_proplist(svn_repos_t repos, svn_revnum_t rev, svn_repos_authz_func_t authz_read_func,
apr_pool_t pool) -> svn_error_t
"""
return _repos.svn_repos_fs_revision_proplist(*args) | 7eb893741c4bf83f8caee0974e9e663d6d07644e | 3,602,934 |
import logging
import time
def get_joystick(sensehat):
"""Get joystick input.
Parses last valid event since last read.
Args:
sensehat (SenseHat)
Returns:
direction, pause
"""
pause = .25 # seconds
while True:
events = sensehat.stick.get_events()
for even... | 1bec4c66fd5b49e54c414eabe389ff5689f6d559 | 3,602,935 |
import math
import torch
def loglinspace(a, b, n=100, **kwargs):
"""Like :meth:`torch.linspace`, but spread the values out in log space,
instead of linear space. Different from :meth:`torch.logspace`"""
return math.e**torch.linspace(math.log(a), math.log(b), n, **kwargs) | ea456462a0d029f1ada1c4a9e40c9377b86e815d | 3,602,936 |
from sys import path
def get_files(directory, filterfn=lambda x: True):
"""Get all the files that are direct children to the given directory and
match the given filter function
:param directory: the directory whose immediate children are to be returned
:param filterfn: the function with which to filte... | 7e3925626de9c148076abe5fe4b2d42d1ea535dc | 3,602,937 |
import types
from typing import Optional
def get_data_view_uri(examples: types.Artifact) -> Optional[str]:
"""Returns the URI to the DataView attached to an Examples artifact.
Or None, if not attached.
Args:
examples: an Examples artifact.
Returns:
The URI to the DataView or None.
"""
assert exa... | c2e0303f42268c5b5e2da8ff4e334e6f7d1663d7 | 3,602,938 |
def infer_spaces(s):
"""Uses dynamic programming to infer the location of spaces in a string
without spaces."""
## Find the best match for the i first characters, assuming cost has
## been built for the i-1 first characters.
## Returns a pair (match_cost, match_length).
words = open("./../data/w... | fca5fb8311d29d3256e03e3462277cf8baac9337 | 3,602,939 |
def get_largest_sample_size(path_to_audio_files):
"""Recursively searches folder and find the largest sample size"""
largest_sample_size = 0
for wav_file in recursively_find_files(path_to_audio_files, '*.wav'):
loader = essentia.standard.MonoLoader(filename=wav_file)
audio = loader()
... | fb3e708541d9bf4b05e7e33e513f3555f38f4d72 | 3,602,940 |
def test_change_logs_on_call(mocker):
"""
Tests if the decorator works on every call
"""
mock = mocker.Mock()
@change(new=mock.new, on_call=mock.log)
def old_sum(a, b):
"""
Sample wrong sum
"""
return a + b + 1
result = old_sum(1, 2)
mock.log.assert_cal... | 354778055df87863d2a5977f9e7cd9ec298284c5 | 3,602,941 |
def fetch_restaurants(data_home=None):
"""Returns a stream containing the data from the Kaggle Recruit Restaurants challenge.
The data is ordered by data and then by store ID.
Parameters:
data_home (str): The directory where you wish to store the data.
Yields:
tuple: A pair (``x``, ``... | 6c8c9b9556128932cfaa5920277ee322c77898d5 | 3,602,942 |
import requests
from bs4 import BeautifulSoup
def get_author_work(url):
""" Get the complete list of work by an author.
Params
------
url(str): The Ideas url of the author.
Returns
-------
pd.DataFrame
"""
url = f'https://ideas.repec.org{url}'
resp = requests.get(url... | 0b6ed0b371c53d84cf7e9ae848038ecdfd173246 | 3,602,943 |
from typing import Optional
from typing import Dict
from typing import Set
import six
def compute_subclass_sets(
schema: GraphQLSchema, type_equivalence_hints: Optional[TypeEquivalenceHintsType] = None
) -> Dict[str, Set[str]]:
"""Return a dict mapping class names to the set of its subclass names.
A clas... | ce3d169fcb97e627916ff073ad317d2f40f1d0bb | 3,602,944 |
def optional_function(func):
"""Only apply function if input value is not None.
Function must be unary.
"""
def wrapper(x, *args, **kwargs):
if x is None:
return None
return func(x, *args, **kwargs)
return wrapper | 3db42719579fc6160b282af4e637f72f9df4781e | 3,602,945 |
def sym2isomass(symbol):
"""
Function to get a mapper dictionary to get isotopic masses rather than
isotopically weigthed atomic masses.
.. code-block:: python
>>> sym2isomass('Ni')
{'Ni': 57.9353429}
>>> sym2isomass(['Ni', 'H', 'C'])
{'H': 1.0078250321, 'C': 12.0, 'Ni'... | 35e485e6d127f6747ba5c8097edf00213b302927 | 3,602,946 |
def _recover_stressi_ctube(xb, dof_map, elem, prop):
"""get the static ctube stress"""
nid1, nid2 = elem.nodes
# axial
i11 = dof_map[(nid1, 1)]
i12 = i11 + 1
i13 = i11 + 2
i21 = dof_map[(nid2, 1)]
i22 = i21 + 1
i23 = i21 + 2
# torsion
i14 = i11 + 3
i15 = i11 + 4
i1... | 6ff2e90d9effe6aef0ddc0b9d407621001f3dbf3 | 3,602,947 |
def battery_converter(result):
"""
Converts a voltage reading result with battery charge state and level.
"""
voltage = result.get("value", None)
ret = {
"_type": "bat",
"level": battery_util.charge_percentage_for(voltage, nominal_voltage=context["battery"]["nominal_voltage"]),
... | 44efe538ee1a511f9b63fd6e83c46e5f106f3c14 | 3,602,948 |
def put_kernels_on_grid (kernel, pad = 1):
"""Visualize conv. features as an image (mostly for the 1st layer).
Place kernel into a grid, with some paddings between adjacent filters.
Args:
kernel: tensor of shape [Y, X, NumChannels, NumKernels]
(grid_Y, grid_X): shape of the grid. Re... | d7db3ed046e31be45e97c7dfe17c0df149d47ed8 | 3,602,949 |
def _is_sub_scope(scope, parent_scope):
"""
Returns True if the given scope is a subset of the permissions
defined in the parent scope.
"""
return not any (
frozenset(permissions_grant).difference(chain.from_iterable(
parent_permissions_grant
for parent_model_grant, p... | a470cd80337826ca18372c65beaf87860dbaf855 | 3,602,950 |
from typing import Union
from pathlib import Path
from typing import Any
import yaml
def read_yaml(fname: Union[str, Path]) -> Any:
"""Read the given file using YAML.
Parameters
----------
fname : str
the file name.
Returns
-------
content : Any
the object returned by YAM... | d0ee4cea6ef04da699d41f03144f36bff4a61914 | 3,602,951 |
def butter_bandpass_filter(rate, data, freqLowCutoff, freqHighCutoff, order=5):
"""Butterworth band pass filter"""
nyq = 0.5 * rate
low = freqLowCutoff / nyq
high = freqHighCutoff / nyq
b, a = butter(order, [low, high], btype='band')
y = lfilter(b, a, data)
return y | 675a62ca3773ea73018ae34b63f4c760a9f1f5c7 | 3,602,952 |
def co2_ppmfrommgCO2pm3(c_mgpm3,T,p):
"""
Convert CO2 concentration units of mgCO2/m3 to umol/mol (ppm)
Usage:
CO2_ppm = co2_ppmfrommgCO2pm3(CO2_mgpm3, T, p)
where
CO2_mgpm3 (input) - CO2 concentration, mgCO2/m3
T (input) - air temperature, C
p (input) - air... | dc1883a479fa79389255d1edf70deba7e1392f4a | 3,602,953 |
def parse_downsample(arg_list):
"""Parse a list of downsampling policies into a dict usable by specificrulevalue."""
def parse_one(arg):
"""
Parse a single downsampling policy.
A downsampling policy consists of a system type (per parse_systemtype), a colon, and a limit or retention prob... | d4a2d7a68ce98f037acea6f248baa274595ce142 | 3,602,954 |
def top_ten_ports_in_network_events():
"""
get top ten repeated ports in network events
Returns:
JSON/Dict top ten repeated ports in network events
"""
date = fix_date(
get_value_from_request("date")
)
country_ip_dest = get_value_from_request("country_ip_dest")
top_ports... | 843d4bbafe5972116a83ec0ca494622006b6e88d | 3,602,955 |
def plt_transfer_ellipse(a: float, focus: VEC, **kwargs) -> Ellipse:
"""Create a transfer ellipse
Parameters:
-----------
a : float
Semi-major axis of the ellipse (Lambert's problem).
focus : `VEC` (numpy.ndarray)
2D vector to vacant focus. The other focus is assumed to lie at the
... | 2a76c9a6ef084c5ba87b4e1a2190362b5352d934 | 3,602,956 |
import tokenize
def tag_and_stem(text):
"""
Returns a list of (stem, tag, token) triples:
- stem: the word's uninflected form
- tag: the word's part of speech
- token: the original word, so we can reconstruct it later
"""
tokens = tokenize(text)
tagged = nltk.pos_tag(tokens)
out =... | ebcd366bbf0c6b285151b6ad065b55a8b2997636 | 3,602,957 |
def temp_biasadj_HH2015(ref_temp, ref_elev, gcm_temp, dates_table_ref, dates_table):
"""
Huss and Hock (2015) temperature bias correction based on mean and interannual variability
Note: the mean over the reference period will only equal the mean of the gcm for the same time period when the GCM
time... | b24c1329a1c18e3928752117566705dfb51e8933 | 3,602,958 |
def _interpolate_missing_data(X, val=255):
"""Replaces all pixels whose value is val with a weighted
average of neighboring pixels.
"""
assert(X.ndim==2)
Xout = np.array(X, copy=True)
rows, cols = np.nonzero(Xout==val)
for ii in range(len(rows)):
row = rows[ii]; col = cols[ii]
... | 4cb00a9c6259006bac69c440460b903394ff0d8d | 3,602,959 |
import io
import os
import configparser
def load_rc(path):
# type: (Path) -> Dict[str, str]
"""This function loads the .hiss file represented as a dict"""
config = io.BytesIO()
config.write(b"[hiss]\n")
# attempt load of rc file
try:
with open(str(path)) as f:
config.write... | fd7e3a3b4bdf1a2f8f80cf73e5d4bca3c2b1c67d | 3,602,960 |
from ..baseobjs.resourceallocation import ResourceAllocation as _ResourceAllocation
def distribute_for_dot(a_shape, b_shape, comm):
"""
Prepares for one or muliple distributed dot products given the dimensions to be dotted.
The returned values should be passed as `loc_slices` to :func:`mpidot`.
Para... | 73bb88f0df2cec116650b7f0a9aa903427c20402 | 3,602,961 |
def resolve(oferta: list, demanda: (list, "matriz"), geral=False) -> "matriz":
"""Função que resolve tanto para um ou mais clientes passado."""
resultado_parcial = []
if not geral:
resultado_parcial.append(oferta_demanda(oferta, demanda))
else:
for i in range(len(demanda)):
... | 72098911a7a6e4a2a14fa589a8c065622ef9f6ad | 3,602,962 |
def home():
"""Home page - play with it if you must!"""
return redirect(url_for('dashboard')) | 2a7559a0c93c3af356fe84af04de6526950c54ec | 3,602,963 |
def compute_precision(Y_pred, Y_true):
"""
Compute precision = True positives / Total Number of Predicted Positives
= True positives / (True Positives + False Positives)
NOTE: This method applies to binary classification only!
Arguments:
Y_pred -- predictions, numpy array of... | f262e8964ea3835852fe85c8fa8b254bcf90139a | 3,602,964 |
def purchaseQuantity_perDate_month(data):
"""
DOCSTRING: Creates a 'Purchase Quantity per Day' column based on 'Purchase Date' and 'Purchase Quantity' columns, to assist future aggregations and plotting computations. Another new column 'Purchase Quantity per Month' gets created based on 'Month' and 'Purchase Qu... | 9a4605e801ca7921065580059ef0309d312c8543 | 3,602,965 |
def get(identifier):
"""Returns an optimizer function from a string. Returns its input if it
is callable (already a :class:`torch.optim.Optimizer` for example).
Args:
identifier (str or Callable): the optimizer identifier.
Returns:
:class:`torch.optim.Optimizer` or None
"""
if ... | cd42cbe3e8aefa1f2140eca76378002c4b1bb957 | 3,602,966 |
def deactivate_app():
"""
When multiple application instances are used, this method allows you to activate
the previously activated app by deactivating the current one.
(This method is meant for advanced users and should not be needed for most)
"""
global APP_STACK, APPS, APP
if len(APP_STA... | 50f0a4c7b3f5896a089dd9904a68bf293b975a5f | 3,602,967 |
import argparse
def get_args(args=None):
""" This is written as a default funtion to put at beginning of all Python
scripts which require command line arguments. This uses the argparse module
which must be declared in the main program to ensure that the object is able
to be used by the caller
--Ad... | 601d2917aefac02066270dd06262031131c65ba1 | 3,602,968 |
import argparse
def parser_selscan_norm_common(parser=argparse.ArgumentParser()):
"""
Build a parser to which arguments are added which are common to
several selscan functions.
"""
input_file_help_string = """A list of files delimited by whitespace for joint normalization.
Expected f... | a35fb2ccb4eedacbd480a2fd00d32f2ab5478aab | 3,602,969 |
import email
def parsemail(raw_message):
"""Parse message headers, then remove BCC header."""
message = email.parser.Parser().parsestr(raw_message)
# Detect encoding
detected = chardet.detect(bytearray(raw_message, "utf-8"))
encoding = detected["encoding"]
print(">>> encoding {}".format(encod... | 83609450cbd03657107646a0872fdbcff169f2bf | 3,602,970 |
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import RandomizedSearchCV
def randomsearch_crossval(training_set, training_labels):
"""[summary]
Args:
training_set ([type]): [description]
training_labels ([typ... | 621a51e46c3148b6c74efb41fe36e28e858a0413 | 3,602,971 |
def to_rdfbyid(request,model,id):
"""
take a model name + object id reference to an instance and apply any RDF serialisers defined for this
"""
try:
return _tordf(request,model,id,None)
except Exception as e:
return HttpResponse("Model not serialisable to RDF: %s" % e, status=5... | ac623cbb5b412e4083d3f1e92b1dedde9665a9a8 | 3,602,972 |
def HomePage ():
"""List all available api routes."""
return(
f"Available Routes are: <br/>"
f"<a href='/api/v1.0/precipitation'>Precipitation data</a><br/>"
f"<a href='/api/v1.0/stations'>List of all the stations</a><br/>"
f"<a href='/api/v1.0/tobs'>Last year's temperature for t... | 6edc00ae7b85e1d885a27c99d248f7f0551fdfd7 | 3,602,973 |
def win_sel(win_str, win_size):
"""
Function returns a window vector based on window name.
Note class can only use windows found in scipy.signal library.
"""
if (win_str == 'blackmanharris'):
win = sig.blackmanharris(win_size)
elif (win_str == 'blackman'):
win = sig.black... | bddf602b90d8a8b8afb7a9b41d7c0e7eff381428 | 3,602,974 |
def report_card_perf_overview(plan: pd.DataFrame):
"""Display performance overview diagrams.
Display a dropdown widget to choose between diagrams showing various
characteristics of the plan's convolution layers."""
layer_types = group_count(plan.df, 'type')
count_per_layer_type = partial(
p... | 74dde6220d7100b0dfd4f4d2bc82b6ed9dd78367 | 3,602,975 |
from typing import List
from typing import Dict
def get_beam_sections_map(model: BDF,
bar_beam_eids: List[int]) -> Dict[int, List[int]]:
"""gets the beams sorted by property_id that can be represented as 3d elements"""
bar_pid_to_eids = defaultdict(list)
int_offts = []
for ei... | fecee4714ff36783755ba2351fce548e6ff37db6 | 3,602,976 |
import inspect
def _instantiate_backend_from_name(name, options):
"""
Instantiate an event tracker backend from the full module path to
the backend class. Useful when setting backends from configuration
files.
"""
# Parse backend name
try:
parts = name.split('.')
module_n... | 7a17f038a5ae6549c749b55487f557d83d142135 | 3,602,977 |
def _start_offset_and_length(range_header):
"""
Returns a tuple of the start offset and the length.
If the range header doesn't exist, defaults to (0, -1). If parsing fails, returns (None, None).
"""
start_offset, length = 0, -1
if range_header is not None:
# Parse the header.
f... | ee93447068eb384c9e2f745b6621089c394939a5 | 3,602,978 |
import uuid
async def trigger_clone(request):
"""
Triggers a clone job on a sourcerepository.
---
description: Triggers a clone job on a sourcerepository.
tags:
- Builds
consumes:
- application/x-www-form-urlencoded
parameters:
- name: repository_id
in: p... | c241c7049ed79bb375665ffb3cdeeeddbc8a6b81 | 3,602,979 |
def requirements():
"""Returns the requirement list."""
with open('requirements.txt', 'r') as f:
return [line.strip() for line in f.readlines()] | e40af4819eac602c4af4845e2f59233dc3fa8a62 | 3,602,980 |
from pathlib import Path
def build_outpath(b:Build)->Path:
""" Return the output path of the realization being built. Output path is a
path to valid temporary folder where user may put various build artifacts.
Later this folder becomes a realization. """
paths=build_outpaths(b)
assert len(paths)==1, f"Build... | 3e6648bcad55dc8c55bd2f5b8cd93c09f7b3c7ed | 3,602,981 |
import dateutil
def parse(path, lang='ENG'):
"""
Get the isotherm and sample data from a BEL Japan .csv file.
Parameters
----------
path : str
Path to the file to be read.
Returns
-------
dataDF
"""
# set encoding
if lang == 'ENG':
encoding = 'ISO-8859-1'
... | 0d918c46b6257fc1b0ab8a44d1ffdacc1d3ed62b | 3,602,982 |
def _query_pkey(query, args):
"""Append 'query' and 'args' into a string for use as a primary key
to represent the query. No risk of SQL injection as memo_dict will
simply store memo_dict['malicious_query'] = None.
"""
return query + '.' + str(args) | d524697af247879f6aca5fa3918d80199b6148d5 | 3,602,983 |
from typing import Optional
import requests
def delete_package_holder(connection: Connection, id: str, project_id: Optional[str] = None,
prefer: str = 'respond-async',
error_msg: Optional[str] = None) -> requests.Response:
"""Delete the in-memory metadata packag... | 9ed5e71c7734bf720f27f6c39a7b7fe351025c54 | 3,602,984 |
def _gen_properties(**kwargs):
"""Creates a TaskProperties."""
args = {
u'cipd_input': _gen_cipd_input(),
u'command': [u'command1', u'arg1'],
u'dimensions': {
u'OS': [u'Windows-3.1.1'],
u'hostname': [u'localhost'],
u'pool': [u'default'],
},
u'env': {u'foo': u'bar', u'joe': u'2'... | f3c381902fa31cb95746326481a0a36de6930981 | 3,602,985 |
from typing import List
from typing import Tuple
def color_map_generate(
colors: List[Tuple[int, int, int]], add_black_if_not_exist: bool = False
) -> List[Tuple[int, Tuple[int, int, int]]]:
"""
컬러 리스트에서 [(id, 컬러)] 리스트를 생성합니다.
단, `(0, 0, 0)`이 있을 경우, 검은색의 id는 0으로 할당됩니다.
`add_black_if_not_exist` 옵션... | 38175b00d3f0bd5ba232cfcfd4b2e4bdb5ee7440 | 3,602,986 |
def upload_full_image(fileId):
"""
Upload a full-resolution image to Amazon S3.
"""
l.debug("Transferring full-resolution photo %s to Amazon S3.", fileId)
dest = str(sender) + '/full/' + fileId
src = 'full/' + fileId
saved = s3.save(src, dest, verbose=True)
if saved:
l.info("Full... | 0fbe20d2fe5158582787abd8c237201c6cd3c306 | 3,602,987 |
def get_innovation_message(ulog: ULog, topic: str = 'innovation') -> str:
"""
return the name of the innovation message (old: ekf2_innovations; new: estimator_innovations)
:param ulog:
:return: str
"""
if topic == 'innovation':
for elem in ulog.data_list:
if elem.name == "ek... | 03c01fb9352102216758c50654e8be626ee9d70f | 3,602,988 |
import os
import glob
def CACD(path: str) -> Dataset:
"""Dataloader of `Cross-Age Celebrity Dataset (CACD)`_ dataset.
.. _Cross-Age Celebrity Dataset (CACD): https://bcsiriuschen.github.io/CARC/
The file structure should be like::
<path>
CACD2000/
14_Aaron_Johnson_00... | d82c068e94517dc4fb032cf434dc7669b735672d | 3,602,989 |
def collate_question(query, template, slot):
"""
Collate a question based on template and slot
"""
T1 = "select one to refine your search"
T2 = "what (do you want | would you like) to know about (.+)?"
T3 = "(which | what) (.+) do you mean?"
T4 = "(what | which) (.+) are you looking for?"
... | 1d615aa6b9b923b0f4c5dff0f01b9e04e45c41f5 | 3,602,990 |
import re
def paragraph_newline(paragraphs):
"""Format newlines for paragraphing"""
# Put new paragraphs here; will be joined on ''
newlined_ps = ['']
first_footnote = True
line = re.compile('\(\d\d*\)')
poet_line = re.compile('/\n')
footnote_line = re.compile('\[\^\d\d*\]:')
for i,... | d43ef0de1f95945a747d44957bb86128e1281c5c | 3,602,991 |
def phasemap_cm(m=256):
"""
Colormap periodic/circular data (phase).
"""
theta = 2 * np.pi * np.arange(0, m) / m
circ = np.exp(1j * theta)
# Vertices of colour triangle.
vred, vgreen, vblue = -2, 1 - np.sqrt(3) * 1j, 1 + np.sqrt(3) * 1j
vredc = vred - circ
vgreenc = vgreen - circ... | 78d942fd0f64a4199fc73e5267e2df6fc2744f27 | 3,602,992 |
def convert_coord(coord, name='none', original_image=None, converted_image=None):
"""
:param coord: coord = [label_index, center_x, center_y, width, height]
:param name:
1) rot_90
2) rev_rot_90
3) rev_flip_1 (flip code = -1)
4) flip_1 (flip code = 1)
5) flip_0 (flip code = 0)
---- i... | 32e41fba349dfa32d4b2b8c28e62515ed21d2832 | 3,602,993 |
def build_model(vocab_size: int, batch_size: int, store: BaseConfig) -> tf.keras.Sequential:
"""
Utilizing tf.keras.Sequential model
"""
model = None
if store.dp:
model = build_dp_model(store, batch_size, vocab_size)
else:
model = build_default_model(store, batch_size, vocab_siz... | 0828280c92411aebbae0b00b7a9de43a750e40b4 | 3,602,994 |
import hashlib
def login():
"""
" user login based on [email] and [password]
"""
data = request.json
if data is None:
return response_error(MESSAGE.INVALID_PARAMETER, CODE.INVALID_PARAMETER)
email = data['email']
password = data['password']
if is_valid_email(email) == False... | a3d6de620dd6f28b43e270d3f088ee627f832eea | 3,602,995 |
def data_split_with_processing():
"""
:return: preprocessed data as X input variables y output variable
"""
data = pd.read_csv("C:\\Users\\jackc\\OneDrive\Desktop\\jjp068\\final_data.csv", index_col=[0])
X = data.iloc[:, :-1]
y = data['winner']
rus = RandomUnderSampler()
X, y = rus.fit_... | 07792ed77c8b7c095cd4f8e01bab66cbc795ac33 | 3,602,996 |
def invert_transforms(ts: transforms.Compose) -> transforms.Compose:
"""
Inverts Normalize and ToTensor transforms in a transformation sequence defined via torchvision.transforms.Compose.
:param ts: transforms.Compose object with the list of transforms to be inverted
:return: a torchvision.transforms.Co... | 30da1bd8c0896d523a86dd1567811623a3ca16a3 | 3,602,997 |
import os
def get_script_path(which_script):
"""
Gives executable path of requested script.
Args:
which_script (str): Script from `run_constants.py`.
Returns:
(str): Absolute path to requested script (Python file).
"""
return os.path.join(GRADIENTFUZZ_SCRIPTS_DIR, which_script) | 1821284abb70ff51ee1f49896363cd479b0f80a5 | 3,602,998 |
from sympy.concrete.summations import Sum
from sympy.calculus.util import AccumulationBounds
from re import S
def limit_seq(expr, n=None, trials=5):
"""Finds the limit of a sequence as index n tends to infinity.
Parameters
==========
expr : Expr
SymPy expression for the n-th term of the sequ... | 23f32c5617c66fd16a2e4548ff187a76c3143945 | 3,602,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.