content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def check_in_image(paste_image_location, paste_image_size, canvas_image_size):
"""Checks whether the location for the pasted image is within the canvas.
Args:
paste_image_location: a namedtuple of utils.XY, with 'x' and 'y' coordinates
of
the center of the image we want to paste.
paste_image_si... | 173ff3ca7961bff34237512990fb2f103dd7ddc9 | 9,700 |
import functools
def withSEVCHK(fcn):
"""decorator to raise a ChannelAccessException if the wrapped
ca function does not return status = dbr.ECA_NORMAL. This
handles the common case of running :func:`PySEVCHK` for a
function whose return value is from a corresponding libca function
and whose retu... | 938468e504cb37a154c6165cc052f59995f806bc | 9,701 |
from datetime import datetime
def convert_ts_to_date(ts):
"""
Converts a timestamp to a date object
"""
# TODO: is this function necessary?
return datetime.fromtimestamp(ts) | f081ef4999959b0effb0708a303932dc09a414ad | 9,702 |
from . import ism, gradient, referencebased
def available_methods():
"""Get all available importance scores
"""
int_modules = [ism, gradient, referencebased]
available_methods = {}
for m in int_modules:
available_methods = merge_dicts(available_methods, m.METHODS)
return available_met... | 3f452affeebafdae1571cfb54d6af9235871f798 | 9,703 |
import os
def templates():
"""
.. versionadded:: 2015.5.0
List the available LXC template scripts installed on the minion
CLI Examples:
.. code-block:: bash
salt myminion lxc.templates
"""
try:
template_scripts = os.listdir("/usr/share/lxc/templates")
except OSError... | 4f79b1baaf2e6434a221bd3ea449d71ce2fad8b5 | 9,704 |
def is_sketch_list_empty():
"""Check to see if any sketches"""
return len(_CVB_SKETCH_LIST) == 0 | fdaa5b5a251bde8a8b4d2e5a0c8a1d4b4b3d5f7d | 9,705 |
def pb22():
"""
Problem 22 : Names scores.
We first open the file, suppress the useless ", put everything into lowercase, and split to get a list.
We use merge sort to sort the list by alphabetical order (see utils.merge_sort), and then :
- for each word in the list
- for each character in t... | f8c08fc3c42e0889514d84e2193e10a8be1f8595 | 9,706 |
def resize(im, target_size, max_size, stride=0, interpolation = cv2.INTER_LINEAR):
"""
only resize input image to target size and return scale
:param im: BGR image input by opencv
:param target_size: one dimensional size (the short side)
:param max_size: one dimensional max size (the long side)
... | ba2238bfaeb3c3c08ad4c1b9371e87c5e0653edc | 9,707 |
from typing import List
from typing import Tuple
import json
def _add_qc(
samples: List[Sample], namespace: str, overwrite_multiqc: bool
) -> Tuple[str, str]:
"""
Populates s.qc_values for each Sample object. Returns paths to MultiQC
html and json files.
"""
multiqc_html_path = join(
f... | 8c93cd7c08c3e392b9f79956189295cb5c486048 | 9,708 |
def oscillAnglesOfHKLs(hkls, chi, rMat_c, bMat, wavelength,
vInv=None, beamVec=bVec_ref, etaVec=eta_ref):
"""
Takes a list of unit reciprocal lattice vectors in crystal frame to the
specified detector-relative frame, subject to the conditions:
1) the reciprocal lattice vector mus... | 37d17027fcaa15613188f0be61b0df4c5965a19c | 9,709 |
def srfFaultSurfaceExtract(SRFfile):
"""
Generate fault surface from SRF file convention
Following the Graves' SRF convention used in BBP and CyberShake
"""
lines = open( SRFfile, 'r' ).readlines()
Nseg = int(lines[1].strip().split()[1])
# loop over segments to get (Nrow,Ncol) of ... | 6e1197b76b88f92e0d61bee87d57910660192346 | 9,710 |
def _to_response(
uploaded_protocol: UploadedProtocol,
) -> route_models.ProtocolResponseAttributes:
"""Create ProtocolResponse from an UploadedProtocol"""
meta = uploaded_protocol.data
analysis_result = uploaded_protocol.data.analysis_result
return route_models.ProtocolResponseAttributes(
i... | 1594a90ce1351ad33961819201409167c0f462a7 | 9,711 |
def has_valid_chars(token: str) -> bool:
"""
decides whether this token consists of a reasonable character mix.
:param token: the token to inspect
:return: True, iff the character mix is considered "reasonable"
"""
hits = 0 # everything that is not alphanum or '-' or '.'
limit = int(l... | b9b65f1bfd3529275847f1d6e227d57dfebea8a8 | 9,712 |
import logging
def sqlalchemy_engine(args, url):
"""engine constructor"""
environ['PATH'] = args.ora_path # we have to point to oracle client directory
url = f'oracle://{args.user}:{pswd(args.host, args.user)}@{args.host}/{args.sid}'
logging.info(url)
return create_engine(url) | 06a670eccf96997c23a9eb5125925db5be33e978 | 9,713 |
import os
import multiprocessing
def cpu_count():
""" Returns the default number of slave processes to be spawned.
"""
num = os.getenv("OMP_NUM_THREADS")
if num is None:
num = os.getenv("PBS_NUM_PPN")
try:
return int(num)
except:
return multiprocessing.cpu_count() | 57dce269531835175e93f6b974be58ae08e2cbd8 | 9,714 |
def shortcut_layer(name: str, shortcut, inputs):
"""
Creates the typical residual block architecture. Residual blocks are useful
for training very deep convolutional neural networks because they act as
gradient 'highways' that enable the gradient to flow back into the first few
initial convolution... | b680df8c6415d256ee98d292d491fc30a6a4bb4a | 9,715 |
def event_message(iden, event):
"""Return an event message."""
return {"id": iden, "type": "event", "event": event} | bfc3fca17a9ad8d3767853c82c5453328d4c07e3 | 9,716 |
def match(command):
"""Match function copied from cd_mkdir.py"""
return (
command.script.startswith('cd ') and any((
'no such file or directory' in command.output.lower(),
'cd: can\'t cd to' in command.output.lower(),
'does not exist' in command.output.lower()
... | e49540995f26b40b4c52879814fe905f35b1c8fd | 9,717 |
def db_remove_game(game: str, channel: str) -> bool:
"""Removes a game from the database, for a specific channel
"""
if db_check_game_exists(game, channel):
cursor.execute(
"DELETE FROM deathcount "
"WHERE channel=(?) AND game=(?)",
(channel.lower(), game.lower(... | 536a48201274767f834443d7b1c279c2c5c15e14 | 9,718 |
def get_unique_id():
"""Return an ID that will be unique over the current segmentation
:return: unique_id
:rtype: int
"""
global UNIQUE_ID
UNIQUE_ID = UNIQUE_ID + 1
return UNIQUE_ID | e55be0d1619f3435d0b6b76a3da2661c1349213b | 9,719 |
def logout_route():
"""logout route"""
logout_user()
return redirect(url_for('app.index_route')) | 097644c147003be394a886c4b796b57e8cc775c7 | 9,720 |
import argparse
def setup_command_line_parser():
"""
Sets up command line argument parser. Additional arguments could be added
easily. For example if the version needed to be passed in with -v you
could add it as a positional argument like so:
parser.add_argument("-v", "--version",... | 6625daeec98cc06b319aab52a5757195b89c88eb | 9,721 |
def get_repo_name(
name: str, in_mode: str, include_host_name: bool = False
) -> str:
"""
Return the full/short name of a Git repo based on the other name.
:param in_mode: the values `full_name` or `short_name` determine how to interpret
`name`
"""
repo_map = get_complete_repo_map(in_mo... | 3eebb75487f5eb5c8c8eb7a5a7a46c92dcf4c304 | 9,722 |
def binary_search_hi(a,d,lo,hi):
"""
Created for leetcode prob 34
"""
if d!=a[lo]:
raise Exception("d should be a[lo]")
while hi>lo:
mid=(lo+hi)//2+1
if a[mid]==d:
lo=mid
else:
hi=mid-1
if a[hi]==d:
return hi
else:
retur... | 4ef9ad63fb83bbb1cb1a9f7d4a3ea4a08ad40d8d | 9,723 |
def check_subscription(func):
"""Checks if the user signed up for a paid subscription """
@wraps(func)
def wrapper(*args, **kwargs):
if current_user.is_authenticated():
subscription = current_user.subscription
if not subscription.active and subscription.plan.name != 'Free':
... | 853b16cc4a05742f2bd17fd159ac570f92fdb16c | 9,724 |
def spikesbetter(P):
"""
same as the custom cython function _dice6, a python implementation for easy use on other computers
does spin selection procedure based on given array of probabilities
--------------------------------------------------------------------
Inputs:
P: probability of silence a... | 75fcff7e53ccbd392361faf46f2c4f171f85e724 | 9,725 |
def t3x1_y(y):
"""
Translation in y.
"""
return t3x1(0.0, y, 0.0) | 26d99e8a5b5ccd676d5488a8e8aafcd76d5272a5 | 9,726 |
def perm_data_time(x, indices):
"""
Permute data matrix, i.e. exchange node ids,
so that binary unions form the clustering tree.
"""
if indices is None:
return x
N, M, Q = x.shape
Mnew = len(indices)
assert Mnew >= M
xnew = np.empty((N, Mnew, Q))
for i,j in enumerate(ind... | ed1201d34cb35debe7653601d0048f099e32db16 | 9,727 |
def check_chromium() -> bool:
"""Check if chromium is placed at correct path."""
return chromium_executable().exists() | 21b60e3070ba707ae46e53f68f31ef8e719aed76 | 9,728 |
from typing import Dict
from typing import Optional
def draw_lane(image, extracted_lane: Dict = {}, output_path: Optional[str] = None):
"""render extracted lane"""
# TODO: refactor separate concern moving out the saving to a file
lane_annotation_image = image.copy()
if "right" in extracted_lane:
... | dd6891fc6c0fc0509084c9b2e063fb46c589d039 | 9,729 |
def plot_edges(lattice : Lattice,
labels : np.ndarray = 0,
color_scheme : np.ndarray = ['k','r','b'],
subset : np.ndarray = slice(None, None, None),
directions : np.ndarray = None,
ax = None,
arrow_h... | 8f4b6ef68b6eae62637a772621c68ecb0acc1a55 | 9,730 |
def menu_items_api(restaurant_id):
"""Route handler for api endpoint retreiving menu items for a restaurant.
Args:
restaurant_id: An int representing the id of the restaurant whose menu
items are to be retrieved
Returns:
response: A json object containing all menu items for a g... | 472adaa25cd588246aef9f2b9a621723df399503 | 9,731 |
import logging
import tqdm
def run(indata):
"""indata: event detection DataArray or DataSet"""
if isinstance(indata, xr.DataArray):
events = indata
else:
events = indata["Event_ID"]
logging.info("events array defined.")
# turn events into time x space by stacking lat & lon:
even... | 817bb329638adb39950fac3b3f10d81938515f1a | 9,732 |
def format_trace_id(trace_id: int) -> str:
"""Format the trace id according to b3 specification."""
return format(trace_id, "032x") | 2c0541b4a25d85ae990e68e00dd75012aa1ced60 | 9,733 |
def get_count_name(df):
"""Indicate if a person has a 'Name'
Parameters
----------
df : panda dataframe
Returns
-------
Categorical unique code
"""
# Feature that tells whether a passenger had a cabin on the Titanic
df['Words_Count'] = df['Name'].apply(lambda x: len(x.split... | c51dfbcc025908243f20d10f4faa498fa068d4f7 | 9,734 |
from django.contrib.auth.models import User
def register_action(request):
"""
从这个django.contrib/auth.models 库里倒入里User方法。(其实User是orm方式操作用户表的实例)
然后我们直接用User.objects.create_user方法生成一个用户,参数为用户名和密码。然后保存这个生成的用户 就是注册成功了
但是如果用户表中已存在这个用户名,那么,这个生成语句就会报错。所以我们用try来捕获这个异常,如果发送错误那就是“用户已经存在”,如实给用户返回这句话。如果没问题,那么就返回 注... | 4e0d4cdd6ba3547846738b6483ba242adacb71e0 | 9,735 |
from typing import Callable
from typing import Any
import asyncio
import functools
async def run_blocking_io(func: Callable, *args, **kwargs) -> Any:
"""|coro|
Run some blocking function in an event loop.
If there is a running loop, ``'func'`` is executed in it.
Otherwise, a new loop is being creat... | e277d1fca909f26d0226c3085fe0e0fbf03bf257 | 9,736 |
def parse_config(cfg, section):
""" parse config data structure, return data of required section """
def is_valid_section(s):
valid_sections = ["info", "project", "variables", "refdata"]
return s in valid_sections
cfg_data = None
if is_valid_section(section):
try:
c... | 72d36dfaf93e17da166cac0c9b786da29107db3e | 9,737 |
from hmmlearn import hmm
import collections
def _predict_states(freqs):
"""Use frequencies to predict states across a chromosome.
Normalize so heterozygote blocks are assigned state 0 and homozygous
are assigned state 1.
"""
freqs = np.column_stack([np.array(freqs)])
model = hmm.GaussianHMM(2... | be1b1b540b644dc9f412a3d648076a36369e9aae | 9,738 |
def tp(*args) -> np.ndarray:
"""Tensor product.
Recursively calls `np.tensordot(a, b, 0)` for argument list
`args = [a0, a1, a2, ...]`, yielding, e.g.,
tp(a0, a1, a2) = tp(tp(a0, a1), a2)
Parameters
----------
args : sequence
Sequence of tensors
Returns
-------
np.... | c02b74d79d484e7335387e568fda723fcf3851b8 | 9,739 |
def aws_aws_page():
"""main endpoint"""
form = GenericFormTemplate()
return render_template(
'aws_page.html',
form=form,
text=util.get_text(module_path(), config.language),
options=g.user.get_options(),
) | 2605838a948e3b58fe7c669a388a859144c329c6 | 9,740 |
import subprocess
def popen_program(cmd, minimized=False, pipe=False, shell=False, **kwargs):
"""Run program and return a subprocess.Popen object."""
LOG.debug(
'cmd: %s, minimized: %s, pipe: %s, shell: %s',
cmd, minimized, pipe, shell,
)
LOG.debug('kwargs: %s', kwargs)
cmd_kwargs = build_cmd_kwar... | fe1e3d508dbd8ed086ea91f538a48ce0a9aeb69b | 9,741 |
def precompute(instr):
"""
Args:
instr:
Returns:
"""
qecc = instr.qecc
if qecc.name == '4.4.4.4 Surface Code' and qecc.circuit_compiler.name == 'Check2Circuits':
precomputed_data = code_surface4444(instr)
elif qecc.name == 'Medial 4.4.4.4 Surface Code' and qecc.circuit_... | 789e1f1f5e37f118f791a5c72c1c0dd7df2cf745 | 9,742 |
import re
def remove_url(txt):
"""Replace URLs found in a text string with nothing
(i.e. it will remove the URL from the string).
Parameters
----------
txt : string
A text string that you want to parse and remove urls.
Returns
-------
The same txt string with url's removed.
... | 8d1b8b89cb65ca7761c093dc388d1f19729137e7 | 9,743 |
def use_database(fn):
"""
Ensure that the correct database context is used for the wrapped function.
"""
@wraps(fn)
def inner(self, *args, **kwargs):
with self.database.bind_ctx(self.models):
return fn(self, *args, **kwargs)
return inner | 71a42974ce2413c0b24863be9397252bcd06f22e | 9,744 |
import imaplib, email, email.header
def getImapMailboxEmail(server, user, password, index, path="INBOX", searchSpec=None):
"""
imap_headers(server, user, password, index, path="INBOX", searchSpec=None)
Load specified email header from an imap server. index starts from 0.
Exampl... | c04569870f9528539e958cc114c11ad80c36800c | 9,745 |
from .shelf import ShelfStorage
import redis
from .redisobjectstore import RedisObjectStore
import os
def create_storage(uri=None):
"""factory to create storage based on `uri`, the ANYVAR_STORAGE_URI
environment value, or in-memory storage.
The URI format is one of the following:
* in-memory diction... | 34a6fa22b7f8fd1770aeae28c92f222d2160c901 | 9,746 |
def nmatches_mem(txt, pat, t, p, mem):
"""Find number of matches with recursion + memoization using a dictionary
(this solution will also crash when recursion limit is reached)
nmatches_mem(text, pattern, len(text), len(pattern), {})
"""
if (t,p) in mem:
return mem[t, p]
... | 5b6a10328ca876481fb9b8425bde2442f603d7e1 | 9,747 |
import os
import subprocess
def get_size_stats(args):
"""
Calculate size for each of the iterator.
It recusively iterate though a directory to find a specific extension file and report their size in preferred format.
"""
lang_size_dict = {}
for (dirpath, dirnames, filenames) in os.walk(args.da... | 11f70bf097fbf39e1b928e73413b8356e2b4986b | 9,748 |
def data_get():
"""
Get shared data from this server's local store.
"""
consistency = request.json["consistency"]
name = request.json["name"]
field = request.json["field"]
value = ""
error = "ok"
if consistency == "strict":
store = globalvars.get_data_store(globalvars.STRICT_... | c8a56b4171109800f4818d59aaf2b3bd9eed1b78 | 9,749 |
def pad_sequences(sequences, maxlen=None, value=0):
"""
pad sequences (num_samples, num_timesteps) to same length
"""
if maxlen is None:
maxlen = max(len(x) for x in sequences)
outputs = []
for x in sequences:
x = x[:maxlen]
pad_range = (0, maxlen - len(x))
x = n... | 29204f0f47150f6fac0761876b8045f680032da5 | 9,750 |
import traceback
import sys
def reset_password():
"""
Three main states of this controller
1. by default just show the email field
2. in a second step, also show the field for the code and new password
3. in a third step, if code is correct, redirect to login
:return: templa... | aa11367a202b51f2e0c1a844931fea0561fea0e2 | 9,751 |
def download(request, path):
"""
Downloads a file.
This is inspired by django.views.static.serve.
?disposition={attachment, inline}
"""
decoded_path = urllib.unquote(path)
if path != decoded_path:
path = decoded_path
if not SHOW_DOWNLOAD_BUTTON.get():
return serve_403_erro... | d2754b9b243e057cda2b20760af050bf908a3763 | 9,752 |
import random
def spacegroup_a_to_spacegroup_b(atoms, spgroup_a, spgroup_b, target_b_contribution, create_replicas_by,
min_nb_atoms=None, target_nb_atoms=None, max_diff_nb_atoms=None, radius=None,
target_replicas=None, max_rel_error=0.01, **kwargs):
... | d1254eae056b1229890e38030027ba8fd6670327 | 9,753 |
def empty_surface(fill_color, size=None, flags=0):
"""Returns an empty surface filled with fill_color.
:param fill_color: color to fill the surface with
:type fill_color: pygame.Color
:param size: the size of the new surface, if None its created
to be the same size as the screen
:type size... | b48d21649f279736f531ca0cb6e7dabf083c813b | 9,754 |
def getNetAddress(ip, netmask):
"""
Get the netaddress from an host ip and the netmask.
:param ip: Hosts IP address
:type ip: str
:param netmask: Netmask of the network
:type netmask:
:returns: Address of the network calculated using hostIP and netmask
:rtype: str
"""
ret... | 2bc70d21edcc08d82b146de83389ce94d2fa64ee | 9,755 |
import psutil
import os
import time
def begin_operation(name: str) -> dict:
"""
Gets the stats for the current operation.
Parameters
----------
name: str
name of the operation
Returns
-------
dict
dictionary with the operation stats
Examples
--------
>>> f... | b5f6444c5b8868723a6b920d578fec41e54b89a3 | 9,756 |
import time
import os
import pickle
import codecs
import random
from typing import Counter
def create_or_load_vocabulary(data_path,training_data_path,vocab_size,test_mode=False,tokenize_style='word',fine_tuning_stage=False,model_name=None):
"""
create or load vocabulary and label using training data.
proc... | 51aaa3b373512f1e47eb5e1a77870cf72292a389 | 9,757 |
def balance_intent_data(df):
"""Balance the data for intent detection task
Args:
df (pandas.DataFrame): data to be balance, should contain "Core Relations" column
Returns:
pandas.DataFrame: balanced data
"""
relation_counter = build_counter(df, "Core Relations")
# augment each... | 3f759ae229de5e30fe4f13f42e4b8db18f0c913d | 9,758 |
def npareamajority(values, areaclass):
"""
numpy area majority procedure
:param values:
:param areaclass:
:return:
"""
uni,ind = np.unique(areaclass,return_inverse=True)
return np.array([np.argmax(np.bincount(values[areaclass == group])) for group in uni])[ind] | 9e43244ef81e63d9870d281660b738fa3b73a11f | 9,759 |
def calcReward(eventPos, carPos, closeReward, cancelPenalty, openedPenalty):
"""
this function calculates the reward that will be achieved assuming event is picked up
:param eventPos: position of events
:param carPos: position of cars
:param closeReward: reward if event is closed
:param cancelPe... | 52226496b5338a0ebd3433ae9ee779c036c64809 | 9,760 |
from typing import Any
def b64encode(s: Any, altchars: Any = None) -> bytes:
"""Encode bytes using the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` to encode.
Optional ``altchars`` must be a byte string of length 2 which specifies
an alternative alphabet for the '+' and '/... | deef546ada7679a538afa5432a13846ce765b911 | 9,761 |
def select_programs(args, filter_paused=True, force=False):
"""
Return a list of selected programs from command line arguments
"""
if not (args.all ^ bool(args.names)):
if args.all:
log.error("You may not specify a program name when you use the -a/--all option (See -h/--help for mor... | 8b597b043ac7e245bf16aec17a779c5639d451d9 | 9,762 |
import math
def three_comp_two_objective_functions(obj_vars, hz: int,
ttes: SimpleTTEMeasures,
recovery_measures: SimpleRecMeasures):
"""
Two objective functions for recovery and expenditure error
that get all required params as... | f02403d00142556b17371f3adedd32994dbf9fad | 9,763 |
def scale(data, new_min, new_max):
"""Scales a normalised data series
:param data: The norrmalised data series to be scaled
:type data: List of numeric values
:param new_min: The minimum value of the scaled data series
:type new_min: numeric
:param new_max: The new maxim... | 3e7720ae90cfdbef1253dbfa39b3e4a10fc118bb | 9,764 |
def default_config() -> ClientConfig:
"""
:return: Default configuration for the experiment
"""
simulation_config = SimulationConfig(render=False, sleep=0.8, video=True, log_frequency=1,
video_fps=5, video_dir=default_output_dir() + "/videos", num_episodes=1000,
... | d7e53ccc4ad8818453cd673ddaa21fe0614dfc5a | 9,765 |
def get_same_padding(kernel_size: int, stride: int, dilation: int) -> int:
"""Calculates the padding size to obtain same padding.
Same padding means that the output will have the
shape input_shape / stride. That means, for
stride = 1 the output shape is the same as the input,
and str... | 12548482e855dcfc627c5b0a6ccf69ad4a74b39b | 9,766 |
def move_child_position(context, request):
""" Move the child from one position to another.
:param context: "Container" node in which the child changes its position.
:type context: :class:kotti.resources.Node or descendant
:param request: Current request (of method POST). Must contain either
... | 082aef1169de6dab4881593ef8abf85e5076f190 | 9,767 |
import requests
def get_current_version(package: str) -> str:
"""
Query PyPi index to find latest version of package
:param package: str - name of pacahe
:return: str - version if available
"""
url = f'{PYPI_BASE_URL}/pypi/{package}/json'
headers = {
'Content-Type': 'application/j... | 6d65dcb6d381c8cf6cba7c06ccebf538c16b85c7 | 9,768 |
import sys
import warnings
import os
def get_model_path(model_name):
"""
Returns path to the bird species classification model of the given name.
Parameters
----------
model_name : str
Name of classifier model. Should be in format
``<model id>_<taxonomy version>-<taxonomy md5sum>... | fa22967a40c53da8693e7aea6043e9e3192dccd5 | 9,769 |
def mconcat(xs : [a]) -> a:
"""
mconcat :: (Monoid m) => [m] -> m
Fold a list using the monoid.
"""
return Monoid[xs[0]].mconcat(xs) | cd87cc91bb4d2c6d1cf653fb45967ecb59d6749d | 9,770 |
def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask):
"""If necessary, zero out inputs to a conv for padding positions.
Args:
inputs: a Tensor with shape [batch, length, ...]
kernel_size: an integer or pair of integers
nonpadding_mask: a Tensor with shape [batch, length]
Returns:
Ten... | e53c1e181cac554047b9acb8d70d358baa9f8a4c | 9,771 |
import json
def display_json(value):
"""
Display input JSON as a code
"""
if value is None:
return display_for_value(value)
if isinstance(value, str):
value = json.loads(value)
return display_code(json.dumps(value, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)) | 727dc50d9844a5b0b7f01231c348652056d334cc | 9,772 |
def get_rgba_from_color(rgba):
"""Return typle of R, G, B, A components from given color.
Arguments:
rgba - color
"""
r = (rgba & 0xFF000000) >> 24
g = (rgba & 0x00FF0000) >> 16
b = (rgba & 0x0000FF00) >> 8
a = (rgba & 0x000000FF)
return r, g, b, a | 56d3e0dce01cfc4348ae115de81abb55ec85eb56 | 9,773 |
def beauty_factor(G):
"""Return the "beauty factor" of an arbitrary graph, the minimum distance
between a vertex and a non-incident edge."""
V, E = G[0], G[1]
dists = []
for (i, u) in enumerate(V):
for (j, k) in E:
if i == j or i == k:
continue
v, w = ... | 9267a534d8453a17561b2c8e1f67e40942069ffe | 9,774 |
def line_plane_cost(line, plane):
"""
A cost function for a line and a plane
"""
P = normalised((line|plane)*I5)
L = normalised(meet(P, plane))
return line_cost_function(L, line) | 34ab1df71f2018544a52020d232514127e16aa3e | 9,775 |
import requests
def register_document_to_documentsbundle(bundle_id, payload):
"""
Relaciona documento com seu fascículo(DocumentsBundle).
Utiliza a endpoint do Kernel /bundles/{{ DUNDLE_ID }}
"""
try:
response = hooks.kernel_connect(
"/bundles/%s/documents" % bundle_i... | df70b6b3556527a10ec7dd3f83ca4bc69fb90e61 | 9,776 |
import numpy
def force_full_index(dataframe: pd.DataFrame, resampling_step: int = None,
resampling_unit: str = "min", timestamp_start: int = None,
timestamp_end: int = None) -> pd.DataFrame:
""" forces a full index. Missing index will be replaced by Nan.
Note: re... | cc08ee348467e5fe335ebf3239ce78880c0f99c4 | 9,777 |
def legislature_to_number(leg):
"""
Takes a full session and splits it down to the values for
FormatDocument.asp.
session = '49th-1st-regular'
legislature_to_number(session) --> '49Leg/1s'
"""
l = leg.lower().split('-')
return '%sLeg/%s%s' % (l[0][0:2], l[1][0], l[2][0]) | cffeeea2bad17d9dadcfd75d70417824c7fe3396 | 9,778 |
def get_variable_field_type(variable_name, field_name, error_prefix=''):
"""
获取某个变量的某个字段的类型
"""
schema = get_variable_schema(variable_name)
result_type = schema.get(field_name)
if not result_type:
raise RuntimeError(utf8(error_prefix) + '变量(%s)不包含字段(%s)' % (utf8(variable_name), utf8(fie... | 6038cebd8219350eec5595bd5ca9aa0151f287cf | 9,779 |
def test(input_test_data):
"""
Run test batches on trained network
:return: Test accuracy [0-1]
"""
print('--- Execute testing ---')
one_hot_label = np.zeros(10, dtype=np.uint8)
correct_n = 0
total_n = 0
for batch_id, (mini_batch, label) in enumerate(input_test_data):
for s... | dcdbaad1c1496f7cc611ca81f0cb086c3dd127fc | 9,780 |
def test(net, example):
"""
Args:
net (FlowNet): Instance of networks.flownet.FlowNet model, only to be used for pre-processing.
example (dict): Un-processed example.
Returns:
good (list, DMatch): List of good SIFT matches.
"""
net.eval()
example = net.preprocess(example... | b0a864e0468304c6c0060d3ee621d579f806c58f | 9,781 |
def get_hashers():
"""
从settings.py中动态导入一连串hashers对象
Read list of hashers from app.settings.py
"""
hashers = []
# 导入报名
for hasher_path in current_app.config.get('PASSWORD_HASHERS'):
hasher_cls = import_string(hasher_path)
hasher = hasher_cls()
hashers.append(hashers)
... | d44784d077a99ca23190826249fab6bbf8ad57d5 | 9,782 |
def str2range(s):
"""parse a samtools/tabix type region specification 'chr:start-stop' or 'chr:start..stop'"""
chrom = None
start = 1
stop = None
tmp = s.split(':')
chrom = tmp[0]
if len(tmp)>1:
if '-' in tmp[1]:
tmp = tmp[1].split('-')
else:
tmp = tmp... | 8a72107495cc0e7587cadc289b80d326b7901c59 | 9,783 |
import json
def turn_read_content(path, labelIdx, dataIdx):
"""
sentences: (dialog_num, turn_num, nbest_num, sentence_len)
scores: (dialog_num, turn_num, nbest_num)
acts: (dialog_num, turn_num, machine_act_len)
labels: (dialog_num, turn_num, [label_dim])
"""
sentences, scores, acts, labels... | 09049b9028ab4331de9c71afb35a79d348bfce08 | 9,784 |
def index_page() -> dict:
"""Get data for Index page , interfaces, dp neighbors, arps, and hsrp"""
interfaces = GetThisDataFromDevice.get_interfaces(request.json.get('ip'), request.json.get('port'), request.json.get('username'), request.json.get('password'))
neighbors = GetThisDataFromDevice.get_dp_neighbo... | 5506031e11e5ab2c8b40e1f294e04a0ed56a96ac | 9,785 |
def reverse_int_bits(n: int, n_bits: int = 10) -> int:
"""Reverses the bits of *n*, considering it is padded by *n_bits* first"""
return int(format(n, '0' + str(n_bits) + 'b')[::-1], 2) | 3c76db59296863161b0bb543e057a82383a780a2 | 9,786 |
def get_conn():
"""
获取
:return:
"""
for name in GENERATOR_MAP:
print(name)
if not hasattr(g, name):
setattr(g, name + '_cookies', eval('CookiesRedisClient' + '(name="' + name + '")'))
setattr(g, name + '_account', eval('AccountRedisClient' + '(name="' + name +... | 7bf4d23db3f829203041560077e0813a94930af0 | 9,787 |
def get_rule_satisfaction_matrix(x, y, rules):
""" Returns a matrix that shows which instances satisfy which rules
Each column of the returned matrix corresponds to a rules and each row to an instance.
If an instance satisfies a rule, the corresponding value will be 1, else 0.
:param x: np.ndarray
... | 1df187006449e2c101f09b88ac2e8fe9851c7698 | 9,788 |
def refactor(df, frequency = '1W'):
"""Refactor/rebin the data to a lower cadence
The data is regrouped using pd.Grouper
"""
low = df.low.groupby(pd.Grouper(freq=frequency)).min()
high = df.high.groupby(pd.Grouper(freq=frequency)).max()
close = df.close.groupby(pd.Grouper(freq=fr... | 217e65236994e9a075ef410488250cbb1051dbb4 | 9,789 |
def pendulum_derivatives(theta, omega, g=9.8, l=1):
"""
\dot{\theta} = \omega
\dot{\omega} = -\frac{g \sin\theta}{l}
:param theta: angel of the pendulum
:param omega: angular velocity of the pendulum
:param g: gravitational acceleration
:param l: length of the pendulum
:return: derivativ... | 1e83af5ed6028a9cd0ecf5819d3797986493df25 | 9,790 |
def get_sql_filtered( source_query, python_types, db_conf_file_name, filters=[]):
"""
Return list of DBAPI tuples (& prefixed header row) filtered by value
Keyword Parameters:
source_query -- String, representing SQL definition of requested datasource
python_types -- JSON encoded string representi... | 2eb8333efa7843f32bba1dd63fabad23e8ffbb75 | 9,791 |
def task_edit(request, pk=None):
"""
"""
return edit(request, form_model=TaskForm, model=Task, pk=pk) | 8ff6f1bd007ff4f6931030da41f5efeaa2380d3a | 9,792 |
def get_intersect(pre_df, post_df, args, aoi=None):
"""
Computes intersection of two dataframes and reduces extent by an optional defined AOI.
:param pre_df: dataframe of raster footprints
:param post_df: dataframe of raster footprints
:param args: arguments object
:param aoi: AOI dataframe
... | 56c35cd0ecd883418bb8b88102721ed9ad6a5654 | 9,793 |
import torch
def _gradient(P, T, N, A):
"""
Creates the gradient operator, starting from the point set P, the topology tensor T, the normal tensor N and the
triangle area tensor A
Parameters
----------
P : Tensor
the (N,3,) point set tensor
T : LongTensor
the (3,M,) topolo... | dd1118218ca6e8ad3ff3202c2a3c6d603f88a3a9 | 9,794 |
from typing import Tuple
def breast_tissue_diagnostic_black_pen() -> Tuple[
openslide.OpenSlide, str
]: # pragma: no cover
"""breast_tissue_diagnostic_black_pen() -> Tuple[openslide.OpenSlide, str]
Breast tissue, TCGA-BRCA dataset. Diagnostic slide with black pen marks.
This image is available here... | 9758d6ac89a5bb4402e89486be624de9fad986d4 | 9,795 |
def fitcand(t,fm,p,full=False):
"""
Perform a non-linear fit to a putative transit.
Parameters
----------
t : time
fm : flux
p : trial parameter (dictionary)
full : Retrun tdt and fdt
Returns
-------
res : result dictionary.
"""
dtL = LDTwrap(t,fm,p)
dt ... | dbf1252d3a4b9d81d092d983b231b7f25a2ef10b | 9,796 |
def cbar_for_line_plot(axis, num_steps, discrete_ticks=True, **kwargs):
"""
Adds a colorbar next to a line plot axis
Parameters
----------
axis : matplotlib.axes.Axes
Axis with multiple line objects
num_steps : uint
Number of steps in the colorbar
discrete_ticks : (optional)... | b9d83d93f7b86259a796cc71638a0bef0c81dce7 | 9,797 |
from typing import Union
def get_config_based_on_config_file(path: str) -> Union[Config, None]:
"""
load config and check if section exist or not
:param path: path to config file
:return: None if section [laziest] not exist in Config object updated with params from section if exist
"""
cfg... | 1a537aace82528ff1163deadeea3c48b9289c622 | 9,798 |
import typing
import asyncio
import concurrent
def threadpooled( # noqa: F811
func: typing.Optional[typing.Callable[..., typing.Union["typing.Awaitable[typing.Any]", typing.Any]]] = None,
*,
loop_getter: typing.Union[None, typing.Callable[..., asyncio.AbstractEventLoop], asyncio.AbstractEventLoop] = None... | 77a91a627569a069728531e2baaa92d8ee5609b3 | 9,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.