content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_should_raise_if_invalid_syntax_dvc_meta():
"""
Test meta check method raise if invalid syntax meta
"""
with pytest.raises(MlVToolException):
DocstringDvc.meta_checks(params={'p1': 'str'},
args=['keyword', 'p1', 'extra_param'],
... | 5,295,300 |
def findsource(object, cache_key):
"""
findsource that does not cache
"""
file = inspect.getsourcefile(object)
if not file:
raise IOError('source code not available')
lines = None
with open(file) as f:
lines = f.readlines()
if not lines:
raise IOError('could not ... | 5,295,301 |
def parse_from_file(
root_processor, # type: RootProcessor
xml_file_path, # type: Text
encoding='utf-8' # type: Text
):
# type: (...) -> Any
"""
Parse the XML file using the processor starting from the root of the document.
:param root_processor: Root processor of the XML doc... | 5,295,302 |
def plotAreaXYZ(xyz, dem, show=True, save=None):
"""Plot figure with image overlayed with xyz coordinates representing
either areas or line features.
:param xyz: Input xyz coordinates for plotting
:type xyz: arr
:param dem: Underlying DEM for plotting over
:type dem: :class... | 5,295,303 |
def start(nick: str, vlc_dict:dict):
"""Consigue la configuracion de partida y crea la ventana dependiendo de
lo elegido por el usuario
Args:
nick (str): El nick del jugador
"""
user= check_config(nick)
game_window, value_matrix,help_list = build(nick,user["config"])
game_number=st... | 5,295,304 |
def bb(a, b, c):
"""ナップザック問題を分枝限定法で解く
:param np.array a: 制約条件の係数
:param int b: 制約条件の値
:param np.array c: 目的関数の係数
:return:
"""
answer_temp = greedy(a, b, c)
# スタックに(aの残り, bの残り, cの残り, 答えの先頭部分)という形式で部分問題を登録する
stack = [(a, b, c, np.array([]))]
while stack:
print('---------... | 5,295,305 |
def is_lock_pending(
end_state: NettingChannelEndState,
secrethash: typing.SecretHash,
) -> bool:
"""True if the `secrethash` corresponds to a lock that is pending to be claimed
and didn't expire.
"""
return (
secrethash in end_state.secrethashes_to_lockedlocks or
secreth... | 5,295,306 |
def NCBITAXON(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "2021-12-14", **kwargs
) -> Graph:
... | 5,295,307 |
def gather_contact_details():
"""
**gather_contact_details**
obtains contact details from request. args
:return:
"""
names = request.args.get('names')
email = request.args.get('email')
cell = request.args.get('cell')
subject = request.args.get('subject')
message = req... | 5,295,308 |
def dave4vm(mag, window_size, threshold=1.0):
""" DAVE4VM - Differential Affine Velocity Estimator for Vector Magnetograms
Parameters
---------
MAG :
structure of vector magnetic field measurements',
MAG.DX :
X spatial scale (used to compute B?X),
... | 5,295,309 |
def test_check_version_success(mock_get, mock_cosmos):
"""
Test _check_3dt_version(), should not fail.
"""
mock_cosmos().enabled.return_value = True
m = mock.MagicMock()
m.json.return_value = {
'capabilities': [{'name': 'SUPPORT_CLUSTER_REPORT'}]
}
mock_get.return_value = m
... | 5,295,310 |
def osm_shp_from_geocode(
query,
filepath,
which_result=None,
by_osmid=False,
buffer_dist=None,
):
"""Download place(s) by name or ID from the Nominatim API as a shapefile.
Args:
query (str | dict | list): Query string(s) or structured dict(s) to geocode.
filepath (str): Fil... | 5,295,311 |
def read_corpus():
"""读取语料,每行一个json
"""
while True:
with open(data_file) as f:
for l in f:
arr = l.strip().split('\t')
if len(arr) != 3:
try:
if arr[2].strip() != '0':
res = {}
... | 5,295,312 |
def test_checkpoint_new_on_context_with_1_datasources_with_no_datasource_option_prompts_user_and_generates_runnable_tap_file(
caplog, empty_data_context, filesystem_csv
):
"""
We call the "checkpoint new" command on a data context that has 1 datasources
configured.
The command should:
- NOT pro... | 5,295,313 |
def quit():
"""Break out of PicoSystem main loop.""" | 5,295,314 |
def test_scheme_15():
"""SCHEME 15:
Rule 11: For Mixed Aromatic/Non-aromatic Ring Systems, Retain Non-aromatic Rings with Priority
Aromatic systems are extremely frequent, and benzene is the most frequent ring in practically all data sets.
In order to avoid too many compounds to be linked to benzene a... | 5,295,315 |
def score_o_gram(ax: matplotlib.axes.Axes,
scores: Dict[str, Collection[float]],
t_limits: Tuple[float, float]) -> None:
"""Plots classification scores as a "score-o-gram" image.
Each row plots scores for one label, and the horizontal dimension is time.
Args:
ax: Matplotlib... | 5,295,316 |
def export_colours(profile_list, colour_preset_lookup, output_directory):
"""Write the profile and preset colour schemes to the output directory.
"""
if profile_list:
for profile_lookup in profile_list:
write_colour_plist(profile_lookup, profile_lookup['Name'], 'profile', output_directo... | 5,295,317 |
def clear_expired_alerts():
"""
Iterate over all devices with active alerts and check if the alert is expired,
if so the device is updated to clear the alert.
"""
print 'Checking for expired alerts & update affected devices'
try:
devices = m2x_client.devices_search(streams={'weather_ale... | 5,295,318 |
def publish(sensors):
"""Publish a dictionary of sensor keys amd values using MQTT."""
# Check if MQTT is not connected to a broker or the sensor list is empty
if 'mqtt_client' not in _LOCAL_VARS or not sensors:
return
# Separate out the sensor dictionaries
for original_sensor in sensors:
... | 5,295,319 |
def init(ctx, conf_json):
"""
Start a workflow package project with necessary scaffolds.
"""
project = ctx.obj.get('PROJECT')
if project.root:
click.echo(f"Already under a project directory: {project.root}")
ctx.abort()
init_cmd(project, conf_json) | 5,295,320 |
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: entity_platform.AddEntitiesCallback,
) -> None:
"""Set up the Modem Caller ID sensor."""
api = hass.data[DOMAIN][entry.entry_id][DATA_KEY_API]
async_add_entities(
[
PhoneModemButton(
... | 5,295,321 |
def _check_can_add(self, user, model):
""" check if the user can add the model, deferring first to
the channel if it implements can_add()
else using django's default perm check.
if it can add, then enable the widget to show the + link
"""
lookup = get_lookup(self.channel)
if hasa... | 5,295,322 |
def get_unc_directory_from_string(string):
"""
Parses a string from `UncDirectory`'s `get_auth_path` method and returns a new `UncDirectory`
object based on it. This may raise any errors that can be raised by `UncDirectory`'s
constructor.
"""
creds = None
path = string
if '@\\\\' in str... | 5,295,323 |
def start(start):
"""When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date."""
start_date = dt.datetime.strptime(start, '%Y-%m-%d')
session = Session(engine)
year_query = session.query(func.min(measurement.tobs), \
... | 5,295,324 |
def create_model(fingerprint_input, model_settings, model_architecture,
is_training):
"""Builds a model of the requested architecture compatible with the settings.
There are many possible ways of deriving predictions from a spectrogram
input, so this function provides an abstract interface for c... | 5,295,325 |
def orbit2frame(name, ref_orbit, orientation=None, center=None, bypass=False):
"""Create a frame based on a Orbit or Ephem object.
Args:
name (str): Name to give the created frame
ref_orbit (Orbit or Ephem):
orientation (str): Orientation of the created frame
bypass (bool): By-p... | 5,295,326 |
def last_version():
"""
Shows last version. Usage: fab prod show_last_version
"""
with cd(env.directory):
run('git describe --exact-match') | 5,295,327 |
def from_hex_lsb(text):
"""Decode a hex encoded fingerprint string where the bits and bytes are in LSB order
>>> from_hex_lsb('102f')
(None, '\\x08\\xf4')
>>>
Raises a ValueError if the hex string is not a multiple of 2 bytes long
or if it contains a non-hex character.
"""
return (Non... | 5,295,328 |
def get_first_char(value):
"""
Returns the first char of the given string
:param value:
:return:
"""
return value[:1] | 5,295,329 |
def load_instructions(ufilename):
"""
Expand this, maybe in the readme/docs because it's pretty much the heart and soul of the
program.
Loads a json file that describes the titlecard. In general, it'll be pairings of json
keys and values. There are two keys that are handled specially; the 'backgro... | 5,295,330 |
def dfs_search_recursive(G, src):
"""Entry to recursive Depth First Search."""
marked = {}
node_from = {}
def dfs(v):
"""Recursive DFS."""
marked[v] = True
for w in G[v]:
if not w in marked:
node_from[w] = v
dfs(w)
dfs(src)
re... | 5,295,331 |
def is_cat(filename: str) -> bool:
"""
Returns true if filename is an image of a cat.
In the dataset we are using this is indicated by the first letter of the
filename; cats are labeled with uppercase letters, dogs with lowercase ones.
"""
result = filename[0].isupper()
# print(f"File: {fil... | 5,295,332 |
def rm_user_edges(lcen, rcen, rm_slits):
"""
Remove one or more slits, as applicable
Code compares exisiting slits (which must be sycnhronized)
against the input request and removes any that match.
Args:
lcen (np.ndarray): Left traces of slit/orders
rcen (np.ndarray): Right traces ... | 5,295,333 |
def analyze_text(filename):
"""
Calculate the number of lines and characters in a file
:param filename: the name of the file to analyze
:raises: IOError: if ``filename`` does not exist or can't be read
:return: a tuple where the first element is the number of lines in the file
and the second... | 5,295,334 |
def auto_adapt_batch(train_size, val_size, batch_count_multiple=1, max_size=256):
"""
returns a suitable batch size according to train and val dataset size,
say max_size = 128, and val_size is smaller than train_size,
if val_size < 128, the batch_size1 to be returned is val_size
if 128 < val... | 5,295,335 |
def deploy_packages(session: nox.Session) -> None:
"""Deploying packages.
Args:
session (nox.Session): nox session.
"""
session.install("twine")
session.run("twine", "upload", "dist/*") | 5,295,336 |
def makedirs(*paths, **kwargs):
"""
Make directory.
If intermediate directory does not exist, create them too.
Args:
paths:
is a single part path such as `/tmp/foo` or a separated path such as
`('/tmp', 'foo')`.
mode(int):
specifies permission mode ... | 5,295,337 |
def get_model(model, feat_dim, meta):
"""Build a model specific for the given task.
Arguments:
- model: The model architecture.
- feat_dim: Feature (last hidden layer) dimension.
- meta: Meta data about the task.
Return:
- The corresponding neural network
""... | 5,295,338 |
def pascals_triangle(rows: int) -> Tuple[Tuple[int, ...], ...]:
"""Return tuple containing pascals triangle up to specified length."""
result = []
next_numbers = [1]
for _ in range(0, rows):
# move row
current_numbers = next_numbers
next_numbers = []
result.append(tuple(... | 5,295,339 |
def get_shapefiles(
data_dir: Path, shapefiles: Dict, force_download: bool = False
) -> None:
"""
Retrieve shapefiles
"""
for fname, shapefile_url in shapefiles.items():
download_path = data_dir / fname
type_of_shapefile = fname.split("Boundaries - ")[1].replace(".zip", "")
s... | 5,295,340 |
def gauss2D(valRange, size, mu, sigma):
"""
calculate 2D Gaussian on array.
Parameters
----------
valRange : int
value range to which the Gaussian will be scaled.
size : list of ints
x and y size of array.
mu : list of floats
x and y center position of Gaussian.
... | 5,295,341 |
def _version_tag(
key: str,
artifacts: Mapping[str, str],
require_artifact: bool = False,
) -> str:
"""
First, try and get the value from artifacts;
if no artifact and require_artifact, throw error
then fall back to $TAG;
then fall back to "dev"
We generally set `require_artifac... | 5,295,342 |
def test_emirp_check():
"""
>>> emirp_check(100)
It is not an Emirp
>>> emirp_check(311)
It is an Emirp!
>>> emirp_check(12721)
It is not an Emirp, palindromes don\'t count
"""
pass | 5,295,343 |
def list_results_files(path, instanceid, omittedfiles):
"""
lists the files associated with an instanceid leavuing out the omittedfiles and in ascending age.
:param path:
:param instanceid:
:param omittedfiles:
:return:
"""
files = sorted(os.listdir(os.path.join(path, instanceid)),
... | 5,295,344 |
def two_fer(name="you"):
"""Returns a string in the two-fer format."""
return "One for " + name + ", one for me." | 5,295,345 |
def insert_into_clipboard(string) -> None:
"""Insert specified string into clipboard."""
subprocess.run(['powershell', "-Command", f"Set-Clipboard -Value '{string}'"])
logging.debug(f'Inserted {string} into the clipboard.') | 5,295,346 |
def insere_randomico(lista, qtd_insercao):
"""
Insere n elementos de acordo com a quantidade passada por parametro
qtd_insercao - quantidade a ser inserida na lista
"""
for i in range(qtd_insercao):
lista.append(random.randint(1,10000))
random.shuffle(lista)
return lista | 5,295,347 |
def use_case_config(privilege=None, request_object=NoneType):
"""Class decorator that allows to attach a privilege and a request_object class
to a certain use case class
Usage:
@use_case_config(Privileges.ListStudies, ListStudiesRO)
class ListStudiesUC(UseCase):
pass
:param privilege... | 5,295,348 |
def project(ifs: IteratedFunctionSystem, point: Vec) -> Vec:
"""Project a point by repeatedly applying functions from the IFS.
:param ifs: The Iterated Function System to use for projection.
:param point: The point in the plane to repeatedly project.
:returns: A point obtained by applying random functi... | 5,295,349 |
def create_pagination(page, results_per_page, total_results):
"""Create pagination to filter results to manageable amounts."""
pagination = {}
# For UI
pagination['page'] = page
pagination['total_results'] = total_results
pagination['total_pages'] = math.ceil(total_results / results_per_page)
... | 5,295,350 |
def draw_rec_prec(rec, prec, mrec, mprec, class_name, ap):
"""
Draw plot
"""
plt.plot(rec, prec, '-o')
# add a new penultimate point to the list (mrec[-2], 0.0)
# since the last line segment (and respective area) do not affect the AP value
area_under_curve_x = mrec[:-1] + [mrec[-2]] + [mrec... | 5,295,351 |
def get_source(url):
"""Return the source of the supplied url argument"""
http = httplib2.Http()
try:
status, response = http.request(url,
headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'})
if status.status == 200:
return response
else:
return None
ex... | 5,295,352 |
def pygrep_iterator(iterator, keyword, ilen=100, ishift=0, begin=0):
""" """
ibuffer = -1
out_str = ""
maxlen = ishift + ilen
#
for line in iterator:
if keyword in line:
out_str = keyword + line.partition(keyword)[2]
ibuffer = len(out_str)
break
#... | 5,295,353 |
def func1():
"""
"""
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'サンプルデータ'
writeData(ws.cell(row=2, column=1), '伊集院', 'ddFFFF')
writeData(ws.cell(row=2, column=2), 43, 'FFFFee')
writeText(ws.cell(row=2, column=3), 54.3)
writeText(ws.cell(row=2, column=4), datetime.datetime.t... | 5,295,354 |
def sdebug(f):
"""
debugging decorator for _store functions
"""
def newf(*args, **kwds):
print('{0:20} {1:20}'.format(f.func_name, args[2]))
return f(*args, **kwds)
newf.__doc__ = f.__doc__
return newf | 5,295,355 |
def waveletCoeffs(name):
"""
Return the wavelet coefficients according to the wavelet name.
Parameters
----------
name : str
Name of wavelet. Supported values:
* '**haar**' : Haar wavelet
* '**db1**'-'**db20**' : Daubechie wavelets with different support siz... | 5,295,356 |
def get_default_gateway_linux():
"""Read the default gateway directly from /proc."""
with open("/proc/net/route") as fh:
for line in fh:
fields = line.strip().split()
if fields[1] != '00000000' or not int(fields[3], 16) & 2:
# If not default route or not RTF_GATEW... | 5,295,357 |
def find_or_update_user(id, role=None):
""" Find existing user and update role """
user = User.query.filter(User.id == id).first()
if user and role:
user.roles.append(role)
db.session.commit()
return user | 5,295,358 |
def conv_len(a, l):
"""
Function that converts a number into a bit string of given length
:param a: number to convert
:param l: length of bit string
:return: padded bit string
"""
b = bin(a)[2:]
padding = l - len(b)
b = '0' * padding + b
return b | 5,295,359 |
def finish_calibration(model, args):
"""Disable calibration and load amax for all "*_input_quantizer modules in model."""
logger.info("Loading calibrated amax")
for name, module in model.named_modules():
if name.endswith("_quantizer"):
if module._calibrator is not None:
... | 5,295,360 |
def perform(level, box, options):
"""
Args:
level (MCInfdevOldLevel): Full level to generate the village in
box (BoundingBox): Box that limits where the village can be placed
options (dict): Options given to the Filter from MCEdit2
"""
level_array = build_level_array(level, box)
build_map, surface_height_m... | 5,295,361 |
def catalog_to_mask(catalog, shape, wcs, radius=np.radians(4/60)):
"""
Convert catalog with DEC, RA values to binary point source mask.
Parameters
----------
catalog : (2, N) array
DEC and RA values (in radians) for each point source.
shape : tuple
Shape of output map.
wcs :... | 5,295,362 |
def xml_check_xsd(xml, flavor='autodetect', level='autodetect'):
"""
Validate the XML file against the XSD
:param xml: the Factur-X or Order-X XML
:type xml: string, file or etree object
:param flavor: possible values: 'factur-x', 'zugferd', 'order-x' or 'autodetect'.
Value 'zugferd' means ZUGFe... | 5,295,363 |
def get_image_as_b64(uuid, filetype='png'):
"""Gets b64 image string by uuid
:param uuid: uuid of image
:param filetype: file type to output, options are jpeg, png, or gif
:returns: b64 string of image
"""
filetype = filetype.lower()
img_format = None
if filetype == 'png':
... | 5,295,364 |
def _cost_of(rule):
"""Calculate the cost of a rule based on the number of constraints.
Rules requiring more tokens to match are made less costly and tried first.
"""
return math.log2(1 + 1 / (1 + _num_tokens_of(rule))) | 5,295,365 |
def generate_test_cohort(project,
max_size=10,
write=False,
user_interval_size=1,
rev_interval_size=7,
rev_lower_limit=0):
"""
Build a test cohort (list of UIDs) for the given project... | 5,295,366 |
def ensure_aware_datetime(dt, default_tz=UTC):
"""
Ensures that the returned datetime object is not naive.
"""
if dt.tzinfo is None:
dt = dt.replace(tzinfo=default_tz)
return dt | 5,295,367 |
def ping_target(target, timeout, count, size):
"""Ping a target and handle socket errors.
Returns:
pythonping.ResponseList
socket.error
RuntimeError
"""
try:
return pythonping.ping(
target=target,
timeout=timeout,
count=count,
... | 5,295,368 |
def validate_password(password):
"""Validates a password
Notes
-----
The valid characters for a password are:
* lowercase letters
* uppercase letters
* numbers
* special characters (e.g., !@#$%^&*()-_=+`~[]{}|;:'",<.>/?) with the
exception of a backslash
... | 5,295,369 |
def Sub(a, b):
"""
Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
:param a: operand a
:param b: operand b
:return: a - b if a - b > 0 or revert the transaction.
"""
Require(a>=b)
return a-b | 5,295,370 |
def apply_volume_reduction(event, subarray, config):
"""
Checks the volume reduction algorithm defined in the
config file, and if not None, it applies to a **calibrated**
event the volume reduction method. Modifies the event container
by applying the computed mask to the image, the waveform and the
... | 5,295,371 |
def wrap_mc_method(func, f_args, f_kwargs, return_val, funcname=None):
"""Pulls the operation and (for get) whether a key was found, on each public method."""
kvs = {}
if funcname in MC_COMMANDS:
kvs['KVOp'] = funcname
# could examine f_args for key(s) here
if funcname == 'get':
kvs[... | 5,295,372 |
def binary_accuracy(output: paddle.Tensor, target: paddle.Tensor) -> float:
"""Computes the accuracy for binary classification"""
with paddle.no_grad():
batch_size = target.shape[0] # .size(0)
pred = (output >= 0.5).t().flatten() # .view(-1)
correct = pred.eq(target.flatten()).sum()
... | 5,295,373 |
def check_iban(iban):
"""Check the syntax and the checksum of an IBAN.
Return the parts of the IBAN: Country Code, Checksum, Bank/Branch Code and
Account number.
Raise an IBANError exception if the input is not correct.
"""
err = None
code = iban[:2]
checksum = iban[2:4]
bban ... | 5,295,374 |
def best_step(x, y):
"""
Fits a step function to the data.
Returns
-------
low, high, threshold : floats
The parameters of the step function
"""
ths = x[2:-2]
scores = np.array([((y - degrau(x, y[x<th].mean(), y[x>=th].mean(), th))**2).sum() for th in ths])
th = ths[scores... | 5,295,375 |
def ln_s(source, dest, dry_run=False, clobber=True, create_dirs=False, silent=False):
"""Link file from source to destination.
Parameters
----------
source : str
Path to source file.
dest : str
Path to destination directory or destination file name.
dry_run : bool, optional
... | 5,295,376 |
def peek(buckets, max_builds=None, start_cursor=None):
"""Returns builds available for leasing in the specified |buckets|.
Builds are sorted by creation time, oldest first.
Args:
buckets (list of string): fetch only builds in any of |buckets|.
max_builds (int): maximum number of builds to return. Defaul... | 5,295,377 |
def a_raininess_oracle(timestep):
"""Mimics an external data source for raininess
Arguments
=========
timestep : int
Requires a year between 2010 and 2050
Returns
=======
raininess : int
"""
msg = "timestep {} is outside of the range [2010, 2050]".format(timestep)
asse... | 5,295,378 |
def load_model_keras(model_path):
"""
Loads Keras model.
:param model_path: Path to H5 model.
:return: Keras model.
"""
model_loaded = load_model(model_path)
return model_loaded | 5,295,379 |
def user_identity_lookup(user: User) -> str:
"""Define identity user field."""
return user.email | 5,295,380 |
def plot_data_tiled(data, normalize=False, title="", vmin=None, vmax=None, cmap="Greys_r",
save_filename=None):
"""
Save figure for input data as a tiled image
Inpus:
data: [np.ndarray] of shape:
(height, width, features) - single image
(n, height, width, features) - n images
normalize: [boo... | 5,295,381 |
def extract_entity(funct):
"""Decorate for extract entity object from request."""
@asyncio.coroutine
def async_api_entity_wrapper(hass, config, request):
"""Process a turn on request."""
entity_id = request[API_ENDPOINT]['endpointId'].replace('#', '.')
# extract state object
... | 5,295,382 |
def _value_name(value):
"""Return the name of the value."""
return '{} {}'.format(_node_name(value.node), value.label) | 5,295,383 |
def drop_schema():
"""
drops all database models.
"""
print_warning('Dropping all models...')
migration_services.drop_all() | 5,295,384 |
def shrinking_sphere(xyz, vxyz, m, delta=0.025):
"""
Compute the center of mass coordinates and velocities of a halo
using the Shrinking Sphere Method Power et al 2003.
It iterates in radii until reach a convergence given by delta
of 1% of the total number of particles while there are more than 1000... | 5,295,385 |
def test_partitioned_model_state_copies():
"""Tests whether cloning the model state properly copies all the options.
If it does not copy them, bad things can happen as the state is
mutated to build up migration state.
"""
options = dict(method=PostgresPartitioningMethod.RANGE, key=["timestamp"])
... | 5,295,386 |
def resize_image(original_img_path, resized_img_path, new_size_px):
"""
Resizes image and saves it as new file
@param original_img_path: Path of the original image
@param resized_img_path: Path for resized image
@param new_size_px: New size in pixels
@type original_img_path: str
@type resize... | 5,295,387 |
def movefiles():
"""
function to move files.
"""
data=json.loads(request.data)
parentid = data["parentid"]
filelist = data["filelist"]
if len(filelist) > 0:
try:
return update.movefiles(parentid,filelist,current_user)
except Exception as e:
print e
... | 5,295,388 |
def get_positives(scores, label, other_labels, threshold, shift = 10):
"""
:param scores:
:param label:
:param other_labels:
:param threshold:
:return:
"""
from math import ceil
avg_window_half_size = int(ceil(100 / shift))
positives = []
x = scores[:, label]
peaks = f... | 5,295,389 |
def find_folders(root: str,
file_client: FileClient) -> Tuple[List[str], Dict[str, int]]:
"""Find classes by folders under a root.
Args:
root (string): root directory of folders
Returns:
Tuple[List[str], Dict[str, int]]:
- folders: The name of sub folders under th... | 5,295,390 |
def back_test(stock):
"""
Run back testing tasks via multiprocessing
:return: None
"""
task = btasks.Task(bsm.MATrendStrategy, stock)
result = task.task()
stock_id = result.get('stock_id')
trading_days = result.get('trading_days')
total_return_rate = result.get('total_return_rate')... | 5,295,391 |
def matrix_to_homogeneous(batch: torch.Tensor) -> torch.Tensor:
"""
Transforms a given transformation matrix to a homogeneous
transformation matrix.
Args:
batch: the batch of matrices to convert [N, dim, dim]
Returns:
torch.Tensor: the converted batch of matrices
"""
if ba... | 5,295,392 |
def main():
"""Play a game of chess.
The main function of this module starts a really basic game of chess on the
commandline. Moves are input in the format 'e2e4'.
Examples:
>>> import nerdchess
>>> nerdchess.main()
What is the name of player 1?henk
With which color sho... | 5,295,393 |
def council_member(func: Callable[..., R]) -> CouncilMember[R]:
"""
a function decorator to create an appropriate member
:param func: the function to wrap
:return: a CouncilMember that will call func, ignoring council_state unless a parameter of that name exists
in func's signature
"""
sig... | 5,295,394 |
def stopService():
"""Stop the NSSM service for the SerGIS Server socket server."""
shell.ShellExecuteEx(lpVerb="runas",
lpFile="cmd",
lpParameters="/K " + NSSM_PATH + " stop " + NSSM_SERVICE_NAME,
nShow=5,
fMask... | 5,295,395 |
def setup(hass, config):
"""Setup the Buspro component. """
host = config[DOMAIN][CONF_HOST]
port = config[DOMAIN][CONF_PORT]
name = config[DOMAIN][CONF_NAME]
hass.data[DOMAIN] = "<buspro>"
#load_platform(hass, 'light', DOMAIN, {'optional': 'arguments'})
#load_platform(hass, 'light', ... | 5,295,396 |
def _mock_vasp(strict_match): # pylint: disable=too-many-statements, too-many-locals, too-many-branches
"""Verify input objects are parseable and copy in output objects."""
from aiida.manage.configuration.settings import AIIDA_CONFIG_FOLDER # pylint: disable=import-outside-toplevel
pwd = Path().absolute()... | 5,295,397 |
def LoadScene(filepath: str):
"""
Loads spyke scene from given file and makes the scene current.
param filepath: Scene filepath.
"""
def readline():
nonlocal file
line = file.readline()
if not line:
raise EOFError
return line.replace('\n', '')
start = time.perf_counter()
try:
file = open(filep... | 5,295,398 |
def effect_icon_blit(self):
"""For blitting all status effect icon"""
SCREENRECT = self.SCREENRECT
position = self.troopcard_ui.rect.topleft
position = [position[0] + 70, position[1] + 140]
startrow = position[0]
for icon in self.effect_icon.sprites():
icon.kill()
for status in se... | 5,295,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.