content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def process_categorical_data(df):
"""Splits categories and converts categories to numbers
Args:
df: Pandas DataFrame
Return
categories: Pandas DataFrame
"""
# create a dataframe of the 36 individual category columns
categories = df['categories'].str.split(pat = ';', expand = T... | b329e44a486206c5a750341b611b77a8cd35e586 | 49,249 |
def next_vol_pred(model, data_generator, verbose=False):
"""
get the next batch, predict model output
returns (input_vol, y_true, y_pred, <prior>)
"""
# batch to input, output and prediction
sample = next(data_generator)
with timer.Timer('prediction', verbose):
pred = model.predict... | 6bdfe28a5f3498900e0fbebd18f5ec2abda1354d | 49,251 |
from typing import Iterable
from typing import Optional
from typing import List
def marshal_bson(
obj: object,
types: Iterable=BSON_TYPES,
fields: Optional[List[str]]=None,
) -> dict:
""" Recursively marshal a Python object to a BSON-compatible dict
that can be passed to PyMongo, Motor, etc...... | cebd51004799fc229159847e00bd9ce8146dc8f6 | 49,252 |
def api_get_all_sysrepo_modules():
"""
Returns all Sysrepo module names
"""
return json_resp(sr_model.get_modules_names()) | 75c37d52e18cce3f1e37145bd083b66f58d51eb2 | 49,253 |
def get_category_index_from_categories(categories, category):
"""
Gets the index of a category from the categories dictionary. If the category
doesn't exist, it creates a new entry for that category name and returns
the new index number.
"""
if category not in categories:
categories[cat... | 94ce8e2926c1de55383d5fd11e531d9c81792f9c | 49,254 |
def next_wangib(date):
"""Waning gibbous."""
return find_moon_phase(date, pi * 2.0, pi + (pi / 4.0)) | 3b7e05102ca409c76b13fe8eb2583be226eca4d9 | 49,255 |
def create_repas_noel_column(X):
"""Crée la variable pour le repas de Noël"""
X["repas_noel"] = X["repas_noel"] * X["effectif"]
return X | adfd6d07007d8e0f30903e16ed43f37dd55d92a2 | 49,256 |
def intervalLength(aa, wrapAt=360.):
"""Returns the length of an interval."""
if wrapAt is None:
return (aa[1] - aa[0])
else:
return (aa[1] - aa[0]) % wrapAt | dbceac2d1606d1bedf7c12b4114c17b70db78a86 | 49,257 |
import re
def is_valid_ordering(ordering):
"""checks if an ordering is valid
Args:
ordering (str): The ordering of a note
Returns:
bool: True if the ordering is valid
"""
if re.match(r'^[0-9_]+$', ordering):
return True
else:
return False | 306d618fb0af6793c474d0cf96d9a5182a15ed23 | 49,258 |
def translateDNA_6Frames(sequence) :
"""returns 6 translation of sequence. One for each reading frame"""
trans = (
translateDNA(sequence, 'f1'),
translateDNA(sequence, 'f2'),
translateDNA(sequence, 'f3'),
translateDNA(sequence, 'r1'),
translateDNA(sequence, 'r2'),
translateDNA(sequence, 'r3')... | 691b5828a394c15213b6bb2e6bf97735c7de8715 | 49,259 |
def load(f, where=None):
"""Read Amiga disk font file."""
# read & ignore header
_read_header(f)
hunk_id = _read_ulong(f)
if hunk_id != _HUNK_CODE:
raise FileFormatError('Not an Amiga font data file: no code hunk found (id %04x)' % hunk_id)
glyphs, props = _read_font_hunk(f)
return F... | 1fb0c3ed81ebb5d6f9f99666ef0cf28873cbcc52 | 49,261 |
import requests
def block(self, hash_or_number: str, **kwargs):
"""
Return the content of a requested block.
https://docs.blockfrost.io/#tag/Cardano-Blocks/paths/~1blocks~1{hash_or_number}/get
:param hash_or_number: Hash or number of the requested block.
:type hash_or_number: str
:param retu... | c6a79e379f52fa72bf22b911f69e9a530eb568e4 | 49,262 |
def sql_from_one_hot_encoder(
X: list, categories: list, drop_first: bool = False, column_naming: str = None
) -> list:
"""
---------------------------------------------------------------------------
Returns the SQL code needed to deploy a one-hot encoder model using its
attributes.
Parameters... | 8568f633de60785238307224c71794be99f51668 | 49,263 |
def load(trange=['2013-11-5', '2013-11-6'],
probe='15',
instrument='fgm',
datatype='1min',
suffix='',
downloadonly=False,
no_update=False,
time_clip=False):
"""
This function loads data from the GOES mission; this function is not meant
to be... | 106b469e871b5c2eca6f396ed7d943218e4acb65 | 49,264 |
def map_data_ea(*args):
"""
map_data_ea(insn, addr, opnum=-1) -> ea_t
map_data_ea(insn, op) -> ea_t
Map a data address.
@param insn: the current instruction (C++: const insn_t &)
@param addr: the referenced address to map (C++: ea_t)
@param opnum: operand number (C++: int)
"""
return _ida... | 9641d4c32bd014ab1835c94ad264fac4eb8c1d7d | 49,265 |
from operator import invert
def act(q, v):
"""
Returns the transformation (rotation) of a vector v by a unit-quaternion q.
"""
return compose(compose(q, np.insert(v, 0, 0)), invert(q))[1:] | dd29a2aaab7bfb1d5173695ccd8346d50b916d15 | 49,266 |
def untile_data3D(data,(lentZ,lentY,lentX),(lenZ,lenY,lenX)):
"""
Reorganize tiled sparky data into 3D data
Parameters:
* data 1D numpy array of tile data
* lentZ size of tile in Z (w1) dim
* lentY size of tile in Y (w2) dim
* lentX size of tile in X (w3) dim
* lenZ size o... | 61e3087a35148c025384b0f5b41175de5e404933 | 49,267 |
def evenly_combine(objects, select=None):
"""
Evenly combine multiple objects into a single object.
Parameters
-----------
values: list of objects
A list of objects to combine, the objects can be of any type as long as the selected object is either an iterable or a dict.
select: fun... | 4b9a57768a46a2ee1ba6570e2ed600ba334b3398 | 49,268 |
def list_flavors(as_list=False):
"""
Print `openstack` server size (flavor) options.
Set ``as_list`` to return a python list object.
Usage:
fab provider.list_flavors
Flavors:
+----+-------------------------+-----------+------+----------+-------+-------------+
| ID | ... | 9414d8db196c36f19412975b069328821693aea6 | 49,269 |
def shark_saved_queries():
"""
Retrieve saved queries for a user/account
GetParams:
account: an account
user: a user
Returns:
A json object conatining a list of saved queries
"""
error, user, account, _, handle = getRequestParameters(forceCluster=False)
if error is ... | 98f2c976133d870bd66fb7b969ae31988bee4b9b | 49,270 |
def is_remote_a_wordpress(base_url, error_page, downloader):
"""
This functions checks if remote host contains a WordPress installation.
:param base_url: Base url
:type base_url: basestring
:param error_page: error page content
:type error_page: basestring
:param downloader: download func... | d26c1a2f49a9522fe590ba315af90a17c592419f | 49,271 |
from re import X
def CNOT(control: int, target: int) -> QCircuit:
"""
Convenience CNOT initialization
Parameters
----------
control: int
control qubit
target: int
target qubit
Returns
-------
QCircuit object
"""
return X(target=target, control=control) | 1d259a19f1c0cdb5fce5319889fa65c85173c7b1 | 49,272 |
import platform
def get_python_version():
"""
A convenience function to get the python version used to run this
tutorial. This ensures that the conda environment is created with an
available version of python.
"""
versions = {'3': '3.8'}
return versions[platform.python_version_tuple()[0]] | f34439a174862cf5c4958baca217c0fb149c887a | 49,273 |
import json
def read_json(file_path: str) -> dict:
"""Reads json file from the given path.
Args:
file_path (str): Location of the file
Returns:
dict: Json content formatted as python dictionary in most cases
"""
with open(file_path, "r") as f:
return json.load(f) | 251c0ad8597ca2819727f95e7e52aa062444cba2 | 49,274 |
from typing import List
def join_stmts(
stmts: List[str], opts: PrintOptions, delimiter: str = ","
) -> str:
"""A convenience method for joining statements when the entire stmt list is already known"""
return JoinPrinter(delimiter=delimiter, stmt_list=stmts).to_string(opts) | e7fa6b460584c4b3d327031881c1b6e832330b3f | 49,275 |
def str_is_none(source):
"""
判断字符串不为空
"""
if source == '' or source == 'NULL' or source == 'None' or source is None:
return True
return False | e99d4bf0cae1e0a92cf51a133280a823fc354b31 | 49,276 |
def atttyp(att: str) -> str:
"""
Helper function to return attribute type as string
:param str: attribute type e.g. 'U002'
:return type of attribute as string e.g. 'U'
:rtype str
"""
return att[0:1] | ff6b4dd284c235db8a12591f78ce276bc73dd6ce | 49,277 |
def lin2freq(n_lin):
"""Compatibility hack to allow for linearly spaced cosine filters
with `make_erb_cos_filters_nx`; intended to generalize the
functionality of `make_lin_cos_filters`.
"""
return _identity(n_lin) | 6001e24f133f3bd0d2c2d1627516f93e3c09c4db | 49,278 |
def lower_confidence_bound(num_class_A: int, num_samples: int, alpha: float) -> float:
"""
Computes a lower bound on the probability of the event occuring in a Bernoulli distribution.
Parameters
----------
num_class_A: int
The number of times the event occured in the samples.
num_samples... | fddb252d21782f876fd804949e236915260a994a | 49,279 |
def get_weather_units(units):
"""returns a str representation of units of measurement that corresponds to given system of units.
if units is 'metric' return °C
if units is 'kelvin' return K
by default if units is 'imperial' return °F
Parameters
----------
:param str units: the system of un... | 6a12cb96e98f6ccf95927a79a5e9ffaa0a31d4ab | 49,280 |
def trca_feature(W: ndarray, X: ndarray,
n_components: int = 1) -> ndarray:
"""Return trca features.
Modified from https://github.com/mnakanishi/TRCA-SSVEP/blob/master/src/test_trca.m
Parameters
----------
W : ndarray
spatial filters from csp_kernel, shape (n_channels, n_filters)
... | a5e746dbe200c606a1856d8fc741cabc8b38f807 | 49,281 |
def get_data(flist):
"""
Extract data to pandas dataframes from all files in flist.
All coordinates should be same within all phi files in this directory.
Parameters
----------
flist - list of phi file names to read from CHARMM PBEQ output
Returns
-------
crds - X Y Z coordinates f... | da4d5a5064a10e16ae5aa780bef130a300360d2e | 49,282 |
def unescaper(msg):
""" unescape message
this function undoes any escape sequences in a received message
@param msg: the message to unescape
@return: the unescaped message
"""
out = []
escape = False
for x in msg:
if x == 0x5c:
escape = True
continue
... | e5e440269426784a7317860ac67133d61d7db7b0 | 49,283 |
def squarest_of(c, sort_key=None, reverse_on_key=False):
"""Returns the :term:`squarest` member of `c`, a collection of numbers.
If there are multiple perfect squares,
`sort_key` is used to pick a single one.
Parameters
----------
c : iterable of int
A collection of integers.
so... | 8f5c38f415b41de763973398ffa23354af22e563 | 49,284 |
def compute_curvature(point1: geom.Point, point2: geom.Point, point3: geom.Point) -> float:
"""
Estimate signed curvature along the three points.
:param point1: First point of a circle.
:param point2: Second point of a circle.
:param point3: Third point of a circle.
:return signed curvature of t... | 49fa7865fb57399201b79badcccbe30e8f440d06 | 49,285 |
from typing import Callable
from typing import Iterable
from typing import Dict
from typing import Any
def groupby_many_reduce(key: Callable, reducer: Callable, seq: Iterable):
"""Group a collection by a key function, when the value is given by a reducer function.
Parameters:
key (Callable): Key function... | 7d08325206bfb78cfe421244af6d91b4cd3ceb56 | 49,286 |
def compare_modules(file_, imports):
"""Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
tuple: The modules not imported in the project, but do e... | 3085d16b0b92153711868aed615611a481ed6fa0 | 49,287 |
def categorize(state):
""" Given a state, categorize it as winning(good)=0/ losing(bad)=1/ tie=2 or incomplete game=3 state"""
if (state[0][0] == 2 and state[0][1] == 2 and state[0][2] == 2) or (
state[1][0] == 2 and state[1][1] == 2 and state[1][2] == 2) or (
state[2][0] == 2 and state[2][1] == 2 and state[2][2]... | 20e8931b8204ad360afcb9521c3a375c07a5aecd | 49,288 |
def _FetchAllFiles(input_api, white_list, black_list):
"""Hack to fetch all files."""
# We cannot use AffectedFiles here because we want to test every python
# file on each single python change. It's because a change in a python file
# can break another unmodified file.
# Use code similar to InputApi.FilterSo... | 99f3a88be278af877ab4dec2a164ce4093a16e82 | 49,290 |
def __split2contiguous(levels):
""" Function __split2contiguous(levels)
takes list of split intervals and make it contiguous if possible
"""
tmplevs = []
for il in range(len(levels)):
lv = levels[il]
if not (isinstance(lv, list) or isinstance(lv, tuple)):
raise VCSUtilsEr... | 590f62a295fda41a2849f6e14719165f4f54ad2f | 49,291 |
def _programs_with_attribute(attr):
""" get a list of modules with a given attribute
"""
progs = []
for prog in PROGRAM_MODULE_NAMES.keys():
module = _import_module(prog)
if hasattr(module, attr):
progs.append(prog)
return progs | 24347e2d07876108f0a31821e16840f007149708 | 49,293 |
import base64
def recursive_decode(s:str, level=9, method=[]) -> str:
""" Recursive decode `s`(encoded by `recursive_encode`) using base64,
`level` is depth of recursive, the max value is 32 """
assert 0 < level <= 32
if not isinstance(s, (bytearray, bytes)):
s = bytes(s, 'utf-8')
if m... | 49614a7c13126eb4c620a4527302809de6c88393 | 49,294 |
def get_envelope(t_note_length, t_attack=0.010, t_release=0.3, sr=16000):
"""Create an attack sustain release amplitude envelope."""
t_note_length = min(t_note_length, 3.0)
i_attack = int(sr * t_attack)
i_sustain = int(sr * t_note_length)
i_release = int(sr * t_release)
i_tot = i_sustain + i_release # atta... | 5547855641c49d733dddd19c2a8065ffbb52d31e | 49,296 |
def create_update(table, columns: dict, filters: dict):
"""
:param table:
:param columns: dict:
:param filters: dict:
"""
table = Table(table)
query = Query.update(table)
for k, v in columns.items():
query = query.set(k, v)
query = set_query_filters(filters, query, table)
... | 7e95532c05c07d436c851899ed6545df5bd00da0 | 49,297 |
def new_recipe(request):
"""Создание рецепта '/new' """
user = User.objects.get(username=request.user)
form = RecipeForm(request.POST or None, files=request.FILES or None)
ingredients = get_ingredients(request)
if not form.is_valid():
return render(
request,
'new_re... | ee08c4357932cdc2ea0e731a56a5c0597a8c6c6d | 49,298 |
import requests
def get_nameservers():
"""Returns the available nameservers."""
return requests.get(
'https://api.cloudns.net/dns/available-name-servers.json',
params=get_auth_params()) | 654233d6ef13f518a63c1dcf60ff8c8026872593 | 49,299 |
import json
def load_data(raw=None):
""" load data to development workspaces
Parameters
--------------
raw: (bool) if True, function returns cleaned dataset.
return (df) data frame of data and its labels
"""
raw_data = []
with open('./data/cyber_data.json') as f:
for l... | 7ff0051cd7f6f90bb00b24cc2025e0ed88b629ed | 49,301 |
def nearer(lons, lats, lon, lat, tolerance=np.inf, max_sites=None):
"""Nearer stations in (lons, lats) to site (lon, lat).
Args:
lons (array): Longitudes of stations to search.
lats (array): Latitudes of stations to search.
lon (float): Longitude of of station to locate from lons.
... | 5482e59d835094fd31d8eff82d432a93a341af77 | 49,302 |
def draw_perm_reps_diff_mean(x, y, size=1):
"""Generate array of permuation replicates."""
out = np.empty(size)
for i in range(size):
x_perm, y_perm = draw_perm_sample(x, y)
out[i] = np.mean(x_perm) - np.mean(y_perm)
return out | 31bc21ef017e636106a67ad3e32972d7b29abeba | 49,303 |
import torch
def pois_llik(y, eta):
"""Return ln p(y | eta) assuming y ~ Poisson(exp(eta))
This implementation supports broadcasting eta (i.e., sharing parameters
across observations).
:param y: tensor
:param eta: tensor
:returns llik: tensor (y.shape)
"""
return y * eta - safe_exp(eta) - torch.lg... | bd933181b3687a5fc6d4b6d851f34d481739ff3c | 49,304 |
import zipfile
def get_docx_text(path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(path)
xml_content = document.read('word/document.xml')
document.close()
tree = XML(xml_content)
paragraphs = []
for paragraph in tree.ge... | ff0b4d315197573ab6cdfdb22b4b8d62226ef337 | 49,305 |
def config_unconfig_interface_ip_addresses(dut, if_data_list=[], config='add',cli_type='',ip_type=''):
"""
Configure IP addresses on multiple interfaces
Author: Naveena Suvarna (naveen.suvarna@broadcom.com)
:param dut:
:param if_data_list:
:param config:
:return:
"""
if config != 'a... | e73e24cccb3a0458e297daa66a7da0c88546c5b7 | 49,306 |
import random
def compare_with_ties(a, b):
"""
Comparison function for two items with the condition that if they are equal,
one of the two values is randomly selected to be greater than the other.
Arguments
a - the first item to compare
b - the second item to compare
Returns:
... | 9acfacc40d8ca0bc0ec2a4a226e82a5d55bfe440 | 49,307 |
def store(src, rel, dst):
"""
Returns an SQL statement to store an edge into
the SQL backing store.
:param src: The source node.
:param rel: The relation.
:param dst: The destination node.
"""
smt = 'INSERT INTO %s (src, dst) VALUES (?, ?)'
return smt % rel, (src, dst) | 1fcb76ff722fbf0a43c125a4ff42405b12d54ec6 | 49,308 |
def make_node_dict(node_dict, xml_dict, hch_id, hch_tag, parent, classification_orpha):
"""
Recursively parse xml_dict to output a collection of Disorder with all their children
:param node_dict: Dictionary of Disorders i.e.
{2846: {
"Preferred term": "Congenital pericardium anomaly",
"... | 5f0b254122a40240829d016b3cf76f89053a5d00 | 49,309 |
def fateman_poly_F_1(n):
"""Fateman's GCD benchmark: trivial GCD """
Y = [Symbol('y_' + str(i)) for i in range(n + 1)]
y_0, y_1 = Y[0], Y[1]
u = y_0 + Add(*[y for y in Y[1:]])
v = y_0**2 + Add(*[y**2 for y in Y[1:]])
F = ((u + 1)*(u + 2)).as_poly(*Y)
G = ((v + 1)*(-3*y_1*y_0**2 + y_1**2 -... | 38413804cc477d9fb3b502b394b78933381e53c0 | 49,310 |
def markdown(value):
""" Converts the specified markdown string to HTML
Args:
value (str): Markdown string
Returns:
string: HTML equivalent
"""
return markdown2.markdown(value) | 225ae6551a717c4844bc33fb6b85f10efed6e67e | 49,311 |
def irpf(base, porcentaje=12.5,prorrateado=False):
"""
irpf (sueldo,porcentaje, prorrateado=boolean)
"""
if prorrateado:
cantidad_prorateada = base/6
if type(base)==float and type(porcentaje)==float:
return (base/100) * porcentaje
else:
return None | cbc3fbb115f9896a5e852126b242a22c49bba66b | 49,312 |
import string
def generatepin(length=4):
"""Generates a PIN number of the specified length."""
return generatepass(length, string.digits, exclude_similar_chars=False) | 94d2d4a5b39bf36991f8daac9d29182f63921004 | 49,314 |
def read_p2g(path):
"""Read graph in p2g format from path.
Returns an MultiDiGraph.
If you want a DiGraph (with no self loops allowed and no edge data)
use D=networkx.DiGraph(read_p2g(path))
"""
fh=_get_fh(path,mode='r')
G=parse_p2g(fh)
return G | 76fc8b348f67ac0b5bb52859001335bac279ff17 | 49,315 |
def get_by_index(items, index):
"""
Return an element of a list based on its index.
Usage in template::
{% load list_to_columns %}
{{ items|get_by_index:0 }}
Args:
``items`` (list): A list of elements.
``index`` (int): The position of the element to be returned.
... | a355560ab741ef821c62e9b11e77476d3ab7248c | 49,316 |
from datetime import datetime
def admin_ide_stop_id(id: str):
"""
Stop a specific IDE
:return:
"""
# Search for the theia session
session = TheiaSession.query.filter(
TheiaSession.id == id,
TheiaSession.course_id == course_context.id,
).first()
# Verify it exists
... | c66585753bbac987b5cde340df4d6b7fb06c9cb2 | 49,317 |
import uuid
def lci_instance_id():
"""Id for the low-cost instance."""
return f"lci-instance-{uuid.uuid4().hex[:10]}" | 2c559d27879b418f86e12f00cff7526ce964258a | 49,318 |
def command_exists(command):
""" Check if the given command was registered. In another words if it
exists.
"""
for category, commands in command_categories.items():
for existing_command in commands:
if existing_command.match(command):
return True
return False | a9ad8c23fb354da395b7fe865e6bda7a3ed68148 | 49,320 |
from typing import Dict
def users_search(client: Client, args: Dict) -> CommandResults:
"""Search users
Args:
client: Client object with request.
args: Usually demisto.args()
Returns:
Outputs.
"""
email = str(args.get('email', ''))
query = str(args.get('query', ''))
... | 0e48fc1b8367146d05fcaa7ec15b9f70445b07be | 49,321 |
def list_files():
"""
List some of the files on the Drive.
:returns: A dictionary containing the list of file-details.
"""
results = file_service.list(
pageSize=10, fields="files(id, name)").execute()
return results | 914649ec9099ea10b0607cb124ff5d6b061222af | 49,322 |
def onwindowcreate(window_name, fn_name, *args):
"""
On window create, call the function with given arguments
@param window_name: Window name to look for, either full name,
LDTP's name convention, or a Unix glob.
@type window_name: string
@param fn_name: Callback function
@type fn_name: fun... | d2d4e21f5f119be972a34acb3717eb64c01357a1 | 49,323 |
def expand(entity_id):
"""Returns a list of diagrams for the role
---
get:
summary: Expand an entity to get its adjacent entities
description: >-
Get the property-wise list of entities adjacent to the entity
with id `entity_id`.
parameters:
- in: path
name: en... | 46605a8f4c46cf79413881d3ebfb6459497f12bf | 49,324 |
def get_model_preds(CP):
"""Reads in or generates model predictions.
Parameters
----------
CP : dict
Containins directory locations for loading data and storing
predictions.
Returns
-------
craters : h5py
Model predictions.
"""
n_imgs, dtype = CP['n_imgs'], ... | b789ff9a5c7f40cc6be875b89eec5b73228db934 | 49,326 |
def detach():
"""
Detaches a specified device
"""
scsi_id = request.form.get("scsi_id")
unit = request.form.get("unit")
process = ractl.detach_by_id(scsi_id, unit)
if process["status"]:
flash(_("Detached SCSI ID %(id_number)s LUN %(unit_number)s",
id_number=scsi_id, unit_... | 916db39fd210510ec27d63e61eb5244c5d288731 | 49,327 |
def weld_range(start, stop, step):
"""Create a vector for the range parameters above.
Parameters
----------
start : int
stop : int or WeldObject
Could be the lazily computed length of a WeldObject vec.
step : int
Returns
-------
WeldObject
Representation of this com... | 196ef891804bd9104e9e2e4582f3de5fe19751e7 | 49,328 |
def _capture(which='stdout', printonly=None):
"""private method, should not be called directly
(cf. capture_stdout() and capture_stderr())
"""
assert which in ('stdout', 'stderr'
), "Can only capture stdout or stderr, not %s" % which
if which == 'stdout':
fd = 1
else:
fd ... | 534ad7f1cf0f703936921dd03325096000f65a33 | 49,329 |
def flatten(d):
"""Return a dict as a list of lists.
>>> flatten({"a": "b"})
[['a', 'b']]
>>> flatten({"a": [1, 2, 3]})
[['a', [1, 2, 3]]]
>>> flatten({"a": {"b": "c"}})
[['a', 'b', 'c']]
>>> flatten({"a": {"b": {"c": "e"}}})
[['a', 'b', 'c', 'e']]
>>> flatten({"a": {"b": "c", "... | 9d7f83e8f57c2df9c33b69e46536553092ae1ec1 | 49,330 |
def plot_pair(img, adv, model=None, suptitle=None):
"""
Visualize clean image, purturbation, and adversarial example
# Arguments
img: np.array
The clean image with shape (w, h, 3)
adv: np.array
The adversarial example with shape (w, h, 3)
model: keras model
... | 5a0a23230e9b1696d7ec8ba218ae4b0ad753ed91 | 49,331 |
import _io
def plot2opencv(fig):
"""Convert a pyplot instance to image"""
buf = _io.BytesIO()
fig.savefig(buf, format='png', bbox_inches='tight', pad_inches=0)
buf.seek(0)
rawbuf = np.frombuffer(buf.getvalue(), dtype='uint8')
im = cv2.imdecode(rawbuf, cv2.IMREAD_COLOR)
buf.close()
ret... | d1453c6a6f684386730e29d8572b9d3da32a8ce7 | 49,332 |
def write_xls(sheet_name, head, data_list):
"""write listed data into excel
"""
try:
wb = openpyxl.Workbook()
ws = wb.get_active_sheet()
except Exception as e:
logger.error(e)
return None
ws.title = sheet_name
row_num = 0
# write table head
for col_num... | 5046cf12f2175229c871016012d2571f14d47c87 | 49,333 |
def missing_local_with_stage(stage: str, ssm_env: dict, local_env:dict, filter_env: list = []):
"""Returns missing values between ssm stage and local env"""
ssm_env = [x for x in ssm_env.keys() if x not in filter_env]
local_env = [x for x in local_env.keys() if x not in filter_env]
in_ssm = [x for x in ... | b69571464257b02aba1f5e7bdd3a8901c7842f70 | 49,335 |
def _slot_history(tracker_dump):
# type: (Dict[Text, Any]) -> List[Text]
"""Create an array of slot representations to be displayed."""
slot_strs = []
for k, s in tracker_dump.get("slots").items():
colored_value = utils.wrap_with_color(str(s),
utils... | 00a9157ef364217faa54cb7faa4c8f6b54cbbb2b | 49,336 |
from operator import concat
def HTN_classical_partition_function_from_edges(
edges,
beta,
j=1.0,
h=0.0,
site_ind_id="s{}",
site_tag_id="I{}",
bond_tag_id="B{},{}",
):
"""Build a hyper tensor network representation of a classical ising model
partition function by specifying graph ed... | 70539041daa68c4e70dcbf5d15c8f959885ad208 | 49,337 |
def country(cert):
"""
Attempt to get the country from a given certificate.
:param cert:
:return:
"""
try:
return cert.subject.get_attributes_for_oid(
x509.OID_COUNTRY_NAME
)[0].value.strip()
except Exception as e:
sentry.captureException()
current... | e6ba28a61c4f561fb596fccd1cc571f51ad6d320 | 49,338 |
def detect_fns_free_variables(source_code, imports_and_functions="",
step_parameters=None):
"""Return the function's free variables.
Free variable: _If a variable is used in a code block but not defined
there, it is a free variable._
An Example:
```
x = 5
def... | db5df686b118f70899e66c44ef90ebb8595d011e | 49,339 |
def assign(grid: Grid, s: Square, d: Digit) -> MaybeGrid:
"""Eliminate all the other values (except d) from grid[s] and propagate.
if a contradiction is detected, return None
"""
others = grid[s].replace(d, "")
for d in others:
if eliminate(grid, s, d) is None:
return None
r... | c82b31fb25ae9e018090198feee1c42fa62e3d67 | 49,340 |
import shlex
def split_types(query):
""" Split a string of multiple :py:class:`MeasurementType` keys (e.g., one
generated by using addition or subtraction of :py:class:`MeasurementType`
objects and/or strings).
:param query: A :py:class:`MeasurementType` or a string containing
... | 3777a879503aef0925ef239e32731c6fdb93543d | 49,341 |
import re
def get_outcome(output: str, test: Test, sig: int):
"""
Parses out the number of passed and failed tests from cb-test output
"""
test_outcome = TestOutcome()
test_outcome.total = 1
test_outcome.passed = 0
test_outcome.name = test.name
test_outcome.is_pov = test.is_pov
... | fa666ddda9769d65b2c8d6a6b0a437240356844e | 49,342 |
def search():
"""
Return search results for a given query
"""
query = request.args.get("query", "")
if query == "":
return redirect(url_for("main.browse"))
page = int(request.args.get("page", 1))
format = request.args.get("format", "")
scan_ids = request.args.get("includeScan... | 8fff27cd059612f0a7dd0b66a2d27efc27f5090b | 49,345 |
def bubble_sort(array):
"""
Sorts a list using bubble sort algorithm
Input: A list of integers
Output: A list containing the same integers as the input, but sorted in
ascending order
Sorts by iterating through a list swapping values that are in the wrong order.
Stops when it is imp... | 5af7e90dd423ac57bd6aa3b27e139d35c814a45f | 49,346 |
def issue_dir(issue_id):
"""
input: 123
output: /path/to/repo/gl/i/123
"""
return DIR / "i" / str(issue_id) | 40f9c063fb1e69f835bfa5615875427de4b7d572 | 49,347 |
from typing import Dict
from typing import Any
def _read_info(info_filename: str) -> Dict[str, Any]:
"""read info into dictionary"""
with open(info_filename, "r") as info_file:
lines = info_file.readlines()
info = {}
for line in lines:
key, val = line.strip().split("\t")
... | 884a0a309380e1b077c5d1830ca3b6803804644b | 49,348 |
def signal_derivs(zc, params, dparams):
"""
Calculate derivatives of signal covariance w.r.t. cosmological parameters.
"""
derivs = []
# Loop over parameters that should be included in Fisher matrix
pnames = dparams.keys()
pnames.sort()
for pname in pnames:
print " Derivati... | 18919688ae1acdda84b0dda004634a32a0533b11 | 49,349 |
def view_coach(request, coach_id):
""" A view to show a particular coaches page and their comments"""
coach = get_object_or_404(Coach, pk=coach_id)
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
co... | bbacfd2a0ac978bc0ca4fdda49f08e6a0d8ac3a3 | 49,350 |
def replace(filename, stext, rtext):
""" replace string stext with rtext in file filename """
status = True
try:
_input = open(filename, "r")
except Exception, e:
tolog("!!WARNING!!4000!! Open failed with %s" % e)
status = False
else:
try:
output = open(f... | 43c7441653ed84e935c99101c8ca0d2cbba8dff4 | 49,351 |
def get_unlucky_days():
"""Returns the days that had article request fails percentage higher
than 1%."""
query = """SELECT to_char(date, 'FMMonth FMDD, YYYY') as date,
error
FROM request_errors_per_dar
WHERE error > 0.01;"""
return format_query(
'... | beb24244a715656a38c6e7e0da435e4b786f9160 | 49,353 |
def GetGradleSnippet(args):
"""Forms a gradle snippet to add to the build.gradle file.
Args:
args: an argparse namespace. All the arguments that were provided to this
command invocation.
Returns:
A gradle snippet.
"""
repo_path = _GetRepoPath(args)
gradle_template = """\
Please insert follo... | 4ab4444c809040207c33eb7fabc9ccf13306660b | 49,354 |
from typing import Dict
def run(config) -> Dict[str, dict]:
"""
Lowpolyfy one or more images using default or user-provided config.
Returns (Dict[str, dict]): A mapping from file paths to the config used to generate them.
"""
if config.run.mode == "single":
results = single(config)
el... | ec2bbae3803c111b63438a3a4ada861678e0876b | 49,355 |
import importlib
def load_connector(connector_info):
"""instantiate the connector class"""
connector = importlib.import_module(
f"bookwyrm.connectors.{connector_info.connector_file}"
)
return connector.Connector(connector_info.identifier) | e105c74d7f497132df439ff9e561d5492adb4c73 | 49,356 |
def axes_contains(ax, obj_list):
"""
Check that a matplotlib.Axes instance contains certain elements.
Parameters
----------
ax : matplotlib.Axes
Axes instance.
obj_list : list of tuples
List of tuples, one for each type of object to look for. The tuple
should be of the ... | 09da4420a5552902cb0b2da2a38c4e61af092b2f | 49,357 |
import requests
def get_globally_rescoped_token(globaltoken, defaultid):
"""Summary - Get a global project scoped auth token
Returns:
STRING: Globally Scoped Object
Args:
globaltoken (string): valid global token
defaultid (string): default projct id
"""
identityURL = 'htt... | d1e85b80862ab7e4bbe4c735fe5b6632eca64dcb | 49,358 |
def compile_cons_check(context):
"""Throw a runtime error if the value in rax is not a cons cell or nil.
Does not modify rax.
See also `compile_list_check`.
"""
error_block = compile_die(b"not a cons cell :(\n", context)
result = []
# mov rdi, rax
result.extend([0x48, 0x89, 0xC7])
... | 6a03fb89b60c15f256ac20ab27eac2412079ca4e | 49,360 |
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
http://..... | 58897a8c5fd5f694579d8a35fb15a993dd40b87b | 49,361 |
import functools
import logging
import traceback
def signin_required(include_gitlab_login=False):
"""Check if the user is signed in or the access token is valid and return the user."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
try:
u... | 0884eb5f7e50111236c14b362f2307c794236518 | 49,362 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.