content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def evenify(n):
"""Ensure number is even by incrementing if odd
"""
return n if n % 2 == 0 else n + 1 | 8a0e3263c2a4853c25361fda434c88a5f6c45a91 | 3,597,785 |
def get_statements(s, relations=None, t=None, keywords=None, types=None, pageNumber=None, pageSize=None): # noqa: E501
"""get_statements
Given a specified set of [CURIE-encoded](https://www.w3.org/TR/curie/) 'source' ('s') concept identifiers, retrieves a paged list of relationship statements... | 08d2fa01ae7ee9f2644463ae5ffb22e37d5b3057 | 3,597,786 |
from datetime import datetime
def parse_traktor_sheet(file):
""" Extract a list of (track, time) tuples from Traktor sheet file. """
tracks = []
with open(file, 'r') as f:
data = bs4.BeautifulSoup(f)
for entry in data.find_all('tr')[1:]:
meta = entry.find_all('td')
... | 63bd5ff62e46ea92c232bef01b8d66f2e9d2271e | 3,597,787 |
def change_password():
"""Show form to update user password.
Requires confirming current password.
"""
form = PasswordResetForm()
if form.validate_on_submit():
# Update user
current_user.password = crypto_manager.hash(form.password.data)
try:
correct = True
... | f82898babdb9e1b3473cac31730d235aafef6937 | 3,597,788 |
async def async_api_set_target_temp(hass, config, directive, context):
"""Process a set target temperature request."""
entity = directive.entity
min_temp = entity.attributes.get(climate.ATTR_MIN_TEMP)
max_temp = entity.attributes.get(climate.ATTR_MAX_TEMP)
unit = hass.config.units.temperature_unit
... | 02dc3af0978bf58178dba6ccaf921f869c483f49 | 3,597,789 |
from typing import List
def get_parameter_names(model: pyhf.pdf.Model) -> List[str]:
"""Gets the pretty labels of all fit parameters. Expands gammas using indices.
Args:
model (pyhf.pdf.Model): HistFactory model in pyhf format
Returns:
List[str]: list of pretty names for fit params
"... | b4db001e5f72410ef65ff8b6c4c0113957243232 | 3,597,791 |
import logging
def _LoadResource(path):
"""Load the resource at given path.
Args:
path: a string resource path.
Returns:
The contents of that resource.
Raises:
ValueError: If the path is not set up correctly.
IOError: If the path is not found, or the resource can't be opened.
"""
try:
... | 73b5e318214fe44e9de2af251a4e58e7e5ef0376 | 3,597,792 |
def larImage(shape):
""" Compute vertices and skeletons of an image of given shape """
imageVerts = larImageVerts(shape)
skeletons = gridSkeletons(list(shape))
return imageVerts, skeletons | 34f9ba120bf5ed9ea40ee1e8ed28644f1a1a0d3c | 3,597,793 |
import random
def valid_add(gene_info, individual):
"""Based on gene info and current individual, return a valid index to add
to an individual.
"""
return random.choice(list(set(range(0, gene_info.gene_count))
- individual)) | bc02ea8d35175ebeb91caf47717bb4d6d8202119 | 3,597,795 |
def NanosecondParameter(default, base=IntParameter, **kwargs):
"""Adds a nanosecond parameter.
Args:
default (int or float): Default value.
base (optional, type): IntParameter or FloatParameter.
Default: IntParameter
"""
return base(default, unit="ns", **kwargs) | 5e18d3bb7230c2d8af843c626fb538c5866e515e | 3,597,796 |
from datetime import datetime
def json_serialize(obj):
"""JSON serializer for objects not serializable by default json code"""
if isinstance(obj, (datetime, date)):
return obj.isoformat()
if isinstance(obj, (UUID)):
return str(obj)
raise TypeError("Type %s not serializable" % type(obj... | 260a787488ce3020391fa9c11125f57fde250795 | 3,597,797 |
from datetime import datetime
def get_observations_data_sat(iod_object_data, inds):
"""Extract three ra/dec observations from IOD observation data file.
Args:
iod_object_data (string): file path to sat tracking observation data of object
inds (int array): indices of requested data
... | 71d46e2430f9fb07763f02241abd06afd5599a63 | 3,597,798 |
import threading
def terminate_threads( func ):
"""Kills all worker threads the method has created by sending the quit signal.
This takes over in case of an error in the main function"""
def wrapper(*args, **kwargs):
cur_threads = set(threading.enumerate())
try:
return func(*args, **kwargs)
finally:
do... | d9d34ed94cbf173edad4e1f09998527060956f2e | 3,597,799 |
import requests
import time
def get_categories_from_ebay():
"""
Fetch all categories using eBay api.
Note: This is slightly inefficient the payload is parsed into an ordered dict,
then into composable objects. This was done to help structure data.
:returns: EBayCategoriesDto
"""
request =... | be30bceca433e608c78865f527edd87d29122165 | 3,597,800 |
def create_user(fullname, username, password):
"""
Function to create a new user account
"""
new_user = User(fullname, username, password)
return new_user | 3bb7a72124d60547a16043cde06587a33759ec8d | 3,597,801 |
from typing import Any
def serialise(obj: Any, no_head: bool = False) -> dict:
"""Takes any non-primitive object and serialises it into a dict.
Arguments:
obj(Any): Any non primitive object.
no_head(bool): Will not specify the module and class of the object when True.
Returns:
dict... | 80f306e4fea637bda548c6292d2d38ecba641af8 | 3,597,803 |
def area_of_sector(r, a):
"""A function that calculates the area of a sector in a circle:
angle/360 * \u03C0 * (r squared)
Parameters
----------
r: int or float
The radius in the equation.
a: int or float
The angle in the equation.
Returns
-------
Float
a... | a9737eb1e40dbf3e89a885fe6517463f7151e7d4 | 3,597,804 |
def process_group_auth(request, openid_teams):
"""Returns True if access granted, False if denied and Response
object if not enough authentication information available and
user should authenticate first (by following that Response).
"""
if not openid_teams:
return T... | 1a15adba6e4d19e83acc7772eb0d8d46dbf876fb | 3,597,805 |
def elslib_ConeParameters(*args):
"""
* parametrization P (U, V) = Location + V * ZDirection + (Radius + V * Tan (SemiAngle)) * (Cos(U) * XDirection + Sin(U) * YDirection)
:param Pos:
:type Pos: gp_Ax3
:param Radius:
:type Radius: float
:param SAngle:
:type SAngle: float
:param P:
... | 5791ee9682ff6bd10938c7cc8dac26c371a7ba1b | 3,597,807 |
from typing import Optional
def command_flag(doc: str, shortname: Optional[str] = None) -> bool:
"""Define a command line flag.
The corresponding option is set to true if it is passed as a command line
option. This is similar to :func:`switch_opt`, except the option is not
available from config file... | 347ba95fd396aae28b3e63ddea7090930477a867 | 3,597,808 |
def next_random_integer(size_in_bits):
"""
Args:
size_in_bits (int): used to specify the size in bits of the random integer
Returns:
int: random integer
Raises:
ValueError: if the specified size in bits is < 0
"""
if size_in_bits < 0:
raise ValueError(f'size in ... | 271799bf6b49f78ecca52221b85f3a0c9985116b | 3,597,810 |
def _multi_stack_worker(args):
"""
Worker to stack sources using multiprocessing
"""
x,y = args
result = stack_source(gbl_imgs, x, y,
gbl_src_shape, gbl_ref_index, gbl_tx_solutions,
gbl_dqmasks, combine_method=gbl_combine_method,
show_plots=False)
return result | 49b20ee37f9e278e0e3a6d6a4724a0a0d512e811 | 3,597,811 |
def version_view(request, package_name):
"""Return a single installed version."""
if package_name not in ALLOWED_PACKAGE_NAMES:
return HttpResponseForbidden('querying package version is not allowed')
version_dict = {'version': get_version(package_name)}
return get_response(request, version_dict... | cd5963c65f2a9784a2cddef90386b00fb11ee500 | 3,597,813 |
def reality_check(A0):
"""
This function takes an agent-class A0 and outputs an agent-class
A0_RC whose instances are the reality-checks of instances of A0.
See Section 5 of "Extending Environments To Measure Self-Reflection
In Reinforcement Learning". In that paper, it is hypothesized that
the reality chec... | cbf699b2995e23aca4924891c044ec6e26817a30 | 3,597,814 |
import re
def get_channels(channels_data):
"""Gets data with channel names from the input string."""
channel_str_regexp = r'CHANNEL\([^)]*\)'
result = re.findall(channel_str_regexp, channels_data)
return result | 56978c3936c1f313c1099d86fa506ea2c3cdeb10 | 3,597,815 |
def ignore_if_new_record_is_dda_and_better_is_available(marc_record, bib_source_of_input, predicate_vectors,
output_handler):
"""
:param marc_record:
:param bib_source_of_input: BibSource
:type predicate_vectors: Dict[Record, PredicateVector]
... | 5c09c7f79faf4465f16e240b7e9a9fe459468ca9 | 3,597,816 |
def collect_optional_attributes(obj, prefix: str = '', disable_omitting_optional: bool = False,
enable_flattening_nested_params: bool = False):
"""
Collect all optional attributes from protobuf message
Args:
attrs: dictionary with attributes
obj: protobuf mess... | 157f5ae5e394f6d3cf2e5384981ab4ff13a962cf | 3,597,817 |
import csv
def sniff_dialect(sample):
"""
A functional version of ``csv.Sniffer().sniff``, that extends the
list of possible delimiters to include some seen in the wild.
"""
try:
dialect = csv.Sniffer().sniff(sample, POSSIBLE_DELIMITERS)
except:
dialect = None
return diale... | 7590c5320a7ccc98cf04af37a5d8858374e36697 | 3,597,818 |
def parse_time_trigger_string(trigger_frequency):
"""
:param trigger_frequency: human-readable and editable string in one of two formats:
- 'at Day_of_Week-HH:MM, ..., Day_of_Week-HH:MM'
- 'every NNN'
:return: return tuple (parsed_trigger_frequency, timer_klass)
"""
# replace multiple spac... | 8083bc3b80e5537ac926bcaa99fde0f5557a1e08 | 3,597,819 |
def bdev_pmem_create_pool(client, pmem_file, num_blocks, block_size):
"""Create pmem pool at specified path.
Args:
pmem_file: path at which to create pmem pool
num_blocks: number of blocks for created pmem pool file
block_size: block size for pmem pool file
"""
params = {'pmem_fi... | f8851fb3d6472751d213ca4b7c4c1d59915e929c | 3,597,820 |
import functools
def receive_kwargs_as_dict(func):
"""A decorator that recieves a dict and passes the kwargs to wrapped func.
It's very useful to use for spark functions:
@receive_kwargs_as_dict
def myfunc(a, b):
return a > 1
print myfunc({'a': 4, 'b': 6})
sc.para... | d74ed4d7f66ae686e816a5dbfe3339478f6035f5 | 3,597,821 |
def callhome_smtp_update(handle, host, port="25", **kwargs):
"""
Updates the SMTP server for callhome
Args:
handle (UcsHandle)
host (string): ip address of SMTP server
port (string): port of SMTP server
**kwargs: Any additional key-value pair of managed object(MO)'s
... | 8dbccd1b65523621537183821b4f8b2115dc2c0e | 3,597,822 |
from datetime import datetime
import pytz
def now_iso_time(zulu_frmt=True):
"""
Returns now time in ISO 8601 format in UTC
:param zulu_frmt: if True return zulu time format, e.g. '2020-11-26T13:51:29Z',
otherwise return string with UTC offset, e.g. '2020-11-26T13:51:29+00:00'
"""
time_now ... | 55abbdda86beeddf7d6ed5e8e95575b89d7f5071 | 3,597,823 |
def to_digits(n: int) -> [int]:
"""Returns a list containing all digits in the integer provided starting at the least significant digit and increasing to the most significant digit.
Args:
n: The integer whose digits are to be determined.
"""
result = []
if n < 0:
n = -n
elif value == 0:
result... | 17effb2d701040da241b9b77171b96a6ab7106f7 | 3,597,824 |
def _get_app_attr(name, obj, mod, is_composable):
"""returns app details for display"""
in_type = [{None: ""}.get(e, e) for e in getattr(obj, "_input_types", [])]
out_type = [{None: ""}.get(e, e) for e in getattr(obj, "_output_types", [])]
data_type = [{None: ""}.get(e, e) for e in getattr(obj, "_data_t... | ccfe9a43a0ae84158e5fb470db374066dcb240a6 | 3,597,825 |
import random
def random_transaction(nodes, amount, min_fee, fee_increment, fee_variants):
"""
Create a random transaction.
Returns (txid, hex-encoded-transaction-data, fee)
"""
from_node = random.choice(nodes)
to_node = random.choice(nodes)
fee = min_fee + fee_increment * random.randint(0... | df35a4ee0c0a8754b8e00f9d6f50044fc3de0790 | 3,597,826 |
import numbers
def _create_weights_tuple(weights):
"""
Returns a tuple with the weights provided. If a number is provided,
this is converted to a tuple with one single element.
If None is provided, this is converted to the tuple (1.,)
"""
if weights is None:
weights_tuple = (1.,)
... | 6d4006a4a88b47fb009e6f45cc654fd7642cbc6a | 3,597,827 |
def tiny():
"""Return the tiny alphanumeric File-set."""
return dcmread(TINY_ALPHA_FILESET) | b3c92dd133c2c7dad455deafc6fa56e533d13717 | 3,597,828 |
def mocked_load_image(*args):
"""
Return a Pillow image. This can be used to mock spacer.storage.load_image()
to bypass image downloading from URL, for example.
"""
return create_sample_image() | ae1b8f47fc66b2928fe21e406771d4924ad4ff75 | 3,597,829 |
def plot_profile(x, fig=None, ax=None, vars=None, trace_attrs=None):
"""
Plot a :class:`medsrtqc.core.Profile` object.
:param x: A :class:`medsrtqc.core.Profile` object
:param fig: An existing matplotlib ``Figure`` such as that returned
by ``matplotlib.pyplot.subplots()``.
:param ax: An exi... | 7a3911ca2e32658d6d8e7a7ed87fa64752c59015 | 3,597,830 |
import typing
def streamline(
fgraph: FunctionGraph,
thunks,
order,
post_thunk_old_storage=None,
no_recycling=None,
nice_errors=True,
) -> typing.Callable[[], typing.NoReturn]:
"""
WRITEME
Parameters
----------
fgraph
thunks
The list of program instructions.
... | 0b52c3b6264aab15d2d2866cf2e1f05af35952e5 | 3,597,831 |
def threshold_quian(signal, threshold):
"""
Calculate threshold by Quian.
Parameters
----------
signal: numpy array
1D signal for threshold determination
threshold: float
Number of estimated noise SD above the mean
Returns
-------
ths_value: float
Value of t... | 7dd319e766a4e9f4eb4abd7d31b09b4c62447d76 | 3,597,833 |
def timestamps_signal_clip(timestamps, signal, timestep_min=980.0,
timestep_max=2000.0, plot=True):
"""Clip the interval of the signal to a given time window.
"""
time_window_idx = np.logical_and(timestamps >= timestep_min,
timestamps <= timest... | 91378c476205515fc66723c85a09608f5af839df | 3,597,834 |
import math
def fnCarts_to_LatLon(R):
"""
function which converts ECEF position vectors to latitude and longitude
Based on rvtolatlong.m in Richard Rieber's orbital library on mathwork.com
Note that this is only suitable for groundtrack visualization, not rigorous
calculations.
Date: 18 ... | 8c88bddd1a52c6cbe158b0eb8185d667c6b8ded6 | 3,597,835 |
def generate_key(seed):
"""generate a key from a seed
Args:
a seed in plain text
Returns:
a signing key
Raises:
None
"""
ring = PRNG(seed)
sk = SigningKey.generate(entropy=ring, curve=SECP256k1)
return sk | ab074e0fd33cf67dfc069f3b438dbf808018e04b | 3,597,836 |
def _create_dense_nn_model(vector_size=40,
dense_width=128,
optimizer='rmsprop',
learn_rate_mult=1.0,
regularization=0.01,
verbose=1):
"""Return callable lstm model.
Returns
... | 2a8e73295c8a01d2499264837aced25ad88e0ef3 | 3,597,838 |
def process_worker(data):
"""
the worker function supposed to read process the pdf data.
process worker accepts data from an already processed PDF and
then removes the stopwords.
"""
d = None
try:
d = remove_stop_words(data)
except AttributeError:
pass
except Exceptio... | 5420776e9e156a20fb8caa78b66053d978691a12 | 3,597,839 |
import functools
def _DeviceMethod(device_id):
"""Decorator that checks if the device exists.
Args:
device_id: The device ID.
"""
def _ActualDecorator(func):
@functools.wraps(func)
def wrapper(instance, *args, **kwargs):
if not instance.HasDevice(device_id):
raise DriverError('There... | 53c1bd56a8678236fde10fe00037623aca1b94ce | 3,597,840 |
from ._array_object import Array
from typing import Optional
def ones_like(
x: Array, /, *, dtype: Optional[Dtype] = None, device: Optional[Device] = None
) -> Array:
"""
Array API compatible wrapper for :py:func:`np.ones_like <numpy.ones_like>`.
See its docstring for more information.
"""
_... | 844857230927cadb817ce7d0e1d9094b9c212ca3 | 3,597,841 |
def root():
"""Base view."""
response = ''.join(map(lambda x: str(x) + '\n', get_data()))
return response | d6415e906c964d1e857b3dfb44438e30b64d7345 | 3,597,842 |
from datetime import datetime
def verify():
""" Save verified checklist """
database = DataProvider()
data = dict()
for key in request.form:
data[key] = request.form[key]
uid = data['uid']
obj = first_or_default(database.checklists, lambda x: x.uid == uid)
obj.update(data)
obj.... | ad0885a9d4f831e59e5a29a5a399e57e19ed9079 | 3,597,843 |
def _handle_regularizer(literal):
"""Construct regularizer from string literal
Parameters
----------
literal : str. E.g. '(0.1, 0)'
"""
literal = literal.strip()
if not literal:
return None
l1, l2 = literal_eval(literal)
if not l1 and not l2:
return None
if l1... | d11c0a86c81cbf9f04bee20298990d55a0e240e6 | 3,597,844 |
def nasa_polynomial(output_str):
""" Parse the NASA polynomial from the PAC99 output file.
:param output_str: string for the output file
:type output_str: str
:rtype: str
"""
lines = output_str.splitlines()
return '\n'.join([lines[i] for i in range(11)]) | cf02c398ac54c40d814bf649fec2b7d3079a01c7 | 3,597,845 |
import torch
def compareParams(params1,angles1,params2,angles2,device):
"""Method to checking the minimal distance between initialized filters and learned ones
Euclidean distances are calculated between each filter for parameters other than orientations
for orientations, we calculate the arc between ... | be65b2c1dd84242cc6045d4bfbcc33a8b3d383a6 | 3,597,846 |
from typing import List
import random
def least_squares_fit(xs: List[Vector], ys: List[float], learning_rate: float = 0.001, num_steps: int = 1000, batch_size: int = 1) -> Vector:
"""
Find the theta that minimizes the sum of squared errors assuming the model y = dot(x, theta)
"""
# start with a random... | 3f3a642e6e2fa41bb637126fdfc8a20e14a9bb2d | 3,597,847 |
def get_kube_sku_completion_list(cmd, prefix, namespace): # pylint: disable=unused-argument
"""
Return the VM sizes allowed by AKS, or 'ANY'
"""
return get_vm_size_completion_list(cmd, prefix, namespace) & set(KUBE_DEFAULT_SKU) | 4733e0792eee942f2eaa3980455de76fc01cbdaf | 3,597,848 |
from typing import List
import time
def create_application_registration(
onefuzz_instance_name: str, name: str, approle: OnefuzzAppRole, subscription_id: str
) -> Application:
"""Create an application registration"""
client = get_graph_client(subscription_id)
apps: List[Application] = list(
c... | b0d70c9434ac4353cbf40db02e584f8d6663a071 | 3,597,849 |
import torch
def get_metrics(pred_scores: torch.Tensor,
true_idx: torch.Tensor,
k_values: torch.Tensor):
"""Calculates mean number of hits@k. Higher values are ranked first.
Args:
pred_scores: (B, N) tensor of prediction values where B is batch size
and N n... | f0c21fbb993805222f2b84fcc6644868211a95b5 | 3,597,851 |
import re
def clean_text(s):
""" Remove non alphabetic characters. E.g. 'B:a,n+a1n$a' becomes 'Banana' """
s = re.sub("[^a-z A-Z _]", "", s)
s = s.replace(' n ', ' ')
return s.strip().lower() | ab18429927bbca362801ec815934aa8dc9a106e9 | 3,597,852 |
import numpy
def radar_constraints_to_loss_fn(radar_tensor, list_of_layer_operation_dicts):
"""Converts radar constraints to loss function.
E = number of examples
M = number of rows in grid
N = number of columns in grid
C = number of radar channels
:param radar_tensor: E-by-M-by-N-by-C Keras... | d5d5c07b995f0fb3712066af24ed269ab935e905 | 3,597,853 |
def add_comment_form():
"""Shows add comment form"""
return """
<h1>Add Comment </h1>
<form method="POST">
<input type='text' placeholder='comment' name='comment'/>
<input type='text' placeholder='username' name='username'/>
<button>Submit</button>
</form>
""" | e6b1fe99be3a4c43f58ad093b749db73f80eae89 | 3,597,854 |
from typing import Tuple
def pad_1d(tensor: Tensor, pad_width: Tuple[int, int], value: float = 0.0) -> Tensor:
"""
Function applies padding to a given 1d tensor (batch size, *, features), * various dimension
:param tensor: (Tensor) Input tensor of shape (batch size, *, features)
:param pad_width: (Tup... | 9a37550806837f418b8210e81c5ae5afd2c94813 | 3,597,855 |
def rowSum(val, colPointer, rowIndices, norm = False):
"""
[Added 17/10/2018]
Computes rowSum**2 for sparse matrix efficiently, instead of using einsum
"""
n = len(rowIndices)-1
S = zeros(n, dtype = val.dtype)
for i in range(n):
s = 0
l = rowIndices[i]
r = rowIndices[i+1]
b = l
for j in range(r-l):
... | 9452127328641762c069b006973633499780eb0e | 3,597,856 |
def fake_upload_endpoint():
"""
These endpoints have return code based behavior and therefore require a 500 error to "work"
correctly.
"""
return abort(500) | e2af700cdc4d610eeb761d26b7cce80f28243848 | 3,597,858 |
import math
import random
def random_crop(img, size, settings, scale=None, ratio=None):
""" random_crop """
lower_scale = settings.lower_scale
lower_ratio = settings.lower_ratio
upper_ratio = settings.upper_ratio
scale = [lower_scale, 1.0] if scale is None else scale
ratio = [lower_ratio, uppe... | 7803643f77c45e32458da6c8b11be2715f01a74e | 3,597,859 |
def insert( employee_id, newInterval, date_time) :
"""Inserts a new interval and assigns room id"""
intervals = date_intervals[date_time]
unavailable_rooms = set()
not_overlapped = False
stack = []
i = 0
#check the overlapping intervals with the newInterval
new_room_id = 1
while i < len(inte... | 65d5d72fd329814c9d0807f10a5ae0a80b15f269 | 3,597,860 |
import random
def getBirthdays(numberOfBirthdays):
"""Returns a list of birthday dates."""
birthdays = []
for i in range(numberOfBirthdays):
dayOfYear = random.randint(1, 365)
if dayOfYear > 334:
month = 'Dec'
day = dayOfYear - 334
elif dayOfYear > 304:
... | 138d7cb8811c03ef7061ed271ff60ac45bdf52b7 | 3,597,861 |
def list_machines(request):
"""
Tags: machines
---
Gets machines and their metadata from all clouds.
Check Permissions take place in filter_list_machines.
READ permission required on cloud.
READ permission required on location.
READ permission required on machine.
"""
auth_contex... | 5d5b1b076b2690df5a84cbfa47a23b65c6c840cc | 3,597,862 |
def get_R_from_axis(angle, axis):
"""
left hand rule
"""
if axis == 'Z':
R = np.array([[cos(angle), sin(angle), 0],
[-sin(angle), cos(angle), 0],
[0, 0, 1]])
elif axis == 'Y':
R = np.array([[cos(angle), 0, -sin(angle)],
[... | 4fe827520de94ab433e4f5241e7b5d9dd0d08d99 | 3,597,863 |
def match_format(dic):
"""
get match format
"""
loc = dic["loc_k"][0, :, 0, :]
val = dic["val_k"][0, :, :]
ans0 = np.hstack((loc, val))
ans1 = np.expand_dims(ans0, axis=0)
ret = []
ret.append(ans1)
return ret | 47674a08180304470c773a2f968b3e0bf2ab2b4b | 3,597,864 |
def IsArticleURL(para):
"""该函数接收一个参数,并判断其是否是简书的文章 URL。
Args:
para (str): 需要被判断的参数
Returns:
bool: 如为 True 代表是文章 URL,为 False 则不是
"""
if para.find("http") == -1:
return False
if para.find("www.jianshu.com") == -1:
return False
if para.find("/p/") == -1:
... | 91f9878938e1799373ef928aa8ed6ea0fea1a3ca | 3,597,865 |
import six
def inject_results(query, updated_entities=None, deleted_keys=None):
"""Creates a query object that will inject changes into results.
Args:
query: The datastore_query.Query to augment
updated_entities: A list of entity_pb2.EntityProto's that have been updated
and should take priority ove... | e4d40467e3adfa7c23ca0d19200ec7acc9365e25 | 3,597,866 |
from typing import List
def harvester_pb2_as_markdown(
machine: MachineInfo,
harvester: Harvester,
plots: List[HarvesterPlot],
disks: List[Disk],
) -> str:
"""Formats a protobuf Harvester as markdown
Parameters
----------
machine : MachineInfo
info about the machine including ... | d6776e5c1c90cc9ee36afaceb5f2e24816538559 | 3,597,867 |
def all_products_for_category(parser, token):
"""
Usage:
1. {% all_products_for_category as varname %}
2. {% all_products_for_category for slug_var as varname %}
3. {% all_products_for_category for "slug" as varname %}
Sets the variable *varname* in the context to a list of all products that... | ee8395f8a8ede34ed555e6eea14d7e6db42b6f5b | 3,597,869 |
from OpenSSL import crypto
def get_automation_certificate(name):
""" Returns an automation certificate in PKCS12 bytes """
certificate = _get_asset(_KEY_CERTIFICATE, name)
pks12_cert = crypto.load_pkcs12(open(certificate[_KEY_CERTPATH], 'rb').read(),
certificate[_KEY_PA... | e73c644aad8fbf6db41d21475233eb42e5989624 | 3,597,870 |
import pandas
import six
from operator import add
from operator import mul
def lmoma(model, reference=None, cache=None, reactions=None, *args, **kwargs):
"""Linear Minimization Of Metabolic Adjustment [1].
Parameters
----------
model: cobra.Model
reference: FluxDistributionResult, dict
cache:... | 5e490e01af0f5ea327b0f29b21188047325b8487 | 3,597,871 |
from typing import Optional
import copy
async def add(
app, otu_id: str, data: dict, user_id: str, isolate_id: Optional[str] = None
) -> dict:
"""
Add an isolate to an existing OTU.
:param app: the application object
:param otu_id: the id of the OTU
:param data: the isolate data
:param us... | baa024529186a1f38931a30108c20a92a673c81d | 3,597,872 |
def readCSV(name):
"""
Function name: readCVS
Description: Using pandas reads the CSV, with no headers, indicated by param and returns it
Arguments:
IN -- route to CSV file
OUT -- data object
"""
CSVdata = pd.read_csv(name, header=None, encoding='utf-8-sig')
# print(C... | 043f556c35aac6b1de88fa92c753741250b47727 | 3,597,873 |
def __get_scp_command():
""" get scp command.
@return: scp command
"""
global ssh_host, ssh_port, ssh_id_file, ssh_user, conf_path, src_path
'scp -i id_file file_path user@domain:dest path'
stack = ['scp']
if ssh_id_file is not None:
fmt = '-i {0}'.format(ssh_id_file)
sta... | 81b0eb68fbe6c2eadd2b2f8855c9d2f59afc0f6d | 3,597,874 |
def _validate_lod(lod, tensor_height=-1):
"""Check whether the input length-based lod info is valid.
There are several things to check:
1. lod should be a list of lists. Empty list is fine.
2. The length of each sublist (a lod level) should be at least one.
3. Each element in each lod level should ... | c9717eb8668b03e4da75abdf24003e9458eb9783 | 3,597,875 |
def generate_sensors(num_sensors=7, spatial_dim=2):
"""
Generate sensor locations.
Input:
num_sensors: The number of sensors.
spatial_dim: The spatial dimension.
Output:
sensor_loc: num_sensors * spatial_dim numpy array.
"""
sensor_loc = 100 * np.random.randn(num_sensors, spatial_dim... | c20da77f28cec9a5d339a203c9a68e87e4437c38 | 3,597,876 |
import socket
def is_address_accessible(address):
"""Check if address is accessible or down"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
is_accessible = s.connect_ex(address) == 0
s.close()
return is_accessible | bfbb92fda908ec6ffec95613e90c408b0612d753 | 3,597,877 |
def sort_one_candle_peaks(peak_df, invert=True):
"""
对同一个k线的极值点进行排序
:param peak_df: pd.DataFrame columns=[datetime, peak, type] 要将datetime设置为index
:param invert: default True, 按 high, high和low, low排列
:return: pd.DataFrame columns=[datetime, peak, type]
"""
# 检测输入类型
assert isinstance(peak... | b2736983b41e6237258c8ecd9ad3adffad33c068 | 3,597,878 |
def tagcloud(threshold=0, maxsize=1.75, minsize=.75):
"""usage:
-threshold: Tag usage less than the threshold is excluded from
being displayed. A value of 0 displays all tags.
-maxsize: max desired CSS font-size in em units
-minsize: min desired CSS font-size in em units
Ret... | 8334993c06b79aa3e070200635e6003863a0568c | 3,597,879 |
def s_ganador():
"""Ejecuta sonido ganar.wav"""
try:
ganar_obj = sa.WaveObject.from_wave_file('Sonidos/ganar.wav')
ganar_play = ganar_obj.play()
except:
pass
else:
return ganar_play | cee066201adf68d6d5f7dc46f343b03cf1d92155 | 3,597,880 |
def test(request):
"""
第一个参数必须是httprequest类型的对象,包含了所有请求信息
并且返回值是一个httpresponse的对象,包含给请求者的相应信息,或者交给render其返回值就是一个response对象
"""
# return HttpResponse('Hello World...')
# context是一个字典,用于封装数据库查询后的结果
context = {
'key': "这是数据库查询的数据..."
}
response = render(request, 'Book... | 615428067699cc96ed6034aa0ae69c0c8e1ca68b | 3,597,881 |
def solve_ss(s_H,s_K,g,n,alpha,phi,delta):
"""args:
sh (float): Investments in human capital
sk float): Investments in physical capital
g (float): Growth in technology
n (float): Growth in labour force
alpha (float): Return on physical capital
phi (float): Return on human ca... | 61836f9cc850a77c03aa7b42bb82465e9aa50481 | 3,597,882 |
def comput_mmi(area_a, area_b, intersect):
"""
计算MMI,2018.11.23 add
:param area_a: 实例文本a的mask的面积
:param area_b: 实例文本b的mask的面积
:param intersect: 实例文本a和实例文本b的相交面积
:return:
"""
eps = 1e-5
if area_a == 0 or area_b == 0:
area_a += eps
area_b += eps
print("the area ... | 7076fa572e8fbc8ac38ab905663fa58fb804d906 | 3,597,883 |
def check_and_count_models(hyper_params, params_zero_one, params_more_than_zero, params_more_than_one,
params_zero_positive, max_grid_model):
"""
This function will look at the hyper-parameter space set in hyper_params, generate a new hyper_param space that
will contain a smaller ... | f9cecb8d47dafde166b206fc36e90cf3f5486f7f | 3,597,884 |
def rpy2tr(roll, pitch=None, yaw=None):
"""
Rotation from RPY angles.
Two call forms:
- R = rpy2tr(r, p, y)
- R = rpy2tr([r, p, y])
These correspond to rotations about the Z, Y, X axes respectively.
@type roll: number or list/array/matrix of angles
@param roll: roll angle, ... | bd9a61799ea6d9348706e9951866c5f62e365f86 | 3,597,887 |
def bfs(graph, start):
"""
Finds the shortest string using BFS
Args:
graph (DFA): The DFA states
start (DFA state): The DFA initial state
Returns:
str: The shortest string
"""
# maintain a queue of paths
queue = []
visited = []
# maintain a queue of nodes
... | 1f339238107a1dbd7528b17a5fe5105d5da850e4 | 3,597,888 |
def dominant_ratio_per_remaining_node(g):
"""
A Faire:
- Ecrire une fonction qui retourne le dominant du graphe non dirigé g passé en parametre.
- cette fonction doit retourner la liste des noeuds d'un petit dominant de g
:param g: le graphe est donné dans le format networkx... | fd864a8cffbd282725889618864133f636a6895f | 3,597,889 |
def lcs8_bit(b: int, s: int):
"""Shift 8-bit quantity `b` `s` bits to the left."""
return ((b << s) | (b >> (8 - s))) & 0xff | 087efe74fac9f700886491b8e7879d152ddc99e2 | 3,597,890 |
def is_config_deploy_forced_for_bundle(
bundle_name, yaml_file=None, fatal=True):
"""Ask the config if the bundle_name should be deploy_forced.
In the config file for the tests, the tests_options.force_deploy option
may be used to force the juju deploy; e.g. the bundle combination isn't
officia... | 86808ac2742bb01ed0a538a15c835aba0f6e5642 | 3,597,891 |
def publish(request):
""" AJAX method to publish user theme """
if request.method != 'POST':
return HttpResponse("FAIL", mimetype='text/plain')
theme_id = request.POST.get('theme_id')
user = auth.get_user(request)
user_theme = UserTheme.objects.get(id=theme_id)
user_theme.user = user
... | 9574f43e2170505c7f222a8916af8949dcfe77ae | 3,597,892 |
def get_fitness(target: np.ndarray, img_vector: np.ndarray) -> float:
"""Calculate fitness of specimen.
Args:
target: Original image converted to NumPy Array
img_vector: Specimen NumPy Array
Returns:
Fitness of specimen
"""
return distance.euclidean(target, img_vector) | bddc1f0086224abd5b73020f35779dd04585e500 | 3,597,893 |
def gather_install_list(manifest):
"""Gather the list of install items."""
# First, swap out for our cache dir
old_managed = prefs.pref('ManagedInstallDir')
prefs.set_pref('ManagedInstallDir', CACHE)
# Process the manifest for managed_installs
(cataloglist, managed_installs) = obtain_manifest(ma... | 45e2dbaf0be5b82a1257ba7434d48ce1fa101f9e | 3,597,894 |
def escape_string(string):
""" Escape a string for use in Gerrit commands.
Adds necessary escapes and surrounding double quotes to a
string so that it can be passed to any of the Gerrit commands
that require double-quoted strings.
"""
result = string
result = result.replace('\\', '\\\\')
... | 2c3b16b67377de3cba821cc405c0c5e24943b995 | 3,597,895 |
import importlib
def import_consumer(value):
"""Pass in a string in the format of foo.Bar, foo.bar.Baz, foo.bar.baz.Qux
and it will return a handle to the class
:param str value: The consumer class in module.Consumer format
:return: tuple(Class, str)
"""
parts = value.split('.')
import_... | c63d57614d7be9cfbda35d25b6634ffaec938288 | 3,597,896 |
def node2link(g):
"""
Convert graph nodes to links
"""
mapping = dict()
result = nx.Graph()
# Create a link for each node
n = 0
for u, v, data in g.edges(data=True):
result.add_node(n, **data)
mapping[(u, v)] = n
mapping[(v, u)] = n
n += 1
# Create edg... | 2fdd2f667c13386df13274ca2107f96b934cb5c2 | 3,597,897 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.