content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
"""Takes filenames out of queue and runs clang-tidy on them."""
while True:
name = queue.get()
shortname = relpath(name, args.source_tree)
invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
... | 62,100 |
def intersect_models(dict1, dict2):
"""Combine two dictionaries that are returned from a source method call to
keep only those models that are present in both. It assumes that the models
present in both dictionaries are identical and takes them for the first
input dictionary.
:param dict1: The firs... | 62,101 |
def post_multipart(site, address, fields, files, cookies):
""" Post fields and files to an http host as multipart/form-data.
@param fields: sequence of (name, value) elements for regular form fields.
@param files: sequence of (name, filename, value) elements for data to be
uploaded as files
@re... | 62,102 |
def translation_xml(data_path, scripts_path):
"""
update the Estoria site with the current reader XML file
"""
logger.info('{}: translation_xml task started'.format(current_task.request.id))
logger.debug('{}: Data path: {}'.format(current_task.request.id, data_path))
logger.debug('{}: Scripts lo... | 62,103 |
def hex2meter(level, hex_x, hex_y):
"""hex xy to meter"""
h_len = HEX_LEN / math.pow(3, level)
y = (hex_x + hex_y) * h_len * math.sqrt(3) / 2.0
x = (hex_x - hex_y) * h_len * 3.0 / 2.0
return x, y | 62,104 |
def create_root_analysis(tool=None, tool_instance=None, alert_type=None, desc=None, event_time=None,
action_counts=None, details=None, name=None, remediation=None, state=None,
uuid=None, location=None, storage_dir=None, company_name=None, company_id=None,
... | 62,105 |
def _extract_base_type(typed):
"""Extracts the name of the type from a _GenericAlias
Assumes that the derived types are only of length 1 as the __args__ are [0] recursed... this is not true for
tuples
Args:
typed: the type of the parameter
Returns:
name of type
"""
if hasa... | 62,106 |
def _UploadFileToObjectResumable(src_url, src_obj_filestream,
src_obj_size, dst_url, dst_obj_metadata,
preconditions, gsutil_api, logger):
"""Uploads the file using a resumable strategy.
Args:
src_url: Source FileUrl to upload. Must not be a st... | 62,107 |
def get_openstack_connection_raw(auth_args):
"""obtains an OpenStack connection from a supplied dictionary of auth args"""
print("Connecting to Openstack at {0}".format(auth_args['auth_url']))
conn = connection.Connection(**auth_args)
return conn | 62,108 |
def recent_feed_like(bot: InstaBot):
"""
Automatically fetches ank like recent_feed_likes
:param bot:
:return:
"""
# first check if self.media_on feed has length zero.
if len(bot.media_to_like) == 0:
print("Refreshing New Media")
if bot.startup:
first_init(bot)
... | 62,109 |
def light_probe_sampling_variance_minimization_Viriyothai2009(
light_probe, lights_count=16, colourspace=RGB_COLOURSPACES['sRGB']):
"""
Sample given light probe to find lights using *Viriyothai (2009)* variance
minimization light probe sampling algorithm.
Parameters
----------
light_pro... | 62,110 |
def view_diff(request, uid):
"""
View most recent diff to a post.
"""
# View most recent diff made to a post
post = Post.objects.filter(uid=uid).first()
diffs = Diff.objects.filter(post=post).order_by('-pk')
# Post has no recorded changes,
if not diffs.exists():
return ajax_su... | 62,111 |
def str2bool(val):
"""Convert string to boolean value
"""
try:
if val.lower() in ['false', 'off', '0']:
return False
else:
return True
except AttributeError:
raise TypeError('value {0} was not a string'.format(type(val))) | 62,112 |
def make_gaussian_filter_tensor(single_filter, angles, device='cuda'):
"""
Generates 3D tensor of size (M, M, number_angles) with stack of rotated Fourier filters to be used for
datacube extraction.
:param single_filter: Initial filter as numpy array of size (M, M)
:param angles: list or numpy array... | 62,113 |
def remove_outliers(df):
"""Summary Line.
Extended description of function.
Args:
arg1: Function will remove 1.5 IQR outliers from data set.
Returns:
Will return a data set with outliers within the 1.5 IQR range removed.
"""
q1 = df.quantile(0.25)
q3 = df.quantile(0.75)
iq... | 62,114 |
def GetOdomFromState(state, spot_wrapper, use_vision=True):
"""Maps odometry data from robot state proto to ROS Odometry message
Args:
data: Robot State proto
spot_wrapper: A SpotWrapper object
Returns:
Odometry message
"""
odom_msg = Odometry()
local_time = spot_wrapper... | 62,115 |
def find_anagrams(s):
"""
:param s:str, user want to search for anagram
:return:the result of the anagram and print all of them
"""
# call the helper function with empty string and empty lst
lst = find_anagrams_helper(s, "", [])
ana_num = len(lst)
print(f'{ana_num} anagrams: {lst}') | 62,116 |
def save_model(model, file):
"""
保存模型
:param model:
:param file:
:return:
"""
with open(file, mode='wb') as f:
pickle.dump(model, f) | 62,117 |
def loadfactory(theclass, *args):
"""Returns an extended instance of `theclass` initiated from dlite
instance or storage.
If `*args` is a dlite instance, the returned object is initiated form
it. Otherwise `*args` is passed to dlite.Instance()
"""
inst = args[0] if isinstance(args[0], Instance... | 62,118 |
def find_diagonal_blocks(mat: np.ndarray) -> np.ndarray:
"""
Find perfect diagonal sub-blocks in a block-diagonalized binary matrix.
Parameters
----------
mat : (n,n) np.ndarray
binary matrix
Returns
-------
inds : (n,) np.ndarray[int]
all elements comprising a unique p... | 62,119 |
def categorical_evaluation(prediction: np.ndarray, target: np.ndarray, metric_name: str, mask=None) -> pd.DataFrame:
"""
Evaluates a regression prediction with the F1 score
on quantile-based categories
Args:
prediction: shape [n_classes, X]
target: shape [n_classes, ... | 62,120 |
def test_us_company_with_unique_zips_generates_valid_address_area(
post_code,
area_code,
):
"""
Test postcode is fixed for the purpose of admin area
generation with valid zip codes format
:param post_code: POSTCODE good
:param area_code: Area Code to be generated from Command
"""
com... | 62,121 |
def get_layers(net_param):
"""Get layers information.
Parameters
----------
net_param : caffe_pb2.NetParameter
A pretrined network description.
Returns
-------
layers : list
description of the layers.
version : string
version information of the pretrained model.
... | 62,122 |
def get_project_root() -> Path:
"""
Get project root directory with assumed structure as:
${PACKAGE_ROOT}/core/common/path.py
"""
return Path(__file__).resolve().parent.parent.parent | 62,123 |
def on_prefs_update():
""" To prevent unlimited calling """
def prefs_reload():
observe_prefs()
observe_prefs(observer=prefs_reload)
# call reload w/ inertial delay
is_alive = check_thread('LikeGitPrefsThread', stop=False)
if not is_alive:
pthread = LikeGitPrefsThread()
p... | 62,124 |
def trna_calculate_end(infiles, outdir):
"""
Calculates the end position for each read for each tRNA cluster then
plots a heatmap
"""
os.mkdir(outdir)
bamfile, fastafile = infiles
PY_SRC_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__),
... | 62,125 |
def _on_display_layer_deleted_cb(node, data):
""" Called when a display layer was deleted.
"""
mfnnode = mapi.MFnDependencyNode(node)
name = str(mfnnode.name())
_lg.debug("Maya deleted display layer '%s'" % name)
m2u.core.editor.delete_layer(name)
_create_all_layer_script_jobs() | 62,126 |
def cvSubdiv2DEdgeOrg(edge):
"""CvSubdiv2DPoint cvSubdiv2DEdgeOrg( CvSubdiv2DEdge edge )
Returns edge origin
[ctypes-opencv] returns None if no point is found
"""
ev = edge.value
e = pointer(CvQuadEdge2D.from_address(ev & ~3))
return pointee(e[0].pt[ev & 3]) | 62,127 |
def vlm_plot(df_vlm, population_index, elasticity=0.3, to_show=True, save_path=None):
"""
绘制变量的vlm图像
Parameters
----------
df_vlm: DataFrame
population_index: dict
全量样本的统计量
elasticity: float, default 0.3
上界和下界的弹性
to_show: bool, default True
是否展示图片
save_path: s... | 62,128 |
def test_can_parse_regular_step_followed_by_tabular_step():
"""
It should correctly extract two steps (one regular, one tabular) into an
array.
"""
steps = parse_steps(I_LIKE_VEGETABLES + I_HAVE_TASTY_BEVERAGES)
assert len(steps) == 2
assert isinstance(steps[0], Step)
assert isinstance(s... | 62,129 |
async def kill_process(op: Operation, host: ObservedHost, pid: int, job_run_until_success) -> bool:
"""
Kills the specified process pid on the desired host
Args:
op: The operation currently being run
host: The host to run the command on
pid: The pid to kill
job_run_until_succ... | 62,130 |
def delete(consul_url=None, token=None, key=None, **kwargs):
"""
Delete values from Consul
:param consul_url: The Consul server URL.
:param key: The key to use as the starting point for the list.
:param recurse: Delete values recursively beginning at the value of key.
:param cas: This flag is u... | 62,131 |
def test_copy_relevant_script_args(run_config: RunConfig, expected_args: List[str]):
"""
Assert that script_args (to be passed when calling script in AML) is created correctly under
a number of different scenarios.
"""
script_args_enum = copy_relevant_script_args(run_config)
assert script_args_e... | 62,132 |
def test_netconf_connection_missing_ssh_keyfile(nornir):
"""Test netconf connection - no ssh config file."""
nr = nornir.filter(name="netconf1")
result = nr.run(netconf_capabilities)
assert isinstance(result["netconf1"].result, list) | 62,133 |
def parse(fname, field_types, custom_append=None):
"""Parse a data file from the Movie Lens data set.
This function parses a file from the Movie Lens data set.
The function returns a generator for JSON dict strings.
Optionally, a callback for extending the JSON dict string can be passed.
... | 62,134 |
def read_forcing(forc_filename, start_time, end_time,
dt=1800.0, na_values='NaN', sep=';'):
"""
Reads forcing data from to dataframe
Args:
forc_filename (str): forcing file name
start_time (str): starting time [yyyy-mm-dd], if None first date in
file used
... | 62,135 |
def test_workout(client):
"""Testing the workout page"""
# Not logged in
returned_value = client.get('/workout/adjr/00000', follow_redirects=True)
assert returned_value.status_code == 200
assert b'login' in returned_value.data
assert g.user is None
trainee = g.database.get_trainee_by_userna... | 62,136 |
def __check_collisions(dst: str, force: bool):
"""
Checks against collisions for the destination path
"""
if not path_exists(dst):
return # direct return
if force:
# Force flag enabled, direct remove and exit
shutil.rmtree(dst)
return
typer.secho(
f"De... | 62,137 |
def validate_hash_digest(value):
"""
Validate that the given value is in the format of a sha3/256 digest
:param value: The value to be validated
:raises: ValidationError
"""
if not value:
raise ValidationError('hash digest cannot be None')
if len(value) < BaseConfig.SHA3... | 62,138 |
def indexCube(nodes, gridSize, n=None):
"""
Returns the index of nodes on the mesh.
Input:
nodes - string of which nodes to return. e.g. 'ABCD'
gridSize - size of the nodal grid
n - number of nodes each i,j,k direction: [ni,nj,nk]
Output:
index - index in th... | 62,139 |
def encode_cf_datetime(dates, units=None, calendar=None):
"""Given an array of datetime objects, returns the tuple `(num, units,
calendar)` suitable for a CF compliant time variable.
Unlike `date2num`, this function can handle datetime64 arrays.
See also
--------
netcdftime.date2num
"""
... | 62,140 |
def aggclus(X, THRESHOLD):
"""
agglomerative clustering using single link
X is the n x m vector where n is the number of samples
uses euclidian distance
"""
clustering = AgglomerativeClustering(n_clusters=None, distance_threshold=THRESHOLD).fit(X)
return clustering.labels_,clustering.n_clust... | 62,141 |
def calc_pval(x, y, nulls):
"""
Calculates p-values for simulations in `x` and `y` using `spatnull`
Parameters
----------
{x, y} : (N,) array_like
Simulated GRF brain maps
nulls : (N, P) array_like
Null versions of `y` GRF brain map
Returns
-------
pval : float
... | 62,142 |
def getstatusoutput(cmd):
"""Return (status, output) of executing cmd in a shell."""
import os
pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')
text = pipe.read()
sts = pipe.close()
if sts is None:
sts = 0
if text[-1:] == '\n':
text = text[:-1]
return (
sts, text) | 62,143 |
def norm_bbox(img, bbox, x_corr=0.025, y_corr=0.025):
"""Add adition value for bbox results in x and y-axis
In order to ensure the detected region can cover all the table, we will add an addition value for both x and y axis of the bbox
Using the correlation value x_corr for x-axis and y_corr for y-axis
... | 62,144 |
def module_dir():
"""directory of the current module"""
from os.path import dirname
module_dir = dirname(module_path())
if module_dir == "": module_dir = "."
return module_dir | 62,145 |
def get_latest_draft_version(version):
"""Get latest draft version of version object
"""
drafts = Version.objects.filter_by_content_grouping_values(version.content).filter(
state=DRAFT
)
return drafts.first() | 62,146 |
def delete_datasource_mapping(connection: Connection, id: str, error_msg: Optional[str] = None):
"""Delete a datasource mapping based on id.
Args:
connection: MicroStrategy REST API connection object
id (string): ID of the mapping meant to be deleted.
error_msg (string, optional): Custo... | 62,147 |
async def setup_webostv(opp):
"""Initialize webostv and media_player for tests."""
assert await async_setup_component(
opp,
DOMAIN,
{DOMAIN: {CONF_HOST: "fake", CONF_NAME: NAME}},
)
await opp.async_block_till_done() | 62,148 |
def launch_batch(param):
"""
batch launcher
"""
try:
batch(param)
except Exception:
print_error_batch()
sys.exit(1) | 62,149 |
def test_coordinates_creation(proj_type):
"""Test projections and coordinates."""
g = Path(__file__).parent / 'data' / f'{proj_type}.grd'
d = Path(__file__).parent / 'data' / f'{proj_type}.npz'
grid = GempakGrid(g)
decode_lat = grid.lat
decode_lon = grid.lon
gempak = np.load(d)
true_la... | 62,150 |
def _build_entity_object_ids(entities: Union[str, Mapping[str, Any], Sequence[str]]) -> str:
"""
Builds the string of object ids as required by the GetObject transaction request. See
section 5.3 for the full definition:
ID ::= resource-set *(, resource-set)
resource-set ::= resource... | 62,151 |
def test_nested_roundtrip(cls_and_vals, strat, omit_if_default):
"""
Nested classes with metadata can be unstructured and restructured.
"""
converter = Converter(
unstruct_strat=strat, omit_if_default=omit_if_default
)
cl, vals = cls_and_vals
# Vals are a tuple, convert into a dictio... | 62,152 |
def get_all_coords(rdmol):
"""Function to get all the coordinates for an RDMol
Returns three lists"""
conf = rdmol.GetConformer()
x_coords = []
y_coords = []
z_coords = []
for atm in rdmol.GetAtoms():
x_coords.append(conf.GetAtomPosition(atm.GetIdx()).x)
y_coords.app... | 62,153 |
def valid_fn(path, fn_name):
"""Shorten file name in case it exceeds system's maximum length."""
PC_PATH_MAX = os.pathconf("/", "PC_PATH_MAX") - 4
PC_NAME_MAX = os.pathconf("/", "PC_NAME_MAX") - 4
full_len = len(path + fn_name)
if full_len > os.pathconf("/", "PC_PATH_MAX"):
logging.debug("P... | 62,154 |
def make_sized_bytes(size):
"""
Create a streamable type that subclasses "hexbytes" but requires instances
to be a certain, fixed size.
"""
name = "bytes%d" % size
def __new__(self, v):
v = bytes(v)
if not isinstance(v, bytes) or len(v) != size:
raise ValueError("bad... | 62,155 |
def evaluations(ty, pv):
"""
evaluations(ty, pv) -> ACC
Calculate accuracy using the true values (ty) and predicted values (pv).
"""
if len(ty) != len(pv):
raise ValueError("len(ty) must equal to len(pv)")
total_correct = total_error = 0
for v, y in zip(pv, ty):
if y == v:
... | 62,156 |
def _is_member_of(cls, obj):
"""
returns True if obj is a member of cls
This has to be done without using getattr as it is used to
check ownership of un-bound methods and nodes.
"""
if obj in cls.__dict__.values():
return True
# check the base classes
if cls.__bases__:
f... | 62,157 |
async def handle_role_change(
member: discord.Member,
coro: typing.Callable[..., typing.Coroutine],
role: discord.Role
) -> None:
"""
Await the given ``coro`` with ``member`` as the sole argument.
Handle errors that we expect to be raised from
:obj:`discord.Member.add_roles` and :obj:`disco... | 62,158 |
def get_base_info(stock_codes: Union[str, List[str]]) -> Union[pd.Series, pd.DataFrame]:
"""
Parameters
----------
stock_codes : Union[str, List[str]]
股票代码或股票代码构成的列表
Returns
-------
Union[Series, DataFrame]
- ``Series`` : 包含单只股票基本信息(当 ``stock_codes`` 是字符串时)
- ``Data... | 62,159 |
def photom(data,stars,uncertainty=None,rad=[3],skyrad=None,display=None,
gain=1,rn=0,mag=True,utils=True) :
""" Aperture photometry of input image with current star list
"""
# input radius(ii) in a list
if type(rad) is int or type(rad) is float: rad = [rad]
# uncertainty either speci... | 62,160 |
def run_create_sourcelists(obs_info_dict, param_dict):
""" subroutine to run create_sourcelists and produce log file when not run sourcelist_generation is not run from
hlaprocessing.py.
Parameters
----------
obs_info_dict : dictionary
Dictionary containing all information about the images b... | 62,161 |
def process_adapter_message(message):
"""
This method is called from the component logic.
It is up to the developer of the logic to decide how a message
will look like. In the end both parties must support the same
set of messages to be compatible.
One often used message in Wirehome is the _in... | 62,162 |
def discount_cumsum(x, dones, gamma):
"""
computing discounted cumulative sums of vectors that resets with dones
input:
vector x, vector dones,
[x0, [0,
x1, 0,
x2 1,
x3 0,
x4] 0]
output:
[x0 + discount * x1... | 62,163 |
def determine_resolves_to_generate(
all_known_user_resolve_names: Iterable[KnownUserResolveNames],
all_tool_sentinels: Iterable[type[GenerateToolLockfileSentinel]],
requested_resolve_names: set[str],
) -> tuple[list[RequestedUserResolveNames], list[type[GenerateToolLockfileSentinel]]]:
"""Apply the `--r... | 62,164 |
def validate_limit_parameter(fields_dict, args):
"""validate limit parameter"""
limit = fields_dict.get("limit")
if not args.get("limit"):
args.update({"limit":limit.get("default")})
elif args.get("limit") > limit.get("max_value"):
raise Exception("Max value for limit parameter is {0}".format(limit.get("max_v... | 62,165 |
def prepare_laplacian(laplacian):
"""Prepare a graph Laplacian to be fed to a graph convolutional layer
"""
def estimate_lmax(laplacian, tol=5e-3):
r"""Estimate the largest eigenvalue of an operator."""
lmax = sparse.linalg.eigsh(laplacian, k=1, tol=tol,
n... | 62,166 |
def green_leds_off(sleep_speed):
"""
Turns off the green LEDs one at a time
Arguments:
sleep_speed: the time to wait between LEDs
"""
sleep_speed = sleep_speed
# Arm 1, Green
PYGLOW.led(4, 0)
sleep(sleep_speed)
# Arm 2, Green
PYGLOW.led(10, 0)
sleep(sleep_speed)
... | 62,167 |
def create_workspaces(Workspaces=None):
"""
Creates one or more WorkSpaces.
This operation is asynchronous and returns before the WorkSpaces are created.
See also: AWS API Documentation
Exceptions
:example: response = client.create_workspaces(
Workspaces=[
{
... | 62,168 |
def hash_str(s):
"""Hash the user_id and SECRET (a constant) to create a cookie hash."""
return hmac.new(SECRET, s).hexdigest() | 62,169 |
def transition_kernel_wrapper(
current_state: 'fun_mc_lib.FloatNest', kernel_results: 'Optional[Any]',
kernel: 'tfp.mcmc.TransitionKernel') -> 'Tuple[fun_mc_lib.FloatNest, Any]':
"""Wraps a `tfp.mcmc.TransitionKernel` as a `TransitionOperator`.
Args:
current_state: Current state passed to the transitio... | 62,170 |
def test_equivalence_GSFA_PCA_for_DT_0():
""" Test of iGSFA and PCA when delta_threshold is smaller than 0.0
"""
x = numpy.random.normal(size=(300, 15))
n = iGSFANode(output_dim=5, slow_feature_scaling_method=None, delta_threshold=0.0)
n.train(x, train_mode="regular")
# n.stop_training() has be... | 62,171 |
def deprecated(_type, old, new, version, stack_level=2):
"""a convenience function for deprecating classes, functions, arguments.
Parameters
----------
_type
should be one of class, method, function, argument
old, new
the old and new names
version
the version by which su... | 62,172 |
def get_valid_output_response(data):
"""
Returns success message correct processing of post/get request
:param str data: message
:return: response
:rtype: object
"""
response = {"status": 200, "message": "Success", "data": data}
return response | 62,173 |
def test_default_config(
tmp_path: Path,
config_default_builder: ConfigBuilder,
pypi_repo: PyPiRepository,
valiant_app_name: str,
valiant_version: str,
) -> None:
"""Basic config test making sure the defaults come through correctly."""
from string import Template
c = get_config_instance... | 62,174 |
def _get_column_data_type(dataframe: pd.DataFrame):
"""
Returns
-------
when krx.read_date(date='2021-06-22')
{'종목명': 'str',
'시장구분': 'str',
'소속부': 'str',
'종가': 'np.int64',
'대비': 'np.int64',
'등락률': 'float',
'시가': 'np.int64',
'고가'... | 62,175 |
async def create_pr(
maintainer_can_modify: bool = True,
draft: bool = False,
*,
owner: str,
repo: str,
head: str,
base: str,
title: str,
body: str,
app: Application,
logger: BoundLogger,
) -> Dict[str, Any]:
"""Create a GitHub pull request.
This function wraps `POST... | 62,176 |
def test_ncname003_2132_ncname003_2132_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : value=fo124
"""
assert_bindings(
schema="msData/datatypes/NCName.xsd",
instance="msData/datatypes/NCName003.xml",
class_name="Root",
version="1.1",
mod... | 62,177 |
def test_find_pets_by_tags(client: TestClient):
"""Test case for find_pets_by_tags
Finds Pets by tags
"""
params = [("tags", ['tags_example'])]
headers = {
"Authorization": "Bearer special-key",
}
response = client.request(
"GET",
"/pet/findByTags",
headers=h... | 62,178 |
def test_method_get_teacher_forced_logits_for_encoder_decoder_model():
""" Tests if get_teacher_forced_logits() works for encoder-decoder models.
"""
import torch
import numpy as np
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
from shap.models import TeacherForcingLogits
fro... | 62,179 |
def build_metadata_table(city_names):
"""Return the name of a temp file with metadata from the given city."""
metadata = get_complete_metadata(uploadable=True)
city_metadata_rows = metadata[COLUMNS.CITY].str.lower().isin(city_names)
city_metadata = metadata[city_metadata_rows]
city_metadata_file_han... | 62,180 |
def format_log_entry(msg):
"""Add timestamp and align msg for logging purposes"""
timestamp = str(datetime.datetime.now())
# Align colon (msg must begin with 'CTRL', 'SEM' or '3VIEW'):
try:
i = msg.index(':')
except:
i = 0
return (timestamp[:22] + ' | ' + msg[:i] + (6-i) * ' ' + ... | 62,181 |
def test_authenticate_with_stalker_and_ldap_authenticates_an_existing_ldap_user(ldap_server, create_db, monkeypatch):
"""testing if the anima.utils.authenticate() function will authenticate a
ldap user without a problem
"""
from ldap3.extend import StandardExtendedOperations
def mock_return(*arg, *... | 62,182 |
def get_likes_v2(owner_id):
"""Get amount of likes in last 100 posts of any type"""
# wall.get request - get response or raise an error.
try:
response = api.wall.get(owner_id=owner_id, count=100)
except vk.exceptions.VkAPIError:
print('Access denied')
# TODO: get exception key
... | 62,183 |
def multi_quat_diff(nq1, nq0):
"""return the relative quaternions q1-q0 of N joints"""
nq_diff = np.zeros_like(nq0)
for i in range(nq1.shape[0] // 4):
ind = slice(4*i, 4*i + 4)
q1 = nq1[ind]
q0 = nq0[ind]
nq_diff[ind] = quaternion_multiply(q1, quaternion_inverse(q0))
ret... | 62,184 |
async def test_set_ramp_rate(
subject: driver.ThermocyclerDriverV2, connection: AsyncMock
) -> None:
"""It should not send a set ramp rate command."""
await subject.set_ramp_rate(ramp_rate=22)
assert not connection.send_command.called | 62,185 |
def log_sequence(prefix, sequence_to_log):
"""Helper function to log a sequence.
Dump a sequence to the logger, skip if it is empty
Args:
prefix: The prefix string to describe what's being logged
sequence_to_log: The sequence being logged
"""
if sequence_to_log:
logger.debu... | 62,186 |
def temporary_dirs(dirs: Union[Path, str] = []):
"""Temporarily changes all resource directories
Example::
with temporary_dirs([path1, path2, path3]):
# Load some resource here
Args:
dirs (Union[Path,str]) list of paths to use
"""
data_dirs = settings.DATA_DIRS
pro... | 62,187 |
def test_ipv4_detect():
"""IPv4 lookalikes are not valid SubdomainCallingFormat names
Even though they otherwise follow the bucket naming rules,
IPv4-alike names are called out as specifically banned.
"""
assert _is_ipv4_like('1.1.1.1') is True
# Out-of IPv4 numerical range is irrelevant to th... | 62,188 |
def get_global_config(
local_config: LocalConfig,
database: BaseDatabaseDriver,
connection: Connection,
) -> None:
"""Retrieve remote global config for overrides and wikis."""
try_cache(
get=lambda: fetch_global_overrides(local_config),
store=database.store_global_overrides,
... | 62,189 |
def _clean_graph_def(graph_def: tf.compat.v1.GraphDef) -> tf.compat.v1.GraphDef:
"""Edit the GraphDef proto to make it more performant for TFF.
WARNING: This method must _NOT_ make any semantic changes (those that would
change the results of the computation). TFF does not really want to be
modifying the graph ... | 62,190 |
def test_publish_timestamps_match(
dataset: VersionedDataset, model: Model, training_config: TrainingConfig
) -> None:
"""Tests that all 3 timestamps match if no version string is supplied:
metadata.json's version and created_at fields, and the final directory
of the published path.
:param dataset:... | 62,191 |
def _remove_creds(creds_file=None):
"""
Remove ~/.onecodex file, returning True if successul or False if the file didn't exist
"""
if creds_file is None:
fp = os.path.expanduser("~/.onecodex")
else:
fp = creds_file
if os.path.exists(fp):
os.remove(fp)
return True... | 62,192 |
def test__manifest_no_thumbnail_dereference_no_canvas(iiif2_manifest):
"""
Should just return None as there's nothing to de-reference
:param iiif2_manifest:
:return:
"""
thumbnail = get_iiif_resource_thumbnail_json(
iiif_resource=iiif2_manifest, fallback=True, first_canvas_json=None
... | 62,193 |
def index(path):
"""UI base view."""
return render_template('invenio_app_ils/index.html') | 62,194 |
def wrap_exceptions(callable):
"""Call callable into a try/except clause so that if an
OSError EPERM exception is raised we translate it into
psutil.AccessDenied.
"""
def wrapper(self, *args, **kwargs):
try:
return callable(self, *args, **kwargs)
except OSError, err:
... | 62,195 |
def multi_multi_log_loss(predicted,
actual,
class_column_indices=BOX_PLOTS_COLUMN_INDICES,
eps=1e-15):
""" Multi class version of Logarithmic Loss metric as implemented on
DrivenData.org
"""
class_scores = np.ones(len(clas... | 62,196 |
def generate_v_graph(data_format, characters, percentage=True, colour_coding='dft'):
"""generate vertical graph with different colours
data_format = a prepared array return by get_plotly_data() as the first return value
characters = a perpared list of characters returned by get_plotly_data() as the second... | 62,197 |
def filter_production_brand(production_id):
"""
产品品牌
:param production_id:
:return:
"""
production_info = get_production_row_by_id(production_id)
return production_info.production_brand if production_info else '-' | 62,198 |
def print_sami(s, idfile, queryText, outFile=True, verbose=True):
# ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
""" Define a Row Iterator for screen output """
# Prepare some variables.
counter = 0
idlist = []
# Iterate over all supplied rows.
if outFile:
... | 62,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.