content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
def _is_authenticated_query_param(params, token):
"""Check if message is authentic.
Args:
params (dict): A dict of the HTTP request parameters.
token (str): The predefined security token.
Returns:
bool: True if the auth param matches the token, False if not.
"""
return para... | f60f0b326ef50e8feafbe91bb18df6b8bb7f55f9 | 674,888 |
import os
def determine_upload_location(instance, filename):
"""
Determine where files are going to be uploaded
Args
instance: Candidate user instance
filename: filename of resumes being uploaded
Return
path of the resume
"""
_, extension = os.path.splitext(filename)
retu... | 067596f20f1fd457515633883980d689cfa4b936 | 674,889 |
def nohits_tag_from_conf(conf_file):
"""
Construct a 'nohits' tag from a fastq_screen conf file
The 'nohits' tag is a string of '0' characters, with
the number of zeroes equal to the number of 'DATABASE'
lines in the conf file.
For example: if there are 3 genomes in the file then
the 'nohi... | d7f0836d0526733bda9c7b557c10e6157ac2586a | 674,890 |
import imp
import sys
def mock_module(module_name):
"""
Create an empty module.
Use this to mock modules for testing if there's
no resonable way how to install the module via setup.py.
"""
head = module_name.split(".")
tail = []
# lookup for the longest available module path
pare... | 1b8de87366f5ab4066aa401e77c64844f3a9ca7b | 674,891 |
def fetch_cols(fstream, split_char=','):
"""
Fetch columns from likwid's output stream.
Args:
fstream: The filestream with likwid's output.
split_car (str): The character we split on, default ','
Returns (list(str)):
A list containing the elements of fstream, after splitting at... | f108eb94851f73c90503dbaf7ff69d86e18d268d | 674,892 |
import re
def get_event_id_from_url(event_url):
"""
:param event_url: chronotrack url (str)
:return: event id contained in url, None if not present (int)
"""
event_regex = re.compile("event-([0-9]+)")
match = event_regex.search(event_url)
if match:
return match.group(1)
else:
... | be11ac3eb8f7565cd86b1a0ec2979f305c4572a9 | 674,893 |
import requests
from bs4 import BeautifulSoup
import re
def get_opera_extension(extension_url):
"""
Get the file url, extension name and the version of the Opera extension
"""
response = requests.get(extension_url)
html = response.text
s = BeautifulSoup(html, "lxml")
extension_version = s... | d09af3edb5e8718d10e73669341fca4e152d600c | 674,894 |
def flat_dict(od, separator='_', key=''):
"""
Function to flatten nested dictionary. Each level is collapsed and
joined with the specified seperator.
:param od: dictionary or dictionary-like object
:type od: dict
:param seperator: character(s) joining successive levels
:type seperator: str... | b77bcf9cc3c96c930a098512398cf01d3bff03db | 674,896 |
from typing import Dict
from typing import Set
def breadth_first_search(graph: Dict, start: str) -> Set[str]:
"""
>>> ''.join(sorted(breadth_first_search(G, 'A')))
'ABCDEF'
"""
explored = {start}
queue = [start]
while queue:
v = queue.pop(0) # queue.popleft()
for w in grap... | 142ad7b4fd69edbe4b925de5684514acb1d68405 | 674,898 |
def register(key, version, description=None,
format='json', config=False,
fnc_slicing=None,
shipping_group='default'):
"""
A decorator used to register a function as a metric collector.
Decorated functions should do the following based on format:
- json: return JS... | abd42fadaea04fb51dfd2e065dbefc937b065b8a | 674,899 |
def check_moas_cpds_doses(df_moa_cpds):
"""
check if moas have the same compounds in all doses,
and return the moas that don't have the same numbers of compounds.
params:
df_moa_cpds: dataframe of distinct moas with only their corresponding
list of compounds for all doses.
Returns:
... | c1bdd74de211845d5dfd4a6fcaa849bbff1303d7 | 674,900 |
def get_marker_list():
"""
Returns list of markerstyles ['o', 'v', 's', '^', '8', '*', 'h', '+']
Returns
-------
list_markers : list (of str)
List of markerstyles
"""
list_markers = ['o', 'v', 's', '^', '8', '*', 'h', '+']
return list_markers | 8e76a735682f8404f715d80cef2b914bfabc079f | 674,902 |
import os
import jinja2
def render_template(template_path, context):
"""Returns the rendered contents of a jinja template
:param template_path: The path to the jinja template
:param context: Jinja context used to render template
:return: Results of rendering jinja template
"""
path, filename... | 2767fb8c9fdbaec12d42b22336f61fafa19b1816 | 674,903 |
def get_attrs():
"""get attrs."""
attr_map = {"enable_bisect_optimize": True}
return attr_map | ab52b313b151b0424458885ca529d1cde6009632 | 674,904 |
from pathlib import Path
def config_dir():
"""Path to the config directory."""
return Path.home() / '.one/' | c0a51f6e206405fa8c82f5c93d5a087180711ee2 | 674,905 |
def isModerator(forum, user):
"""Determines whether the given user is a moderator of this forum or not."""
if not forum.moderators:
return False
if not user:
return False
for mod in forum.moderators:
if mod.user_id() == user.user_id():
return True
return False | 8664327c1e6207577c57cbf9253d295bd3f38bc3 | 674,906 |
from typing import List
import glob
def get_scripts_from_bin() -> List[str]:
"""Get all local scripts from bin so they are included in the package."""
return glob.glob("bin/*") | 91594517a51197f191afb0418a5e25832fbb5cdf | 674,907 |
def parse_singleline_row(line, columns):
"""
Parses a single-line row from a "net use" table and returns a dictionary mapping from
standardized column names to column values.
`line` must be a single-line row from the output of `NET USE`. While `NET USE` may represent
a single row on multiple ... | 52a24b3c6c00c89a44311a5dfdaf02e3fc6026a6 | 674,908 |
def merge_and_count(first, second):
"""
It is explained during lecture that while implementing merge part there is a single path that
counts the inversions automatically if the second part of the
"""
i = 0
j = 0
ret = []
number_of_inversion = 0
while len(ret) != len(first) + len(sec... | de1ee98eb0d641d10c1e34eca68e5715bb0ab577 | 674,909 |
from typing import Sequence
def mean(s: Sequence[float]) -> float:
"""Return the mean of a sequence of numbers"""
return sum(s) / len(s) | e539681468af48364ef47b0e15b859346baba004 | 674,910 |
def _m_verify_g(state, method_name, state_var_name, arg, desired_val, \
depth, verbose=0):
"""
Pyhop 2 uses this method to check whether a goal_method has achieved the
goal that it promised to achieve.
"""
if vars(state)[state_var_name][arg] != desired_val:
raise Exception(f"depth {d... | 1667745920adeaf2e453fc5c3a632bad30a4c99e | 674,911 |
import os
import json
def load_json(location, file_name):
"""
Load .json file based on given location and file name
and return its content
"""
full_path = os.path.join(location, file_name)
with open(full_path, "r", encoding='utf-8', errors='ignore') as output_file:
json_load_fi... | 5bdb7fb0405f899482274a7e3e75f809a4cf329b | 674,912 |
from enum import Enum
def _get_name(enum_value: Enum):
"""Create human readable name if user does not provide own implementation of __str__"""
if enum_value.__str__.__module__ != "enum":
# check if function was overloaded
name = str(enum_value)
else:
name = enum_value.name.replace(... | 884be95d0969fbd34c0dccfe3931baf495be3f84 | 674,913 |
def get_bb_center(obj):
"""Return center coordinates of object bounding box."""
((x0, y0, z0), (x1, y1, z1)) = obj.GetBoundingBox()
xc = (x0 + x1)/2
yc = (y0 + y1)/2
return xc, yc | d620a99815b951f7bd927c5ffa055bc90842c745 | 674,914 |
def insert_prefix(text, keyword, inserted_text):
"""
在关键字前面插入文本 (从头算起的第1个关键字)
:param text:
:param keyword:
:param inserted_text:
:return: str: 插入后的结果
"""
position = text.find(keyword)
if position != -1:
new_text = text[:position] + inserted_text + text[position:]
retu... | 2b330848c9b284de6ee2ffaf5f3e89e2e013bba8 | 674,916 |
def merge_l_t(l, lt):
"""
Merge a list of tuples lt, each of three values into three lists l.
For example: [('a', 'b', 'c'), ('a', 'd', 'e')] ->
[['a', 'a'], ['b', 'd'], ['c', 'e']]
"""
for t in lt:
l[0].append(t[1])
l[1].append(t[2])
l[2].append(t[0])
return l | 145c09bfbe1d351e7044a36622414fde610b8c1d | 674,917 |
import socket
import time
def read_server_and_port_from_file(server_connection_info):
"""
Reads the server hostname and port from a file, which must contain
'hostname port'. Sleeps if the file doesn't exist or formatting was off (so
you can have clients wait for the server to start running.)
... | 92243aebd0e6ee21ab56550088d0e447fc6f8fed | 674,918 |
import posixpath
def join_uri(bucket, *key_paths):
"""
Compose a bucket and key into an S3 URI. The handling of the components of the key path works similarly to
the os.path.join command with the exception of handling of absolute paths which are ignored.
:param bucket: Bucket name
:param key_path... | ff557e942e5d91380a8ca81414ab09a193a91f7a | 674,919 |
def resultproxy_to_dict(resultproxy):
"""
Converts SQLAlchemy.engine.result.ResultProxy to a list of rows,
represented as dicts.
:param resultproxy: SQLAlchemy.engine.result.ResultProxy
:return: rows as dicts.
"""
d, a = {}, []
for rowproxy in resultproxy:
# rowproxy.items() retu... | 3398ca1d19b3d23a793cf18c0beeb9923430410b | 674,920 |
def server_side(connection, window_info, kwargs):
"""never allows a signal to be called from WebSockets; this signal can only be called from Python code.
This is the default choice.
>>> # noinspection PyShadowingNames
... @signal(is_allowed_to=server_side)
... def my_signal(window_info, arg1=None):... | 4117c48728b28e3bb8eb90114f8d8749785c8768 | 674,922 |
import ntpath
import posixpath
def isabs_anywhere(filename):
"""Is `filename` an absolute path on any OS?"""
return ntpath.isabs(filename) or posixpath.isabs(filename) | 25a38d459a47dd6a16c7c783159eb75885ab491a | 674,923 |
import requests
import sys
def get_device_apps(baseurl, headers, device_id):
"""Return applicaitons installed for a specific device."""
# The API endpont to target
endpoint = f"/v1/devices/{device_id}/apps"
# Initiate var that will be returned
data = None
try:
# Make the api call to... | 63205fa79c0fa1634c4de3d84f673efd3eab5f9b | 674,924 |
def _ll_empty_array(DICT):
"""Memo function: cache a single prebuilt allocated empty array."""
return DICT.entries.TO.allocate(0) | f7b8a60f713dcacbb31e00e0810bb76e2c48c499 | 674,926 |
def _derive_kingdom_column(dfcolnames):
"""estimate the kingdom column headername based on
simple ruleset
kingdom:
A/ screen column names for kingdom (and all upper and lower
alternatives)
B/ if A fails, assuming no kingdom column available
(assuming always a single column with t... | 61157513861952a79be3eb0276b594fb7210a9b5 | 674,927 |
def list_to_str(block, delim=", "):
"""
Convert list to string with delimiter
:param block:
:param delim:
:return: list_str
"""
list_str = ""
for b in block:
# print("processing:", block)
if len(list_str) > 0:
list_str = list_str + delim
list_str = li... | 26da3a41e0e15d0659fcd71a8bcb14fd9a328a6c | 674,928 |
def verify_survey_dtypes(survey):
"""
Verifies if dataframe is formed of desired data types
Arguments:
survey: an instance of the Survey class.
Returns True on match and False otherwise
"""
actual_column_types = survey.data.dtypes
for column in survey.data.columns:
if actual_co... | 33a511dc0e882555f1c8ca5dc6054995202d7276 | 674,929 |
from distutils.spawn import find_executable
def isTool(name):
"""
Check if a tool is on PATh and marked as executable.
Parameters
---
name: str
Returns
---
True or False
"""
if find_executable(name) is not None:
return True
else:
return False | ddb75ceb6cbe1427e32a8a15d47730b0384de038 | 674,930 |
def pal_draw_condition_2(slope):
"""
Second draw condition of polygonal audience lines. The slope of the
lines must be zero or positive
Parameters
----------
slope : float
Slope of the polygonal audience line.
Returns
-------
condition_2 : bool
True if condition has... | d03a6318a9fc864940fc7087e934eea42597a9b3 | 674,931 |
import requests
def get_usdt_price_banner_from_aicoin():
"""
从 banner 获取 usdt 的价格
"""
headers = {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Referer": "https://www.aicoin.cn/",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit... | a2a0c8a813b46e4f207070b8b329c2cc223a2913 | 674,932 |
import numpy
def neural_network(inputs, weights, normalize):
"""
The naked neural network
Args:
inputs: inputs to the input layers
weights: numpy matrices representing the weights between the layers
of neurons
normalize: the function that process the neuron value furth... | f12dd56b3d5dd03577717dd673156bc3765a66d8 | 674,933 |
import re
def validate_fqdn(fqdn):
"""Checks a given string if it's a valid FQDN"""
fqdn_validation = re.match(
'(?=^.{4,253}$)(^((?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}$)',
fqdn,
)
if fqdn_validation is None:
return False
else:
return True | 078c8fed1bcd6ac0d001c8ec1ef33fd2211a7de3 | 674,934 |
from typing import OrderedDict
def names_to_abbreviations(reporters):
"""Build a dict mapping names to their variations
Something like:
{
"Atlantic Reporter": ['A.', 'A.2d'],
}
Note that the abbreviations are sorted by start date.
"""
names = {}
for reporter_key,... | 7668bd7c5c1eeafa1c1b689cfeb8f258a4c8b192 | 674,935 |
def get_subgrids(kgrids, params):
"""Returns subkgrids of multiple given sources
"""
sub_params = {}
sub_summ = {}
for source in kgrids:
sub_params[source] = kgrids[source].get_params(params=params)
sub_summ[source] = kgrids[source].get_summ(params=params)
return sub_summ, sub_... | c93475152c1ceb518d1ab9eff1a64b6925afde68 | 674,936 |
from pathlib import Path
def fullpath(path_or_str=''):
"""
Path: Expand path relative to current working directory.
Accepts string or pathlib.Path input. String can include '~'.
Does not expand absolute paths. Does not resolve dots.
"""
path = Path(path_or_str).expanduser()
if not path.is_... | eea1f856dbe56e97fbf60d3b052540b56e70933e | 674,937 |
def subseteq_table(table_left, table_right):
"""
Checks whether one binary relation of two sets (presented as bool table) is
subset or equals another. Tables should be given as lists of bool lists and
should have the same dimensions. Result is bool.
table_left ?\subseteq table_right
"""
if ... | 0894675bccbf6eb2d5c0fe79d38e46e5172ea0b2 | 674,938 |
def pyramid_csrf_request(pyramid_request):
"""Dummy Pyramid request object with a valid CSRF token."""
pyramid_request.headers['X-CSRF-Token'] = pyramid_request.session.get_csrf_token()
return pyramid_request | d988e757cbe5c65c3178a00e0a849716e1df867d | 674,939 |
import os
def defaultTestFilePath():
"""
get the full path of the default data file
"""
me = os.path.realpath(__file__)
base = os.path.split(me)[0]
testfile = os.path.join(base, 'results_roadRunnerTest_1.txt')
if os.path.isfile(testfile):
return testfile
else:
raise Ex... | 72c9cb4515e231c5fc4cbbea02ffb28e45cd1b94 | 674,940 |
from decimal import Decimal
import datetime
import six
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_text(strings_only=True).
"""
return isinstance(obj, six.integer_types + (type(None), f... | 255e01aa14b4b7c854e404104748de8ff6fa0831 | 674,941 |
def get_period_for_day(period_list, day, default_endless=True):
"""Identify which open period in a list matches a day. day can be None.
If none of them match:
- If there is an endless period and default_endless is true,
return the endless period.
- Otherwise, return None.
"""
default = No... | f74831613a7acd4c64d0d805762f9d047f1e4f8e | 674,942 |
import math
def calc_vo2(distance, time):
"""Calculate VO2 max based on a race result.
Taken from Daniels and Gilbert. See, for example:
* http://www.simpsonassociatesinc.com/runningmath1.htm
* "The Conditioning for Distance Running -- the Scientific Aspects"
Parameters
----------
distan... | 81315946c3e428321237d291feeeab10f002d876 | 674,944 |
import re
def isPalindrome(s):
"""
:type s: str
:rtype: bool
"""
if not s:
return True
s = ''.join(re.findall(r'[0-9a-zA-Z]', s))
s = s.lower()
start = 0
end = len(s) - 1
while start < end:
if s[start] == s[end]:
start += 1
end -= 1
... | 7eea3ecc0dab710dd9ac6bff27d00c489186a0aa | 674,945 |
def get_xml_event_start(event_buffer):
""" get the event start of an event that is different (in time)from the
adjoining event, in XML format """
result_pattern = "<result offset='"
time_key_pattern = "<field k='_time'>"
time_start_pattern = "<value><text>"
time_end_pattern = "<"
event_... | 68df30706cd649eb2996eeee1f709aa1861663b7 | 674,946 |
from typing import OrderedDict
def dict_sort(in_dict: dict)-> OrderedDict:
"""
sort dict by values, 给字典排序(依据值大小)
Args:
in_dict: dict, eg. {"游戏:132, "旅游":32}
Returns:
OrderedDict
"""
in_dict_sort = sorted(in_dict.items(), key=lambda x:x[1], reverse=True)
return OrderedDict(i... | b32187f78861c2f04c377030ecc45b1892ace708 | 674,947 |
import subprocess
def cli_call(command):
"""
Makes the operating system process calls to test the CLI properly.
"""
proc = subprocess.Popen(command,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
)
out,err = proc.communicate()
return out, err, proc.returncode | 980dd289204f9ab1fdaa2f111eacd7133f61db1e | 674,948 |
def mc_to_float(value):
"""
Convert from millicents to float
Args:
value: millicent number
Returns: value in float
"""
return float(value) / (100 * 1000) | 9c72ca3b625a5caaaca8d1a73c2a96bf1117bf11 | 674,949 |
def get_exploding_values(list_of_values: list) -> tuple:
"""
This function will determine which value is the largest in the list, and
will return a tuple containing the information that will have the largest percentage
within the pie chart pop off.
:param list_of_values:
:return: A tuple of 'exp... | aebb9bf98c969871b99c4772ee55876431510b26 | 674,950 |
import requests
def make_get_request(subreddit, after, hot_list):
"""
makes get request to reddit API
"""
url = 'https://www.reddit.com/r/{}/hot.json'.format(subreddit)
if after:
payload = {
'after': after, 'count': str(len(hot_list)), 'limit': '100'
}
else:
... | 935480988f442e8dd4827d4f5bdb614e7219887b | 674,951 |
import os
def GetHeaderFilesInDir(dir_path):
"""Return a list of all header files under dir_path
(as absolute native paths)."""
all_files = []
for root, dirs, files in os.walk(dir_path):
all_files.extend([os.path.join(root, f) for f in files if f.endswith('.h')])
return all_files | 3fadd543f0414e55f1412663b8cf855341652b3b | 674,952 |
def conv_out_dim(w, conv):
"""Assumes square maps and kernels"""
k = conv.kernel_size[0]
s = conv.stride[0]
p = conv.padding[0]
return int((w - k + 2 * p) / s + 1) | 5165b4e4cbf345e2bab24f3a46b11c9873788aab | 674,953 |
import string
def safe_string(unsafe_str, replace_char="_"):
"""
Replace all non-ascii characters or digits in provided string with a
replacement character.
"""
return ''.join([c if c in string.ascii_letters or c in string.digits else replace_char for c in unsafe_str]) | 683fc4937d6a8b9ad3deffa751652fd87daebca2 | 674,954 |
def arraylike(thing):
"""Is thing like an array?"""
return isinstance(thing, (list, tuple)) | 78bebb4bddc3505ea1990af8a8a7ed25dfb504e2 | 674,955 |
def IssueIsInHotlist(hotlist, issue_id):
"""Returns T/F if the issue is in the hotlist."""
return any(issue_id == hotlist_issue.issue_id
for hotlist_issue in hotlist.items) | 31f48cb2c4eeddc450239edcf8d293e554cba265 | 674,956 |
import torch
def batched_index_select(data, dim, indicies):
"""
Args:
data: tensor
dim: from which dimention to select
indicies: to select
Returns:
Selects elements of given indices in given dimention
"""
views = [data.shape[0]] + [1 if i != dim else -1 for i in r... | c34ab1b39257b3d843e44f092dae4ec8c4f49575 | 674,957 |
def makeNormalizedData(data, newCol, defaultVal = 0):
"""
Ensure that all of the labels in newCol exist in data
"""
for item in data:
for key in newCol:
if (key not in item):
item[key] = defaultVal
return data | 86ab19e27a25184a7ac5b24950fcc5831ca040b1 | 674,958 |
from typing import Type
from typing import Any
import types
from typing import List
import inspect
def get_all_subclasses_in_module(
parent_class: Type[Any],
module: types.ModuleType,
exclude_private: bool = True,
exclude_abstract: bool = False) -> List[Type[Any]]:
"""Returns all classes derived fro... | 918a254cbae753d3002d11e5879890ab8f8aa30f | 674,960 |
import json
def to_json(qc_config, out_file=None):
"""Given qc_config return json"""
if out_file:
with open(out_file, 'w') as outfile:
json.dump(outfile, qc_config)
else:
return json.dumps(qc_config) | 20b2dbcbf97c98f6933cac5fed967ae0996d8a93 | 674,962 |
def apply_application_controller_patch(zha_gateway):
"""Apply patches to ZHA objects."""
# Patch handle_message until zigpy can provide an event here
def handle_message(sender, profile, cluster, src_ep, dst_ep, message):
"""Handle message from a device."""
if (
not sender.initial... | 9be805c556a96f48bf41a368385bcd8c0bcbea5c | 674,964 |
def Count_loci(Monomorphics, threshold):
"""Count number of individuals sampled per locus. Retain those \
loci that are >= the threshold."""
with open(Monomorphics, 'r') as Infile:
LineNumber = 0
TotalLoci = 0
TotalBP = 0
MonoLociLengths = []
fo... | a720e9ad0e1e75a5f9d0aa9dda32b775be359d8a | 674,965 |
def get_require_modules():
"""
Get main python requirements modules
"""
with open("./BacterialTyper/config/python/python_requirements_summary.csv", 'r') as f:
myModules = [line.strip().split(',')[0] for line in f]
return myModules | c405fdbcedca59356b4a115bb30a8e0567afde5d | 674,966 |
def tag(*tags):
"""Decorator to add tags to a test class or method."""
def decorator(obj):
if len(getattr(obj, '__bases__', [])) > 1:
setattr(obj, 'tags', set(tags).union(*[
set(base.tags)
for base in obj.__bases__
if hasattr(base, 'tags')
... | 5ea73a8d4169a25a79d91e3c5e9497d2fcf61999 | 674,967 |
def adjust_coordinates(regtype, start, end, strand):
"""
:param regtype:
:param start:
:param end:
:param strand:
:return:
"""
norm = 1 if strand in ['+', '.'] else -1
if regtype == 'reg5p':
if norm > 0:
s, e = start - 1000, start + 500
else:
s... | 08afb19624b5147a79b354913c5d38e21025fe5b | 674,968 |
import os
def separate_files(files):
"""
Separate the input files in folder
Given all input arguments to the command line files entry, separate them in
a list of lists, grouping them by folders. The number of identified folders
will determine the number of information instances to create
"""
... | d800d3bc74fa209edd2973dc574913b646faaa7f | 674,969 |
def run_zip_surject_input(job, context, gam_chunk_file_ids):
"""
run_whole_surject takes input in different format than what we have above, so we shuffle the
promised lists around here to avoid a (probably-needed) refactor of the existing interface
"""
return list(zip(*gam_chunk_file_ids)) | 85bf7ff46624dfc2b7684e078dc4ef55e621b109 | 674,970 |
def pmd_core_mask(host):
""" Get PMD CPU hex mask from target and return as string with leading
'0x' stripped """
hex_value = None
if not host.exists("ovs-vsctl"):
raise Exception("Failed to find ovs-vsctl in system PATH")
with host.sudo():
stdout = host.check_output("ovs-vsctl... | de079c024f340d3cd2b100c402dcd4fa31099640 | 674,971 |
import sys
def parse_args(cmd):
"""
Parse command-line args applying shortcuts and looking for help flags
"""
shortcuts = {
'register': 'auth:register',
'login': 'auth:login',
'logout': 'auth:logout',
'create': 'apps:create',
'destroy': 'apps:destroy',
'... | e557e9e773ec847ab99c76f37d690a16bd94e592 | 674,972 |
def _round_pow_2(value):
"""Round value to next power of 2 value - max 16"""
if value > 8:
return 16
if value > 4:
return 8
if value > 2:
return 4
return value | 35458a3a894df8fc579d027f72a6328ba8b8061d | 674,973 |
def restricted(func):
"""
A decorator to confirm a user is logged in or redirect as needed.
"""
def login(self, *args, **kwargs):
# Redirect to login if user not logged in, else execute func.
if not self.current_user:
self.redirect("/login")
else:
... | e348aca0197800c2d7f7008c603488d7687fdb66 | 674,974 |
def binary_search_2(arr, elem, start, end):
"""
A method to perform binary search on a sorted array.
:param arr: The array to search
:param elem: The element to search
:param start: start position from where to start searching
:param end: start position till where to search
:return: The in... | 026742362d050e4aae3ff769f76f7b8eafaeab25 | 674,975 |
def get_data_from_epochs(epochs):
"""
epochs: mne.Epochs
returns np array of shape (nb_epochs, sampling_rate*epoch_length)
"""
return epochs.get_data().squeeze() | 620ec5ee06282cb3a7317442c1d03d949abf8597 | 674,976 |
def get_bucket(config, length):
"""classify each example into given buckets with its length."""
for i, (start, end) in enumerate(config.buckets):
if start <= length < end:
return config.buckets[i]
return config.buckets[-1] | 42553e8e13a42ac3b81b3dcac8b19ed512235fc3 | 674,977 |
import os
def ListFiles(base_dir):
"""Recursively list files in a directory.
Args:
base_dir: directory to start recursively listing in.
Returns:
A list of files relative to the base_dir path or
An empty list of there are no files in the directories.
"""
directories = [base_dir]
files_list = ... | 1fb2a2b3d8b249cd5e8a206b87522626b13628e2 | 674,978 |
def product_from_branch(branch):
"""
Return a product name from this branch name.
:param branch: eg. "ceph-3.0-rhel-7"
:returns: eg. "ceph"
"""
if branch.startswith('private-'):
# Let's just return the thing after "private-" and hope there's a
# product string match somewhere in... | 7137290d6454cbe474d0ca571c326d442fcb1975 | 674,979 |
def pollution_grade(aqi: int) -> int:
"""Translate aqi levels to pollution grade."""
if aqi <= 50: return 0
elif 50 < aqi <= 100: return 1
elif 100 < aqi <= 150: return 2
elif 150 < aqi <= 200: return 3
elif 200 < aqi <= 300: return 4
else: return 5 | e66405726ceb49acdca093caca9ac5cffd6d201b | 674,980 |
def calHeatTransferCoefficientEq1(Nu, GaThCo, CaPaDi):
"""
calculate heat transfer coefficient [J/m^2.s.K]
**note: for spherical particles
args:
Nu: Nusselt number
GaThCo: gas thermal conductivity [J/m.s.K]
CaPaDi: catalyst particle diameter [m]
"""
# try/except
... | f96f41c60a983d7e238c967a12b80fadce62ff6e | 674,981 |
def diagonal(a, *parms):
"""Rough replacement for Numeric.diagonal."""
return a.diagonal() | 17db70df21a0706ea55b241724a392d020f49b5f | 674,982 |
def test_create_dataframe(data_frame, list_of_col):
"""
Testing whether a dataframe satisfy the following conditions:
The DataFrame contains only the columns that you specified as the second argument.
The values in each column have the same python type
There are at least 10 rows in the DataFrame.
... | 3b4e129641da92a907c50e21afd93feff632dcd2 | 674,983 |
def maybe_coeff_key(grid, expr):
"""
True if `expr` could be the coefficient of an FD derivative, False otherwise.
"""
if expr.is_Number:
return True
indexeds = [i for i in expr.free_symbols if i.is_Indexed]
return any(not set(grid.dimensions) <= set(i.function.dimensions) for i in index... | acc21eb144ea24a6a96b56ceed12f81696430976 | 674,985 |
def create_vm_aws(vpc, region, ami, vm_name, nfkey, source):
"""Create Terraform Module for AWS VM."""
tf_module_vm = {
"source": "%s/m-aws-instance" % source,
"awsRegion": region,
"vm_name": vm_name,
"nfnKey": nfkey,
"ami": ami,
"eth1_scriptPath": source,
... | a88fc771bcbc8676a7417246efe4af85e5bd6442 | 674,986 |
import numpy
def plane_fit(points):
"""
This fits an n-dimensional plane to a set of points. See
http://stackoverflow.com/questions/12299540/plane-fitting-to-4-or-more-xyz-points
:parameter points:
An instance of :class:~numpy.ndarray. The number of columns must be
equal to three.
... | 16c6c337ae73e2b0d3e91d719b69af1673ddc931 | 674,987 |
import re
def row_skipper(file):
"""
Count how many rows are needed to be skipped in the parsed codebook.
Parameters:
file (character): File name of the parsed codebook
Returns:
count: The number of lines to be skipped
"""
with open(file, 'r') as codebook:
count = 0
... | 3060ae59b3f9b378d144d8f85090adf5200d35f4 | 674,988 |
def validarArea(vL, vA, vB):
"""
Eliminar puntos grises y fondo
param: vL: valor espectro L
param: vA: valor espectro a
param: vB: valor espectro b
"""
# validate grayscale and mark points
if vL >= 0 and vL <= 100 and vA > -5 and vA < 5 and vB > -5 and vB < 5:
return False
el... | 628eacc23645dfc6bbb3d69a17f6dd0cefceba62 | 674,989 |
import os
def get_oci_config():
"""
Returns the OCI config location, and the OCI config profile.
"""
oci_config_location = os.environ.get(
"OCI_CONFIG_LOCATION", f"{os.environ['HOME']}/.oci/config"
) # os.environ['HOME'] == home/datascience
oci_config_profile = os.environ.get("OCI_CON... | f152f5f325bdcaf6b58d493b118579d16970f9e1 | 674,990 |
def select_year(movie_list:list, year:int):
"""
Select movies filmed in a specific year and returns a list of tuples (name, location)
"""
n_year_movies = []
for movie in movie_list:
if year in movie:
n_year_movies.append((movie[0],movie[-1]))
print(f"Selected {len(n_year_movi... | 95aa1c4a9fa6e163f6df734648a8caa077fdbdd4 | 674,991 |
import logging
def ping():
"""
Ping the endpoint
:return:
"""
logging.info('/ping')
return "ping Ok" | 67ba7c799edc4bf211454b22638416400a6da179 | 674,992 |
import ast
def robust_literal_eval(val):
"""Call `ast.literal_eval` without raising `ValueError`.
Parameters
----------
val : str
String literal to be evaluated.
Returns
-------
Output of `ast.literal_eval(val)', or `val` if `ValueError` was raised.
"""
try:
retu... | 7c5136d72354ad6018b99c431fc704ed761ea7db | 674,993 |
def maze_solver(maze, start=(1, 1), end=None,
moves=lambda x, y: ((x+1, y), (x-1, y), (x, y+1), (x, y-1)),
is_wall=lambda maze, x, y: maze[y][x] != ' '):
"""Solves a maze, given a stringified maze, an optional start
(default (1, 1)), an optional end (default to the bottom right), and an
opti... | 428e72d2fceb24f5cc2105c0b130953715e1a4b6 | 674,994 |
def hasattr_explicit(cls, attr):
"""Returns if the given object has explicitly declared an attribute"""
try:
return getattr(cls, attr) != getattr(super(cls, cls), attr, None)
except AttributeError:
return False | ff16748ccdebe7f3ff76c117bc1284dc4eb5366c | 674,995 |
def compute_num_trainable_params(architecture_fn):
"""Evaluate the number of trainable model parameters."""
N_dummy = 1
model, _, _, _ = architecture_fn(N_dummy)
return sum(p.numel() for p in model.parameters() if p.requires_grad) | 7f00c1a3681c3ca8c76bf9a0814381ff831f493d | 674,996 |
async def get_root() -> str:
"""Echo the content of the body. """
return """
<html>
<head>
<title>
Some knowledge required.
</title>
</head>
<body>
<h1>
Hello World!
</h1>
</body>
</html>
... | 06aee39ac267276f5f1bee8d71416a914506df27 | 674,997 |
import re
def parse_out_streaming():
"""
Parses rpc.proto to see if methods are streaming or not
This information can't be gleaned from rpc.json since protoc-gen-doc does
not return this information
"""
with open('rpc.proto') as data_file:
lines = data_file.readlines()
streaming_... | 8ae8485e07b17d23576f49483071835ed08da36e | 674,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.