content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
from datetime import datetime
def from_iso_to_unix(iso_dt):
"""Converts from ISO format (e.g., "1984-06-02T19:05:00.000Z") to UNIX.
"""
if isinstance(iso_dt, int):
return iso_dt # Already UNIX.
try:
dt = datetime.strptime(iso_dt, '%Y-%m-%dT%H:%M:%S.%fZ')
except ValueError:
... | 732c2bfdd8dd66716966ca9223d0456ebf56d924 | 60,700 |
def assert_all_above(vector, minval, open_bound=False, name='assert_all_above'):
"""Checks whether all values of vector are above minval.
Note:
In the following, A1 to An are optional batch dimensions.
Args:
vector: A tensor of shape `[A1, ..., An]` containing the values we want to
check.
minv... | 8d1b73de99fa6424f94a34970a5239e793348e47 | 60,701 |
def remove_todolist_item(request, id_item):
"""
View for removing the specified "to do list" item
"""
ls = ToDoList.objects.get(pk=id_item)
ls.delete()
return redirect("/todolist/") | a415d66437cfa8ca61808b111cf14d98e9311037 | 60,702 |
def dumps(trees):
"""
Serialize a list of trees in Newick format.
:param trees: List of Node objects or a single Node object.
:return: Newick formatted string.
"""
if isinstance(trees, Node):
trees = [trees]
return ';\n'.join([tree.newick for tree in trees]) + ';' | bf7e018dff620c5c90aff7d4b7be0dd2c21e1d1e | 60,703 |
import os
def task_collection_from_directory(directory):
"""Return a TaskCollection from a directory."""
task_collection = jicagile.TaskCollection()
fpaths = [os.path.join(directory, fn)
for fn in os.listdir(directory)
if fn.endswith(".yml") or fn.endswith(".yaml")]
for fp ... | 37dd73c111e3a218c798e0c1624fca7db2826146 | 60,704 |
from ckan import model
from pylons import config
from ckan.plugins import toolkit
from ckanext.archiver import default_settings as settings
from ckanext.archiver.model import Status, Archival
def _update_resource(ckan_ini_filepath, resource_id, queue, log):
"""
Link check and archive the given resource.
I... | ce2a754c5ce41bc5d862dedb6aa91934e77b5c59 | 60,705 |
import yaml
def parse_case(case_file):
"""
parse cases from config file
Args:
case_file(string|.yaml): case directory
Returns:
config: a dict that contains configuration
"""
yaml_config = open(case_file)
config = yaml.load(yaml_config)
config['model_dir'] = MODEL_ROOT
... | 5d88e6ef0acb43fb02483f7fa889cea74316fd4a | 60,706 |
def _parse_requirements(req, build=True, host=True, run=True):
"""Flatten a YAML requirements section into a list of names
"""
if not req: # handle None as empty
return set()
if isinstance(req, list): # simple list goes to both host and run
reqlist = req if (host or run) else []
el... | e3c5257d7380c879960c908a9940eb150b1f6552 | 60,707 |
from typing import Dict
import subprocess
import json
def get_user_info() -> Dict:
"""Returns cosbench01 user info available in realm."""
try:
proc = exec_command(cmd="radosgw-admin user info --uid cosbench01")
except subprocess.CalledProcessError:
proc = exec_command(
cmd="rad... | 6c3f59fe7494b9bb64b6fcb05e8c98c43fe8d969 | 60,708 |
def create_shift():
""" creates and deletes shifts according to the time and date """
def check(_time, _date):
""" check if the user has already taken the shift with the time and date """
shift = get_db().execute(
'SELECT s.id, date, shift, created, author_id, username '
... | 20423d7d6129d45071f01a50bbbf7da86a748c02 | 60,709 |
def decode_qrcode(image, debug_level=0):
"""Decode the QR code in the specified image.
Parameters:
image (PIL.Image): Input image.
debug_level (int): Optional debug level (0..3).
Returns:
Decoded data as a byte string.
Raises:
QRDecodeError: If decoding fails.
"""
... | 3e9229429b699c90519ba33799f2f7b7260e0ecc | 60,710 |
import os
def link_cos_initial(
input_folder: str,
model_start_time: pd.Timestamp,
parent_model_output: str
) -> str:
"""
Link laf* files to start COSMO from a given output folder into the given
input folder for the case of a fresh initial start of COSMO.
Parameters
------... | a7f682c157f7f374da74cb68497b481b229b0fa2 | 60,711 |
def has_conditions(action, resource):
"""
Checks if the resource has a condition that needs to be checked with
is_allowed_for
"""
_permissions = permissions_for()._permissions()
return bool(_permissions.get(action, {})
.get(resource, {})
.get('conditions', {})) | 9d5b1fdfa9d96f735143efd2ce085e759582245f | 60,712 |
def lineqs(A, b, show=True, title="Solution Set", color='gray', \
bounds=None, alpha=0.5, s=10, size=(15,15), save=False):
"""
Функция визуализирует множество решений системы линейных алгебраических
неравенств A x >= b с двумя переменными методом граничных интервалов, а
также выводит вершины ... | 6d29aa1c8bf1dd871c250bc9594476741fb414f7 | 60,713 |
import os
import random
import string
from datetime import datetime
def new_image():
""" Make a new image post by uploading a file """
form = CreateImageForm()
if request.method == 'POST':
f = request.files['image']
if f and allowed_file(f.filename):
# Generate a filename
filename = secur... | 5f84f18ab12e578b3999ad6470ec9d87ce5ef8f6 | 60,714 |
import requests
def open_image(image_path: str) -> np.ndarray:
"""Open image as array
Takes an image path as input and returns the image file to the user.
Can be then used for further processing or to save in any format required.
Args:
image_path (str): Path to image to be saved
Returns... | 90d0463ff11685ec347b95ad66ebbe8518d30b83 | 60,715 |
def test_fallback_sum_with_x_tensor_n_default():
"""
Feature: JIT Fallback
Description: Test sum() in graph mode with input x tensor and input n default.
Expectation: No exception.
"""
@ms_function
def foo():
x = sum(Tensor([1, 2, 3]))
return x
out = foo()
assert out.... | 4f7960f78dc2f3b5e00cbcc8b70ac0bca2ea506e | 60,716 |
def as_float(s):
"""Returns a float from a string
"""
if not s: return 0.0
return float(s) | de5e2074b19f723b36c676f20904fa53a4878aa5 | 60,717 |
def school_reopen(trigger, closing_infected, current_infected, closing_t, current_t, current_date, interval_per_day):
"""
:param trigger: str, format: type_population_number, example: monitor_all_75 (75% reduction), no_na_12 (12 weeks)
:param closing_infected: np.array of shape (n_age, riskNum), number of c... | 5d6a9407cc599aea9bfff81e90e08ebd3ae467df | 60,718 |
def _generate_config_prefix(remote):
"""Validate the app name so that it can be used in config vars."""
app_name = remote.name
if not is_app_name_valid(app_name):
raise OAuthError(f"Invalid app name {app_name}. "
"It should only contain letters, numbers, dashes "
... | 531dfa7c8e8b28cbb0019427a9bde1286ab9d19c | 60,719 |
from typing import Dict
def Cora(
directed: bool = False,
verbose: int = 2,
cache_path: str = "graphs/linqs",
**additional_graph_kwargs: Dict
) -> EnsmallenGraph:
"""Return new instance of the Cora graph.
The graph is automatically retrieved from the LINQS repository.
The Cora dataset cons... | 1aba3d1228a90e14ae0ee0bc2b23ec3ce889f7f7 | 60,720 |
from typing import List
def sample_inputs_reduction(op_info, device, dtype, requires_grad, **kwargs):
"""Sample inputs for reduction operators."""
# TODO(@heitorschueroff) Once all reduction operators are using
# ReductionOpInfo use op_info.supports_multiple_dims directly.
supports_multiple_dims: boo... | 64d3e9be98e88da1de15fd4147dacdaa64d7c533 | 60,721 |
def label_nodes(node_dataFrame, top_node_size, path, label_file,sep = ','):
"""
根据节点的出入度,对度为top的节点进行打标签。
:param node_dataFrame: 计算了出入度、度的节点文件。
:param top_node_size:每一个社区需要标记的节点个数。
:param path:标签文件的保存路径。
:param label_file:节点标签文件。格式为(user_id, verify, name),csv文件,以sep分隔
:param sep:标签文件中的分隔符。
... | 71a9fcc8605a82eff06c5cdf6c9f1f589a851233 | 60,722 |
import json
def simplify_geometry(
points,
maxpts=None,
mindist=None,
interpolate=False,
keep_activity=False):
"""Simplify location trace by removing geometrically redundant points.
points -- [{
"geojson": json.dumps({"coordinates": [lon, lat]}),
"time"... | 56fc3c411a1f2f22a2488a1c5b8a6a069800bc3b | 60,723 |
from typing import Callable
from typing import Iterable
from typing import Dict
def count_valid_passports(
validation_func: Callable, passports: Iterable[Dict[str, str]]
) -> int:
"""count the valid passports (those who have all keys"""
return sum(map(validation_func, passports)) | 230fd67e9e3bc2b999a5b44141d51f7507de4062 | 60,724 |
from typing import Optional
from typing import Any
def svd(matrix: BlockSparseTensor,
full_matrices: Optional[bool] = True,
compute_uv: Optional[bool] = True,
hermitian: Optional[bool] = False) -> Any:
"""
Compute the singular value decomposition of `matrix`.
The matrix if factorized int... | 04e5b1780c103b3ab27d9ce964403751d49bb006 | 60,725 |
import os
def get_file_path_from_import_definition(import_definition: str) -> str:
"""
Determines the file path of an imported file from a Python import definition.
:param import_marker: The line which contains the Python import definition.
:returns: The file path of the imported file.
"""
p... | 9da0b336ab29e61462fc2a8c9fdcb22475656e36 | 60,726 |
def get_pose_dis(choose_idx, pose_conf, pose_loc, keypoint_width,
delta1, delta2, mu):
"""
<class 'numpy'>
:param choose_idx:
:param pose_conf: [n x 17]
:param pose_loc: [n x 17 x 2]
:return:
"""
# make sure dim
if pose_conf.ndim == 1:
pose_conf = np.expand_d... | 4fa4bf4d3504bd7f3d9086f650744a62f3fec7a6 | 60,727 |
import json
def json_object_to_str(json_obj):
"""
json对象序列化为json串
:param json_obj: json对象
:return: 序列化的json串
"""
return json.dumps(json_obj, ensure_ascii=False) | 935ebc10d412c803d52493cd648cc0c010adb07d | 60,728 |
def is_tokenizer(value):
"""Tokenizers must be valid Regular expressions. see: options.PrefixTokenizers"""
return bool(non_empty_string(value)) | fb836a96a5da041335205ee9fbc0f28f643c00ef | 60,729 |
def rot_vec(u, v, angle=-45, degrees=True):
"""
USAGE
-----
u_rot,v_rot = rot_vec(u,v,angle=-45.,degrees=True)
Returns the rotated vector components (`u_rot`,`v_rot`)
from the zonal-meridional input vector components (`u`,`v`).
The rotation is done using the angle `angle` positive counterclockwise
(trigonometr... | 39faa84914533000fda999ffd88da817dc3c0d9d | 60,730 |
import os
def plot_model(sum_sjc_array,
pt,
gmm,
min_count: int,
write_dir: str,
filename: str,
):
"""
:param sum_sjc_array: numpy array of junction counts
:param pt: scikit-learn power transform
:param gmm: scik... | 5a49f53886ecfc96bd4e3d4a57d057b817ec8b5f | 60,731 |
import os
import yaml
import click
import sys
def get_config(config_file):
"""This tries to read the yaml config from <config_file>."""
config_file_expanded = os.path.expanduser(config_file)
if os.path.exists(config_file_expanded):
with open(config_file_expanded) as stream:
config = ya... | b7f2418c8fa295e06295672e831acfefd9457bda | 60,732 |
def to_chi(q_oper):
"""
Converts a Qobj representing a quantum map to a representation as a chi
(process) matrix in the Pauli basis, such that the trace of the returned
operator is equal to the dimension of the system.
Parameters
----------
q_oper : Qobj
Superoperator to be converte... | b6e2eb40c2a83b720dfb0f41c570e5929f1cc118 | 60,733 |
def del_points(**kwargs: dict) -> str:
"""Delete all points record for a user; requires admin."""
user = kwargs.get('user')
score = kwargs.get('message')._kwargs.get('score')
msg = ''
if not kwargs['message'].admin:
return msg
if user in score:
del score[user]
msg = "<@{0}> h... | 1d47ba187b873f2bfad9092113a92d20b6d89aaf | 60,734 |
def check_bounds(bounds, shape=0, min_separation=0.0, dtype=float):
"""Input validation for the ``bounds`` parameter.
Checks that ``bounds`` is composed of a list of tuples of the form (lower, upper), where lower <= upper and both
are numeric. Also checks that ``bounds`` contains the appropriate number of... | 4a3d133605465c7641740b51ee76fcfb4a15268c | 60,735 |
from typing import Union
from typing import Literal
from typing import Callable
import multiprocessing
def RGB_colourspace_volume_MonteCarlo(
colourspace: RGB_Colourspace,
samples: Integer = 1000000,
limits: ArrayLike = np.array([[0, 100], [-150, 150], [-150, 150]]),
illuminant_Lab: ArrayLike = CCS_IL... | f51b6b174fd49319cec6c6ccb2eedaca1bd81e38 | 60,736 |
def dsm_6(api) -> SynologyDSM:
"""Alias for api fixture."""
return api | 4f58af157e655db782c9303b7fa90e5101419573 | 60,737 |
def send_many(kwargs_list):
"""
Similar to push.send(), but this function accepts a list of kwargs.
Internally, it uses Django's bulk_create command for efficiency reasons.
Currently send_many() can't be used to send notifications with priority = 'now'.
"""
if not FIREBASE_APP:
return No... | 70c4d83dfe815f9eb42a0e1aa6d5654c215e40d2 | 60,738 |
def mni2tal(coords):
"""
Python version of BrainMap's icbm_other2tal.m.
This function converts coordinates from MNI space (normalized using
templates other than those contained in SPM and FSL) to Talairach space
using the icbm2tal transform developed and validated by Jack Lancaster at
the Resea... | 2f1b6de079f950565bba33fbd555b6faa2b26b3c | 60,739 |
import struct
def vbkv_loads(s, mapper=dict, merge_duplicate_keys=True):
"""
Deserialize ``s`` (``bytes`` containing a VBKV to a Python object.
``mapper`` specifies the Python object used after deserializetion. ``dict` is
used by default. Alternatively, ``collections.OrderedDict`` can be used if you
... | 6f55f93f1c767872aeeac0c9838baf739a1024c3 | 60,740 |
def sql_not_like(a, b):
"""SQL_NOT_LIKE
DESCRIPTION: Clumsy way of handling NOT LIKE as a SQL operator
INPUT:
OUTPUT:
"""
return not sql_like(a, b) | ad8f5b5fc6bad7fb42454801dc2aea7a725b5e10 | 60,741 |
import requests
def newSDDCPublicIP(proxy_url, sessiontoken, notes):
""" Gets a new public IP for compute workloads. Requires a description to be added to the public IP."""
myHeader = {"Content-Type": "application/json","Accept": "application/json", 'csp-auth-token': sessiontoken}
proxy_url_short = proxy_... | c4dad80fb4b57b456007a33f0f32fdea78bdd246 | 60,742 |
def power_of(x):
"""create a inner function to return the power of x"""
def inner_func(y):
return x**y
return inner_func | 69900b32c50c73365cf6c492f7c0e3b2f5641e01 | 60,743 |
def intersect_line_grid(line, grid):
"""Intersect a line with a grid, returning the smallest set of new lines
which cover the original line and such that each new line segment lies
entirely within one grid cell.
:param line: `((x1,y1), (x2,y2))`
:param grid: Instance of :class:`data.Grid` or sa... | 5b682918c243b645e9ff9edac28b2c0e6f3af66c | 60,744 |
def import_csv(filename):
"""Imports the csv file at a given path
:param filename: Path and name of file to import
:type filename: str
:return: Dataframe of csv file
"""
return pd.read_csv(filename, sep=',') | 9b8d6e8bfefdb1602cce5e1ae1f12b3fdcd2c04e | 60,745 |
import ctypes
def pfaffian(
matrix: np.ndarray,
uplo: str = "U",
method: str = "P",
avoid_overflow: bool = False,
):
"""Compute Pfaffian.
Parameters
----------
matrix : numpy.ndarray
Square skew-symmetric matrix.
uplo : str
If 'U' ('L'), the upper (lower) triangle ... | fa53eda48353793d6a4c256996f17ec6663311c4 | 60,746 |
def tsne_condP(D2=np.array([]), perplexity=30.0,
tol=1e-5,max_iter=50, verbose=0):
"""
Performs a binary search to get P-values in such a way that each
conditional Gaussian has the same perplexity.
"""
# Initialize some variables
(n, n1) = D2.shape
if n != n1:
... | ce05a2bf029cf26da62c13f9395d5747135fbf59 | 60,747 |
def _ln(input_tensor, gain, bias, epsilon=1e-5, axes=None):
"""
Apply layer normalisation.
:param input_tensor: (TensorFlow Tensor) The input tensor for the Layer normalization
:param gain: (TensorFlow Tensor) The scale tensor for the Layer normalization
:param bias: (TensorFlow Tensor) The bias te... | dcc4aabe3bbcaa0408bd1d961c5673a40598efd1 | 60,748 |
import h5py
def read_maxwell(file, well_name='well000', rec_name='rec0000'):
"""
Read a maxwell file and return a Probe object. Maxwell file format can be
either Maxone (and thus just the file name is needed), or MaxTwo. In case
of the latter, you need to explicitly specify what is the well number of
... | b1b8868f80642d3bbe9763ebff44ec71c27c0af8 | 60,749 |
import typing
def key_metrics(
apikey: str,
symbol: str,
period: str = "annual",
limit: int = DEFAULT_LIMIT,
) -> typing.List[typing.Dict]:
"""
Query FMP /key-metrics/ API
:param apikey: Your API key.
:param symbol: Company ticker.
:param period: 'annual' or 'quarter'
:param l... | fde07aa73e33b92ba419f2c3d66abe5310fdf0e8 | 60,750 |
def id_maker(pick_time, net, station, loc, ch, phaseHint, ai_type):
"""Creates the seiscomp Pick PublicID
Parameters
----------
pick_time : Obspy UTCDateTime object
Time for phase pick
Returns
------
str
Seiscomp pick PublicID
"""
dateID = pick_time.strftime(... | d576ed1a98aadda69b1354e25d77425cd386ce6b | 60,751 |
def kan_være_købstadsnummer(s: str) -> bool:
"""
Returnerer sand, hvis `s` matcher købstadsnummermønsteret.
Procedure minder om dén for landnumre.
"""
return KØBSTADSNUMMERMØNSTER.match(s.strip()) | 740aa5438168e8148b3917b4a2ad792d05dfc7f1 | 60,752 |
def get_time_for_display(display):
"""
Provide a reader-friendly time string for any time parse-able by get_astropytime -
if that results in None, then the string None is displayed.
"""
d = get_astropytime(display)
if d is None:
d = 'None'
elif isinstance(d, Time):
d = "{:%Y... | 54eba2a07c6f2703ad12031aab29a240871ec276 | 60,753 |
import re
def RetriveEMDBIDFromCIFFile(Infile):
"""Retrieve EMDB ID from CIF file. """
InfileFH = open(Infile, "r")
if InfileFH is None:
MiscUtil.PrintError("Couldn't open input file: %s.\n" % (Infile))
MiscUtil.PrintInfo("\nRetrieving EMDB ID from input file %s..." % Infile)
EMDBID... | 2c5bc5df6778ea1fd9d3996a66c0b8c1b6594aca | 60,754 |
import math
def resize3d_linear(data_in, scale, coordinate_transformation_mode):
"""Trilinear 3d scaling using python"""
dtype = data_in.dtype
d, h, w = data_in.shape
new_d, new_h, new_w = [int(round(i * s)) for i, s in zip(data_in.shape, scale)]
data_out = np.ones((new_d, new_h, new_w))
inde... | 015fc90b649f50d69359b95990b44ed361f7d9cf | 60,755 |
def obtener_cantidad_turistas_y_pais_origen_en_ciudad_en_mes_en_anio(PaisDestino, CiudadDestino, Mes, Anio): #OK
"""
Dado un pais, una ciudad destino, un mes y un año obtiene la cantidad total de personas que llegan a esa ciudad separando por pais de origen
Dado un pais, una ciudad destino, un mes y un año ... | 4e6eddf2f6b5499b5b0916ba8def0f53a91245b7 | 60,756 |
def to_hex_with_size(value, bit_size):
"""Converts a value to hex with given bit_size:"""
return pad_hex(to_hex(value), bit_size) | 9aaa174de1f89f96040328177172875d4e841d6a | 60,757 |
def quantile_with_mask(
values: np.ndarray,
mask: np.ndarray,
fill_value,
qs,
interpolation: str,
axis: int,
) -> np.ndarray:
"""
Compute the quantiles of the given values for each quantile in `qs`.
Parameters
----------
values : np.ndarray
For ExtensionArray, this i... | 6f461aa662bda45cd7998ab0d609dc3557543edd | 60,758 |
def get_positions(console):
"""
Compute a dictionary keyed by button names with horizontal alignment,
and column/row location to show each choice on the EV3 LCD console.
Parameter:
- `console` (Console): an instance of the EV3 Console() class
returns a dictionary keyed by button names with colum... | ba9df0c2ea189e146d5cf123354c283dd6e2b280 | 60,759 |
import inspect
from ..log import PCG_ROOT_LOGGER
def create_object(tag, **kwargs):
"""Factory method for `Link` subclasses.
> *Input arguments*
* `tag` (*type:* `str`): Name identifier of the object class
* `kwargs` (*type:* `dict`): Input arguments for the object class
> *Returns*
`Link`:... | 0760fbb675a29f7ca5057c7e87ac3c9e50486faa | 60,760 |
def add_sample_group(authn): # pylint: disable=too-many-locals
"""Add sample group."""
# Validate input
try:
data = request.get_json()
name = data['name']
organization = Organization.query.filter_by(name=data['organization_name']).first()
except TypeError as exc:
current... | 4aa1473637ee579b87cff8a4dfc12990d7d86a5b | 60,761 |
def convert_to_tenfive(ch_names=None):
"""Convert channel names to 10-5 system
This function aims to convert the channel labeling (in number) to the standardized 10-5 electrode labeling.
Examples
--------
>>> import TruScanEEGpy
>>> import mne
>>>
>>> ch = TruScanEEGpy.convert_to_tenfi... | ea1b4f282cf4c31a8ddd41319a208146cf4d3e58 | 60,762 |
def rotate_point_y(xyz, theta, radians=False):
"""
Rotates a 3D vector by the angle theta about the y axis
Args:
xyz: x, y, z tupple or array
theta: float, angle in degrees unless radians is True
radians: bool, if true then theta is treated as radians
Returns:
a, b, c: ro... | 606509a36c10869bb0ecc084f6c332fa6f14f253 | 60,763 |
import os
import yaml
def load_params(filepath='params.yaml') -> dict:
"""Helper function to load params.yaml
Args:
filepath (str): filename or full filepath to yaml file with parameters
Returns:
dict: dictionary of parameters
"""
assert (os.path.isfile(filepath)), FileNotFoundE... | 68d146f7274dd3c0ccbf16008c522da1ad64ba3c | 60,764 |
from typing import Callable
from typing import Any
def attrs_assert_type(expected_type: type) -> Callable[[Any, Any, Any], None]:
"""
Convenience function for attrs to easily check for a given type by using a validator.
Remark: typing types like Union[...], List[...] are supported.
Examples:
... | 38f7a99ea9058a2ce743804f374a1db84ea42b29 | 60,765 |
def _createTaperedBox( proxy, size, colour, exponentBottom, exponentTop, exponentSide, moiScale, withMesh ):
"""
Private function.
Use createTaperedBox() or createArticulatedTaperedBox() instead.
"""
taperedBox = _createBox( proxy, size, colour, moiScale = moiScale, withMesh = False )
if wi... | 45d955ee012e6d3bc02779a36087c985be5fe3f6 | 60,766 |
def generate_patch_transfer_job_message(messages, job):
"""Generates Apitools patch message for transfer jobs."""
project_id = job.projectId
job.projectId = None
if job.schedule == messages.Schedule():
# Jobs returned by API are populated with their user-set schedule or an
# empty schedule. Empty sched... | 5330f3e248ad57b69045b54f1c46c32219d1dde5 | 60,767 |
def configuration(atol=None, rtol=None, log_level=None):
"""Views and sets constants in the project-wide configuration.
The full list of global constants that are provided in a dictionary to
view, and can be set in any combination, are:
* `atol`
* `rtol`
* `log_level`
These are all consta... | e2d9a4d634c03a5eebc6671944521afa432f838a | 60,768 |
def load_vgg(sess, vgg_path):
"""
This function is to Load Pretrained VGG Model into TensorFlow.
:param sess: TensorFlow Session
:param vgg_path: Path to vgg folder, containing "variables/" and "saved_model.pb"
:return: Tuple of Tensors from VGG model (image_input, keep_prob, layer3_out, layer4_out,... | bc897bd2c5abc52d762d2527f7a9569e505d6a4a | 60,769 |
import logging
def parse_requirements(file_):
"""Parse a requirements formatted file.
Traverse a string until a delimiter is detected, then split at said
delimiter, get module name by element index, create a dict consisting of
module:version, and add dict to list of parsed modules.
Args:
... | 958ff91957667e3783e9971b2f2d0c04e4cd2a61 | 60,770 |
import torch
def find_lengths(messages: torch.Tensor) -> torch.Tensor:
"""
:param messages: A tensor of term ids, encoded as Long values, of size (batch size, max sequence length).
:returns A tensor with lengths of the sequences, including the end-of-sequence symbol <eos> (in EGG, it is 0).
If no <eos... | 32e1eaadedb69ad0b3ea3339b8d326f7a4bcfaf8 | 60,771 |
def duplicate(somelist):
"""
biore binary search na srodku listy
sprawdzam
:param somelist:
:return:
"""
emptylist = []
for i in somelist:
if len(emptylist) == 0:
emptylist.append(i)
else:
if i in emptylist:
return i
em... | aad005e7a2b2fe2f4874673dd93ad6eaf982b13a | 60,772 |
import time
import logging
def main_runner(argv, parser, exe_runner_func, setup_log_func, alog):
"""
Fundamental interface to commandline applications
"""
started_at = time.time()
args = parser.parse_args(argv)
# log.debug(args)
# setup log
_have_log_setup = False
if hasattr(args,... | b2cdea012dc20f3ff524ce1b0f4d46ea126b26b4 | 60,773 |
def get_handler_filename(handler):
"""Shortcut to get the filename from the handler string.
:param str handler:
A dot delimited string representing the `<module>.<function name>`.
"""
module_name, _ = handler.split('.')
return '{0}.py'.format(module_name) | 4e6d464e83e4a6557d03ebabbb4f275fc4784d8f | 60,774 |
def eval(dataloader, head_detector):
"""
Given the dataloader of the test split compute the
average corLoc of the dataset using the head detector
model given as the argument to the function.
"""
test_img_num = 0
test_corrLoc = 0.0
for _, (img, bbox_, scale) in enumerate(dataloader):
... | 7b31b365e2f37f4087b5f58c59e7bfe5ab7b66a8 | 60,775 |
def read_AtomName_ChargeGroup(file_name, ase2pmd):
"""
Function to read in csv file of atom names and associated charge groups with
the help of pandas. Expects dictionary of ASE indices pointing at atom and
residue name tyuples and constructs vector of associated charge
group. The vectors are all ... | 70a19130d06d99bd171943c5e38330a3218858ea | 60,776 |
def build_quadratic_function(x, a, b, c):
""" Returns the function f(x) = ax^2 + bx + c """
return a*x*x + b*x + c | 4b6bec7f9329c515afc94a8ea090c3886d7a6e46 | 60,777 |
def connect_host(host, pid):
"""连接主机"""
host_error = False
hostname, port, username, password = host
client = paramiko.SSHClient() # 创建客户端
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, port, username, password, timeout=3)
except paramik... | 6ae4db4c35fa8b86c0424ba3f7c3b0b1445c4c09 | 60,778 |
def parseEPSGCode(string, parsers):
""" parse EPSG code using provided sequence of EPSG parsers """
for parser in parsers:
epsg = parser(string)
if epsg is not None:
return epsg
return None | b85e2d69952cc16d7f5f3b9e22009d14432a014f | 60,779 |
def big_brain_algorithm(word_list=None):
"""
Checks if a word can be made out of the elements that are contained in it.
:param word_list: A list with where index 0 is the word and index 1 is all possible elements that are in the word.
:return: All possibilities to create the word out of elements.
""... | f26bf23e5ca1215445e230556e720514d477ee0f | 60,780 |
from typing import Optional
from typing import Type
from typing import Callable
def group(
name: Optional[str] = None, cls: Type[GroupCommand] = GroupCommand, **attrs
) -> Callable[["CommandFunctionType"], GroupCommand]:
"""Register a coroutine as a :class:`GroupCommand`.
Parameters
----------
na... | e4017c2c9122004350849d316118715424389912 | 60,781 |
def req_rheader(r):
"""
Resource Header for Needs
"""
if r.representation != "html":
# RHeaders only used in interactive views
return None
record = r.record
if not record:
# RHeaders only used in single-record views
return None
if r.name == "need":
... | 07bcb4f8bd5c91de970633e613e447e13c03de32 | 60,782 |
def sum_intersection(map_list):
"""
Sum a list of HealSparseMaps as an intersection. Only pixels that are valid
in all the input maps will have valid values in the output.
Parameters
----------
map_list : `list` of `HealSparseMap`
Input list of maps to sum
Returns
-------
r... | a7a10bb47210cca4488a8145a90aa9708f8c91b2 | 60,783 |
def colorspace(im, bw=False, replace_alpha=False, **kwargs):
"""
Convert images to the correct color space.
A passive option (i.e. always processed) of this method is that all images
(unless grayscale) are converted to RGB colorspace.
This processor should be listed before :func:`scale_and_crop` s... | 7680bbaa1db5527eb845c2f4cb52f7b66ac75a33 | 60,784 |
def make_tiles(in_data, tile_path, tile_width=256, tile_height=256, tile_overlap=32):
"""Split input images into tiles
Parameters
----------
in_data: iterable
The input images, to split into tiles
tile_path: str
Filepath where the tiles should be saved
tile_width: int
Ti... | 059b3c83bf3b46ffeeaec500abc7075516aabf46 | 60,785 |
def int32(name, description, default=None):
# type: (AName, ADescription, AInt32Default) -> AAnno
"""Add an int32 parameter to be passed when instantiating this YAML file"""
args = common_args(name, default)
return Anno(description, typ=int, **args) | ff44435a9ee735d2840893026d98efe2b881ea7e | 60,786 |
import os
def FindLatestResult(result_dir):
"""Find the latest result in |result_dir| and read and return them.
This is used for comparison of analyzer result between current analyzer
and most known latest result.
Args:
result_dir: the result directory.
Returns:
A tuple of filename (latest_time) ... | a54d43728cc3b9526a3ace4f949604aacee61e1c | 60,787 |
import os
def load_data(datapath):
"""
Load all HDF5 files with extension h5 in the given directory
datapath
directory path for the files; usually the output directory
returns a dictionary with all the HDF5 files loaded
"""
data_dict = {}
ext = 'h5'
for root,directory,files in ... | 1f0dde4fbc836eac662eeab9e1f2e5bb5707058b | 60,788 |
def make_test_data(filename, taiObs, dataType, camera=1, filter="g2", shape=(30, 50), bias=32,
ra=100, dec=-30, exposure_time=30):
"""Make a fake FITS image with a realistic header, returning the header."""
# Make the fake image data
if dataType == "science":
data = np.ones(shape)... | 65ce95b755f7fa9d719df61a5fa69e28a9051694 | 60,789 |
def user_has_pending_game_actions(ctx, u):
""" Returns True if this user has any pending 'actions' in the current game. Actions is currently
defined as unprocessed targets, future chips or future deferred actions, but this definition might change. """
actions = 0
actions += db._run_query_string(ctx,... | 39eef1aa67ba0095d9b1cf87bc75548b284f64b5 | 60,790 |
def project_to_plane(points,
plane_normal=[0, 0, 1],
plane_origin=[0, 0, 0],
transform=None,
return_transform=False,
return_planar=True):
"""
Projects a set of (n,3) points onto a plane.
Parameters
... | 1276c06556e42e3da905a144944761edac8e23bc | 60,791 |
import re
def get_value_for_key(text_buffer, key):
"""Parsing value from a line with key=value"""
for match in re.finditer("%s=(?P<value>.*)" % key, text_buffer):
return match.group('value')
return "" | 86865f806adc3fa5f78671d8a686389cc5f0f353 | 60,792 |
import math
def extract_data_for_map(src, bounds, scale, map_width, map_height):
"""Extract, reproject, and clip data within bounds for map images.
Returns None if there is only nodata within the bounds.
Parameters
----------
src : rasterio.RasterReader
open rasterio reader
bounds : ... | 098f8ff55b40f9e58abf79a738bf6c0bcfd92322 | 60,793 |
import requests
def jawbone_code_to_member(code, ohmember):
"""
Exchange code for token, use this to create and return Jawbone members.
If a matching jawbone exists, update and return it.
"""
if settings.JAWBONE_CLIENT_SECRET and \
settings.JAWBONE_CLIENT_ID and code:
data = {
... | c3b23c739afe1d096945eb1aa3251a3a42ecc79a | 60,794 |
def join_longways(list_of_dataframes):
"""Join the supplied dataframes along the long axis - appending them one after another to make a longer table"""
df = pd.concat(list_of_dataframes,axis=0)
return df | 9334076130673ad2ff84d1958058bd5a4bb6b67b | 60,795 |
import six
def py2_unicode_compatible(klass):
"""
A decorator that defines __unicode__ and __str__ methods under Python 2.
Under Python 3 it does nothing.
"""
if six.PY2:
if '__str__' not in klass.__dict__:
raise ValueError("@python_2_unicode_compatible cannot be applied "
... | 914ac3fed6aab80fe61edef368478c58751ebd7a | 60,796 |
import numpy
def _problem_for_numerical_trainable_transform_cl(dtype=numpy.float32, n_features=None):
"""
Returns *X, intial_types, method, name, X runtime* for a
transformation problem.
It is based on Iris dataset.
"""
data = load_iris()
X = data.data
state = numpy.random.RandomState(... | ca162d2c1e29ab0c572581b20f865f7b10f5e7c8 | 60,797 |
def find_base_url(html_document, fallback_base_url):
"""Return the base URL for the document.
See http://www.w3.org/TR/html5/urls.html#document-base-url
"""
first_base_element = next(iter(html_document.iter('base')), None)
if first_base_element is not None:
href = first_base_element.get('h... | 86501904c5982cfe1402b049b404a67dede6e26d | 60,798 |
import pathlib
def _is_valid_doc_version(folder: pathlib.Path) -> bool:
"""
Test if a version folder contains valid documentation.
A version folder contains documentation if:
- is a directory
- contains an `index.html` file
"""
if not folder.is_dir():
return False
if not (fold... | 5dadea657b717373e8e84360f1f3a9e8b8adc1f8 | 60,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.