content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def loading_effects_decorator(func):
"""
Decorator for creating an loading cursor.
>>> @loading_effects_decorator
>>> def do_lengthy_process():
>>> # DO something
>>> pass
Parameters
----------
func: function
Returns
-------
new_function: object
"""
d... | 76,200 |
def get_response_json(url: str):
"""
Function get response json dictionary from url.
:param url: url address to get response json
:type url: str
:return: dictionary data
:rtype: json
:usage:
function calling
.. code:: python
get_response_json(url)
"""
... | 76,201 |
def JobPostingDetails(request, pk):
"""
Retrieve, update or delete a job posting.
"""
try:
job_posting = JobPosting.objects.get(pk=pk)
except JobPosting.DoesNotExist:
return HttpResponse(status=500)
if request.method == "GET":
serializer = JobPostingSerializer(job_postin... | 76,202 |
def test_data_kept_with_empty_lst():
"""Test that a list stays a list when there is no value in it."""
result = inbound_user_filter({"id": "123-456-abs3", "manager": []}, "azure")
assert result["manager_id"] == [] | 76,203 |
def start_logging(level, logfile):
"""
Initialize a useful logging environment with logging to stderr,
slightly more verbose to a log file, and suitable log levels.
"""
loggingclass.init_logging(level)
if level == loggingclass.DEBUG:
# loggingclass.getLogger().setLevel(loggingclass.D... | 76,204 |
def test_crowdcoding_next_leastcoded(job: int, user: User, admin_user: User, password_user: User):
"""Does crowdcoding favour units with fewer anotations?"""
jobset = get_jobset(job.id, admin_user, True)
units = get_jobset_units(jobset)
set_annotation(units[0], admin_user, {})
u, index = get_next_un... | 76,205 |
def me():
"""Manage your personal information.""" | 76,206 |
def cli():
"""Manage your CRMint instance on GCP.""" | 76,207 |
def _validate_recurse_directive_types(current_schema_type, field_schema_type, context):
"""Perform type checks on the enclosing type and the recursed type for a recurse directive.
Args:
current_schema_type: GraphQLType, the schema type at the current location
field_schema_type: GraphQLType, the... | 76,208 |
def test_check_users_for_update(app, system_user):
"""Test check for users update in sync command."""
with app.app_context():
user = RemoteAccount.query.join(User).one()
ldap_user = {
'displayName': [b'System User'],
'department': [b'Another department'],
'uid... | 76,209 |
def populate_study_device_settings(sender, **kwargs):
"""
Ensure that every newly created Study object has a DeviceSettings object. This essentially
makes the OneToOneField have null=False in both directions.
"""
my_study = kwargs['instance']
if kwargs['created'] and not hasattr(my_study... | 76,210 |
def create_enclave_signup_data():
"""
Create enclave signup data
"""
try:
enclave_signup_data = \
enclave_helper.EnclaveHelper.create_enclave_signup_data()
except Exception as e:
logger.error("failed to create enclave signup data; %s", str(e))
sys.exit(-1)
re... | 76,211 |
def strip_typehints(source):
"""Strip the type hints from a function"""
if black:
source = black.format_str(source, line_length=82)
# parse the source code into an AST
parsed_source = ast.parse(source)
# remove all type annotations, function return type definitions
# and import stateme... | 76,212 |
def upconv(x, channels, kernel=3, stride=2, pad=1, use_bias=True, sn=False, scope='upconv_0'):
"""
upsampling + conv
"""
with tf.variable_scope(scope):
x = up_sample(x, scale_factor=stride)
x = conv(x, channels=channels, kernel=kernel, stride=1, pad=1, use_bias=use_bias, sn=sn, scope=sco... | 76,213 |
def create_temporary_copy(directory_path: str, target_directory_prefix: str = "") -> str:
"""Creates a copy of a directory in a temporary directory and returns its path"""
copy_path = get_temporary_directory_path(target_directory_prefix)
copy(directory_path, copy_path)
return copy_path | 76,214 |
def dumps_content(content):
"""
pickle 序列化响应对象
:param content: 响应对象
:return: 序列化内容
"""
return pickle.dumps(content) | 76,215 |
def get_info(request, tut):
"""Get information about the tutorial from the 'info.ini' file.
:request: Pyramid request
:tutorial: Tutorial name
"""
cfg = SafeConfigParser()
cfg.optionxform = str # case-sensitive keys
cfg.read(os.path.join(get_tutorialdir(request, tut), 'info.ini'))
inf... | 76,216 |
def upgrade_requirements():
"""
Install the contents of requirements.txt to the virtual environment
"""
check = exists('%(path)s/requirements.txt' % env)
if check:
virtualenv('pip install --upgrade -r %(path)s/requirements.txt' % env)
else:
print red("Can't find requirements.tx... | 76,217 |
def test___init__(image_config: ImageConfig, image_config_signed: ImageConfig):
"""Test that signed and unsigned configurations can be instantiated."""
assert image_config
assert image_config_signed | 76,218 |
def run(xml_dir, output_fpath):
""" Gets the path to the framenet root directory and output the csv file with role lus. """
frame2role2lu = extact_frame2role2lu(xml_dir, output_fpath)
save_frame2role2lu(frame2role2lu, output_fpath) | 76,219 |
def hide_solution(key, tpl_dict = latex_doc.tpl_dict):
"""Hide solutions by default"""
return """
{%- if cell.metadata.solution_first or cell.metadata.solution2_first or cell.solution_first or cell.solution2_first -%}
{# exercise #}
{%- elif cell.metadata.solution == 'hidden' or cell.metadata... | 76,220 |
def midpoint(f, a, b, N):
"""Zusammengesetzte Mittelpunktsregel in 1d.
Input:
f : Funktion f(x) welche integiert werden soll.
a, b : untere/obere Grenze des Integrals.
N : Anzahl Teilintervalle in der zusammengesetzten Regel.
"""
x, h = np.linspace(a, b, N+1, retstep=True)... | 76,221 |
def create_arg_parser():
""" Create an argument parser
return: argparse.ArgumentParser
"""
parser = argparse.ArgumentParser()
# Read in the input file
parser = argparse.ArgumentParser(
description="Create metrics plots in a batch mode")
parser.add_argument(dest='main_inputfile', ... | 76,222 |
def content_disposition_filename(filename):
"""
Sanitize a file name to be used in the Content-Disposition HTTP
header.
Even if the standard is quite permissive in terms of
characters, there are a lot of edge cases that are not supported by
different browsers.
See http://greenbytes.de/tech... | 76,223 |
def orgs_v3_p1():
"""
Returns raw orgs from API v3
"""
with open(os.path.join(HERE, 'fixtures', 'orgs_v3_p1.json')) as f:
return json.loads(f.read()) | 76,224 |
def fmt_datetime(object_: datetime) -> str:
"""Parse datetime into pydantic's JSON encoded datetime string"""
return object_.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | 76,225 |
def test_ergodic_forward():
"""Forward algorithm on an ergodic HMM"""
hmm = deepcopy(hmm_e)
hmm.set_random_initial()
hmm.set_random_transitions()
hmm.fit(X)
assert isinstance(hmm.forward(x), float) | 76,226 |
def _gen_setup_file(project_name: str) -> str:
"""
Generate setup.py module content.
"""
content = """\
from setuptools import setup, find_packages
setup(
name='%s',
description='App description.',
version='1.0',
packages=find_packages(),
# package_data={'package': ['subfolder/*']}... | 76,227 |
def generate_manifest_in_from_git():
"""Generate MANIFEST.in from 'git ls-files'"""
cmd = r'''git ls-files | sed 's/\(.*\)/include \1/g' > MANIFEST.in'''
return subprocess.call(cmd, shell=True) | 76,228 |
def get_table_list(transaction_executor):
"""
Connect to a given ledger using default settings.
"""
statement = "SELECT name FROM information_schema.user_tables"
cursor = transaction_executor.execute_statement(statement)
try:
table_list = {}
i = 0
for row in cursor:
... | 76,229 |
def _apply_conv_mode(ret, s1, s2, mode, axes):
"""Calculate the convolution result shape based on the `mode` argument.
Returns the result sliced to the correct size for the given mode.
Parameters
----------
ret : array
The result array, with the appropriate shape for the 'full' mode.
s... | 76,230 |
def submit_local(filename: str, cmd_line_arguments: str, debug: bool = True):
"""Create a local job & submit it based on provided file to execute."""
cmd = f"{PYTHON_EXECUTABLE} {filename} {cmd_line_arguments}"
proc = submit_subprocess(cmd, debug)
return proc | 76,231 |
def format_time(ogtime):
"""Increase readability of given catalog times."""
return pd.Timestamp(' '.join(ogtime.split('T'))[:-1]) | 76,232 |
def test_name(km_user_factory):
"""
The know me user's name property should return the associated user's
short name.
"""
km_user = km_user_factory()
assert km_user.name == km_user.user.get_short_name() | 76,233 |
def train(loss_fn):
"""使用损失函数loss_fn训练回归"""
print("Training;loss function:" + loss_fn.__name__)
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
def loss_for_example(x, y):
return loss_fn(y, prediction(x))
# `grad_fn(x_i, y_i)` returns (1) the value of `loss_for_example`
... | 76,234 |
def estimator(data):
"""
Takes input data and returns it in a
specified format.
"""
# get days
days = timeEstimateDays(data["periodType"], data["timeToElapse"])
# Challenge 1
# Currently infected estimates
currentlyInfectedImpact = int(data["reportedCases"] * 10)
curren... | 76,235 |
def run(method):
"""Run method."""
switcher = {
"construct": lambda: construct(),
"execute": lambda: execute()
}
return switcher.get(method)() | 76,236 |
def unicode_parm(cap, *parms):
"""Return the result of ``tparm(tigetstr())`` except as Unicode."""
return tparm(tigetstr(cap), *parms).decode('utf-8') | 76,237 |
def test_check_instances_dict_formatting():
"""[Utils] check_instances: test formatting of dict."""
instances = {'a': [OLS(), ('ols', OLS()), ('ols', OLS()), ['list', OLS()]],
'b': [],
'c': [OLS(), ('ols', OLS())]}
formatted = _check_instances(instances)
for k, v in f... | 76,238 |
def lmtd(tci, tco, thi, tho, counterflow=True):
"""log mean temperature difference
tci = cold inlet
tco = cold outlet
thi = hot inlet
tho = hot outlet
"""
if counterflow:
itd = thi - tco
otd = tho - tci
else:
itd = thi - tci
otd = tho - tco
return lmd(itd, otd) | 76,239 |
def haversine_distances(X, Y=None):
"""Compute the Haversine distance between samples in X and Y
The Haversine (or great circle) distance is the angular distance between
two points on the surface of a sphere. The first distance of each point is
assumed to be the latitude, the second is the longitude, g... | 76,240 |
def rotateRight(self, head: ListNode, k: int) -> ListNode:
"""
72ms 36.76%
13MB 95.80%
:param self:
:param head:
:param k:
:return:
"""
if not head or not head.next:
return head
old_tail = head
length = 1
while old_tail.next:
old_tail = old_tail.next
... | 76,241 |
def calculate(frame,shares_outstanding):
"""
calculate daily RV/BV/Diff price/volume values from minute price data frame
:param frame: pandas dataframe object from minute price data
:param shares_outstanding: company shares outstanding for volume normalization
:return: the new frame constructed fro... | 76,242 |
def main():
"""
:return:
"""
global THI_time
connect()
# 总循环
while True:
try:
if THI_time == 120:
THI_temp = THI_num()
data = {
"idx": THI_idx[0],
"nvalue": 0,
"svalue":... | 76,243 |
def mgc(piece_u, piece_v, relation):
"""
Computes the final mahalanobis gradient compatibility
:param piece_u: One of the puzzle pieces
:type piece_u: numpy.ndarray
:param piece_v: The other one of the puzzle pieces
:type piece_v: numpy.ndarray
:param relation: The connecting relation be... | 76,244 |
def mock_query_object(LCClient):
"""
Creating a Query Response object and prefilling it with some information
"""
# Creating a Query Response Object
start = '2016/1/1'
end = '2016/1/2'
obj = {
'TimeRange': TimeRange(parse_time(start), parse_time(end)),
'Time_start': parse_tim... | 76,245 |
def determine_edge_sigmoid_params(laplacian_image: itk.Image) \
-> tuple[float, float]:
"""
This function determines the appropriate alpha and beta
for a sigmoid function. This sigmoid function should map
regions of constant intensity to 1.0, while mapping regions
with high intensity gradien... | 76,246 |
def getRandomPopulation(popSize, numItems):
"""
Creates a population of random chromosomes
:param popSize: Population size
:param numItems: Chromosome size
:return: list
"""
return [getRandomChromosome(numItems)
for x in range(popSize)] | 76,247 |
def test_vector_var_setitem():
"""
Tests setting indexes in a Tensor with vector variables
"""
v1 = fwd.var('x', [1, 2, 3])
v2 = fwd.var('y', [2, 3, 4])
res = 2 * v1 * v2
res[0] += res[1] + res[2] / 2
assert np.array_equal(res.value, [28, 12, 24])
assert np.array_equal(res.d['x'], [... | 76,248 |
def multi_synonym(w2v_model, multi_syns, n, pooling):
"""Given list of synonyms that represents crossword clue, return aggregate ranking
Args:
w2v_model : standard Word2Vec 'KeyedVectors' data structure
multi_syns : nested list containing lists of each synonym present in a clue
n : ... | 76,249 |
def handleCookbookError(r):
"""Deals with errors when updating cookbook"""
if(r.status_code == 404):
print ""
print "Error Notifying Cookbook of new Gist. Is this URL correct?"
print cookbookURL
print ""
print "If not, update cookbookURL in uploadGists.py in devtools to c... | 76,250 |
def check_cross_account(policy_text, allowed_accounts):
"""Find cross account access policy grant not explicitly allowed
"""
if isinstance(policy_text, basestring):
policy = json.loads(policy_text)
else:
policy = policy_text
violations = []
for s in policy['Statement']:
... | 76,251 |
async def test_setup_with_photo_session(hass, entry, mock_websocket, setup_plex_server):
"""Test setup component with config."""
mock_plex_server = await setup_plex_server(config_entry=entry, session_type="photo")
assert len(hass.config_entries.async_entries(const.DOMAIN)) == 1
assert entry.state == EN... | 76,252 |
def stokes_ellipsometry(tanpsi, Delta):
"""
Stokes vector using ellipsometer parameters.
This creates a Stokes vector for the specific set of ellipsometry
parameters tanpsi and Delta. See Fujiwara table 3.1 for example.
Args:
tanpsi: abs(E_x/E_y) [-]
Delta: angle(E_x) ... | 76,253 |
def gen_psd(q):
"""
Random PSD matrix of size (q,q)
from Wishart distribution
"""
G = np.random.randn(q,q)
G = G @ G.T * (1/q)
return G | 76,254 |
async def stream(response, streamdict, newkey=lambda k:None, io=stdout, suffix=""):
"""
Stream simulation data into a Buffer (DataFrame)
"""
more = True
while more:
more, res = await read(response, io)
for k, v in res.items():
k = k+suffix # store different runs under dif... | 76,255 |
def menu_loop():
""" Main menu loop """
choice = None
# Loop over options as long as user doesn't quit
while choice != 'q':
# Clear screen
clear_screen()
# Loop over menu items and render each
print("Enter 'q' to quit.")
for key, value in menu.items():
... | 76,256 |
def strictwwid(wwid):
"""Validity checks WWID for invalid format using strict rules - must be Brocade format"""
if len(wwid) != 23: # WWPN must be 23 characters long
print("WWID has invalid length " + wwid)
return None
# Colon separators must be in the correct place
if wwid[2:3] !... | 76,257 |
def GetPlistDateValue(key, secure=False, plist=None, str_format=None):
"""Returns the UTC datetime of a given plist date key, or None if not found.
Args:
key: string key to get from the plist.
secure: boolean; True = munki secure plist, False = munki regular plist.
plist: optional, str plist path to us... | 76,258 |
def get_research_data_by_dev(sn):
"""Return the research data by device
"""
dev = Instrument.query.filter_by(sn=sn).first_or_404()
# Choose model
model = dev._get_data_model()
data = _collection(model, model.query.filter_by(instr_sn=dev.sn),
name='data', sn=dev.sn, researche... | 76,259 |
def clear_database(database_path):
"""Deletes all the property files in the given database
Parameters
----------
database_path : str
Path to the database to be cleared
"""
for table in glob.glob(os.path.join(database_path,'*')):
for file in glob.glob(os.path.join(table,'*'))... | 76,260 |
def main():
"""Entrypoint to this program"""
check_prerequisites()
parser = argparse.ArgumentParser(description='Run pylint and import the results to CodeSonar')
# NB: The fields of 'args' must be compatible with pylint2sarif.py.
parser.add_argument('inputs', nargs='*',
help=... | 76,261 |
def create_layer(number):
""" Creates a new layer """
file_list = glob.glob(f'{shp_path}*.shp')
random_index = randint(0, len(file_list) - 1)
file_uri = file_list[random_index]
layer = file_upload(file_uri)
# keywords
assign_keywords(layer)
# other stuff
resource = layer.get_self_res... | 76,262 |
def gethub():
"""
:return: an initialized instance of the github utility.
"""
# Thanks, I'll be here all week.
return Github(base_url=GITHUB_API_URL, login_or_token=GITHUB_ACCESS_TOKEN) | 76,263 |
def get_verification_link(request):
"""
Computes the verification link
"""
verification = create_verification(request)
if type(verification) is not models.VerificationModel:
return None
else:
return "%s/%s/verify-link/?u=%s&c=%s" %(request.META["HTTP_HOST"], settings.AC... | 76,264 |
def mrp_shadow(mrpset):
"""return the shadow set of a given modified rodrigues parameter
set
:param mrpset: modified rodrigues parameter set
:return: shadow set of the given MRP set
"""
return np.array([-s/(np.linalg.norm(mrpset)**2) for s in mrpset]) | 76,265 |
def subplot(size, location):
"""
Used for plotting multiple figures
"""
plt.subplot(str(size[0]) + str(size[1]) + str(location)) | 76,266 |
def upper_char(c):
"""Return the uppercase version of the character in the current locale."""
return chr(_toupper(ord(c))) | 76,267 |
def test_log_in_link_click(instagram, element):
""" Verify log in page log_in_link_click method works """
instagram.driver.find_element.return_value = element
instagram.log_in_page.log_in_link_click(False)
assert mock.call.find_element(XPATH, LOG_IN_LINK_XPATH) in instagram.driver.method_calls
asse... | 76,268 |
def _create_fig(n_cols, n_rows, figname, wrap_col=5, w_plot=5, h_plot=3):
"""Create a figure with subplots
Parameters
----------
n_cols, n_rows: int, number of rows and column in the plot
figname: str, name of the figure window
wrap_col: int, if only 1 row is present, wrap the columns
w_plo... | 76,269 |
def ipat(pat):
"""Convert glob pattern to case insensitive form."""
(dirname, pat) = os.path.split(pat)
# Convert '/path/to/test.fpt' => '/path/to/[Tt][Ee][Ss][Tt].[]'
newpat = ''
for c in pat:
if c.isalpha:
u = c.upper()
l = c.lower()
if u != l:
... | 76,270 |
def test_duplicate_version_exception():
"""
Test if the duplicate version exception is raised when importing.
"""
with raises(DuplicateVersionException):
from .utils import duplicate_versions | 76,271 |
def rank_reports(unranked, label, metric):
"""
Ordena una lista de listas de reportes con respecto a la label y métrica
especificada.
Args:
unranked (list): Lista de listas de reportes.
label (str): Nombre de la label con la cual se quiere optimizar.
metric (str): Nombre de la m... | 76,272 |
def neural_in_test(nsamp=1000,nin=400,d=4,rvar=0.1,wvar=None):
"""
Unit test for the neural input estimator
"""
if wvar is None:
wvar = 1/nin
# Generate random data
Rvar = rand_cov(d=d,rho=0.5,scale=rvar)
X = np.random.normal(0,1,(nsamp,nin))
W0 = np.random.normal(0,np.s... | 76,273 |
def incomplete_mat_mult_bsr(*args):
"""
incomplete_mat_mult_bsr(int Ap, int Aj, float Ax, int Bp, int Bj, float Bx,
int Sp, int Sj, float Sx, int n_brow, int n_bcol,
int brow_A, int bcol_A, int bcol_B)
incomplete_mat_mult_bsr(int Ap, int Aj, double Ax, int Bp, int Bj, double Bx,
int... | 76,274 |
def write_sorted_dca_scores(file_name, sorted_DI, metadata=None, score_type = None):
"""Writes sorted direct information to file.
Parameters
----------
file_name : str
Path to file where DCA data is going to be saved.
sorted_DI : list
A list containing site pair
... | 76,275 |
def get_fit_entries(path, model_type, num_best):
"""Get entries to insert into the Fit() table, describing the fitted models of a certain model type."""
data = []
for idx in range(num_best):
df = pd.read_csv(os.path.join(path, path_args.fname_best_csv))
run_no = int(df.iloc[idx]['run_no'])
... | 76,276 |
def RemoveIssuerCertsFromKeychain(issuer_cn, keychain=login_keychain, gui=False,
password=None):
"""Removes all certificates issued from a given CN from the keychain.
DeleteCert tries to raise privileges to allow deletions from the System
keychain, so we try and log if it fails.... | 76,277 |
def GetMonthList():
"""
Get a list of the defined month names.
rtype: `list`
"""
monthlist = []
for i in range(13):
name = Month[i]
if name is not None:
monthlist.append(name)
return monthlist | 76,278 |
def get_absolute_url(url, endpoint=None):
"""
Returns the absolute url based on the url and endpoint
Args:
url (str): base url with domain (e.g. https://domain.com)
endpoint (str): link to convert to an absolute url (e.g. /image.png)
"""
endpoint = endpoint.replace('%... | 76,279 |
def test_abutting_lists():
"""Lists next to each other should not be combined."""
content = """* List 1
* List 1
* List 2
* List 2
"""
wikicode = mwparserfromhell.parse(content)
assert (
compose(wikicode)
== "<ul><li> List 1\n</li><li> List 1\n</li></ul><ul><li> List 2\n</li><li> List 2... | 76,280 |
def test_suffix(input_field, suffix):
"""Test ``suffix`` property."""
assert input_field.suffix == suffix | 76,281 |
def add_global_tracks(g, ic):
"""Add the global tracks to every channel."""
add_dummy_tracks(g, ic)
GLOBAL_SPINE_ROW = ic.max_x // 2
GLOBAL_BUF = "GLOBAL_BUFFER_OUTPUT"
padin_db = ic.padin_pio_db()
iolatch_db = ic.iolatch_db()
# Create the 8 global networks
for i in range(0, 8):
... | 76,282 |
async def do_task() -> Response:
"""Run a task with celery workers
Returns:
A response with the results in the payload
"""
s = time()
job = group(tasks.send_task('add.two',args=[i,i]) for i in range(100))
result = job.apply_async()
# result.ready()
res = result.get()
p... | 76,283 |
def test_chunk_write(chunk, lastindex, filename):
"""Try writing a chunk to a new h5py file"""
with h5py.File(filename, 'w') as f:
io.write(chunk, f)
with h5py.File(filename, 'r') as f:
assert chunk.name in f
g = f[chunk.name]
assert_h5py_allclose(g, chunk) | 76,284 |
def get_validation_augmentation():
"""Add paddings to make image shape divisible by 32"""
test_transform = [
A.PadIfNeeded(384, 160)
]
return A.Compose(test_transform) | 76,285 |
def lnlike_0(ts, ys, yivars, deltanu, nupeak, K, numax, Lambda0, H, Gamma):
"""Log Likelihood for a comb of K frequencies centered on nupeak and separated by deltanu (solves for the amplitudes)"""
assert len(ts) == len(ys)
halfK = (K - 1) // 2
thisK = 2 * halfK + 1
M = np.zeros((len(t... | 76,286 |
def find_dpid_port_by_ip(ip):
"""
finds dpid and port in which IP is located
"""
p = [(x['dpid'],x['port']) for x in core.discovery.gmat if x['ip'] == ip]
if not p:
return (None, None)
else:
return p.pop() | 76,287 |
def model_summarize(model, show_weights=True, show_parameters=True):
"""Summarizes torch model by showing trainable parameters and weights."""
tmpstr = model.__class__.__name__ + ' (\n'
params_num = 0
for key, module in model._modules.items():
# if it contains layers let call it recursively to g... | 76,288 |
def gamedvr_record(console):
"""
Default to record last 60 seconds
Adjust with start/end query parameter
(delta time in seconds)
"""
try:
start_delta = request.args.get('start', -60)
end_delta = request.args.get('end', 0)
console.dvr_record(int(start_delta), int(end_delta... | 76,289 |
def validate_display_name(display_name: str):
"""Verify display name is at most 128 chars
Args:
display_name: display name to verify
Raises:
ValueError: display name is longer than 128 characters
"""
if len(display_name) > 128:
raise ValueError("Display name needs to be less... | 76,290 |
def execute(command, env=None, split_lines=False, ignore_errors=False,
extra_ignore_errors=(), translate_newlines=True, with_errors=True):
"""
Utility function to execute a command and return the output.
"""
if isinstance(command, list):
debug(subprocess.list2cmdline(command))
el... | 76,291 |
def my_kernel_exp(dis, gamma=.1):
"""gamma is auto tuned. The argument gamma means shrink_ratio.
"""
# if full_output:
# print 'gamma = {0:.4f} dim = {1:.4f} squared = {2}'.format(gamma, dim, squared)
dis *= -gamma
np.exp(dis, dis)
return dis | 76,292 |
def __get_mir_precursor_to_mature_mapper__():
"""
:return: a dictionary mapping taxonomy ID and miRBase precursor ID to a list containing the IDs of mature miRNAs
made from this precursor, e.g. the tuple ('9606', 'hsa-mir-155') might be mapped to ['hsa-miR-155-5p',
'hsa-miR-155-3p']
... | 76,293 |
def parse_args():
""" PARAMETERS"""
parser = argparse.ArgumentParser("train")
parser.add_argument("--use_cpu", action="store_true", default=False, help = "use cpu mode?")
parser.add_argument("--gpu", type = str, default="0", help = "specify the gpu device")
parser.add_argument("--batch_size", type=i... | 76,294 |
def set_entity_permissions(syn, entity, principalid, permission_level="download"):
"""
Convenience function to set ACL on an entity for a user or team based on
permission levels (view, download...)
Args:
syn: Synapse object
entity: An Entity or Synapse ID to lookup
principalid: ... | 76,295 |
def pipeline_run_add_tag(run_id, tags, organization=None, project=None, detect=None):
""" Add tag(s) for a pipeline run.
:param run_id: ID of the pipeline run.
:type run_id: int
:param tags: Tag(s) to be added to the pipeline run. [Comma seperated values]
:type tags: str
:rtype: list of str
... | 76,296 |
def anisodiff(img, niter=1, kappa=50, gamma=0.1, step=(1., 1.),
option=1):
"""
Anisotropic diffusion on single channel image
Usage:
imgout = anisodiff(im, niter, kappa, gamma, option)
Arguments:
img - input image
niter - number of iterations
ka... | 76,297 |
def selenium_capature():
"""
selenium web页面截屏
:return:
"""
from selenium import webdriver
import time
def capture(url, filename="capture.png"):
browser = webdriver.Chrome(r"C:\Program Files (x86)\Google Chrome\chromedriver.exe")
browser.set_window_size(1200, 900)
brow... | 76,298 |
def add_keys2(a, b, B):
"""
aG + bB, G is basepoint
:param a:
:param b:
:param B:
:return:
"""
return tcry.xmr_add_keys2_vartime_r(a, b, B) | 76,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.