content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_stat_check(string, exception):
"""Test stat_check parse function for valid entries."""
with exception:
result = stat_check(string)
print(result) | 5,335,300 |
def git_hook():
""" Run pylama after git commit. """
from .main import check_files
_, files_modified, _ = run("git diff-index --cached --name-only HEAD")
options = parse_options()
setup_logger(options)
check_files([f for f in map(str, files_modified)], options) | 5,335,301 |
def get_lockfile_path(repo_name: str) -> Path:
"""Get a lockfile to lock a git repo."""
if not _lockfile_path.is_dir():
_lockfile_path.mkdir()
return _lockfile_path / f"{repo_name}_lock_file.lock" | 5,335,302 |
def path_to_graph(hypernym_list, initialnoun):
"""Make a hypernym chain into a graph.
:param hypernym_list: list of hypernyms for a word as obtained from wordnet
:type hypernym_list: [str]
:param initialnoun: the initial noun (we need this to mark it as leaf in the tree)
:type initialnoun: str
... | 5,335,303 |
def make_3d_grid():
"""Generate a 3d grid of evenly spaced points"""
return np.mgrid[0:21, 0:21, 0:5] | 5,335,304 |
def test_main_reboot(capsys, reset_globals):
"""Test --reboot"""
sys.argv = ['', '--reboot']
Globals.getInstance().set_args(sys.argv)
mocked_node = MagicMock(autospec=Node)
def mock_reboot():
print('inside mocked reboot')
mocked_node.reboot.side_effect = mock_reboot
iface = MagicMo... | 5,335,305 |
def rho(flag, F, K, t, r, sigma):
"""Returns the Black rho of an option.
:param flag: 'c' or 'p' for call or put.
:type flag: str
:param F: underlying futures price
:type F: float
:param K: strike price
:type K: float
:param t: time to expiration in years
:type t: float
:pa... | 5,335,306 |
async def novel_series(id: int, endpoint: PixivEndpoints = Depends(request_client)):
"""
## Name: `novel_series`
> 获取小说系列的信息
---
### Required:
- ***int*** **`id`**
- Description: 小说系列ID
"""
return await endpoint.novel_series(id=id) | 5,335,307 |
def to_raw(
y: np.ndarray,
low: np.ndarray,
high: np.ndarray,
eps: float = 1e-4
) -> np.ndarray:
"""Scale the input y in [-1, 1] to [low, high]"""
# Warn the user if the arguments are out of bounds, this shouldn't happend.""""
if not (np.all(y >= -np.ones_like(y) - eps) and np.all(y <= np.o... | 5,335,308 |
def etched_lines(image):
"""
Filters the given image to a representation that is similar to a drawing being preprocessed with an Adaptive Gaussian
Threshold
"""
block_size = 61
c = 41
blur = 7
max_value = 255
# image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
img_blur = cv2.Gauss... | 5,335,309 |
def init(obj, yaml_file):
"""Initialize a new dashboard YAML file"""
name = click.prompt('Dashboard name', default='Example dashboard')
alert_teams = click.prompt('Alert Teams (comma separated)', default='Team1, Team2')
user = obj.config.get('user', 'unknown')
data = {
'id': '',
'n... | 5,335,310 |
def signal(sig, action): # real signature unknown; restored from __doc__
"""
signal(sig, action) -> action
Set the action for the given signal. The action can be SIG_DFL,
SIG_IGN, or a callable Python object. The previous action is
returned. See getsignal() for possible return values.
... | 5,335,311 |
def get_last_position(fit, warmup=False):
"""Parse last position from fit object
Parameters
----------
fit : StanFit4Model
warmup : bool
If True, returns the last warmup position, when warmup has been done.
Otherwise function returns the first sample position.
Returns
-----... | 5,335,312 |
def find_fast_route(objective, init, alpha=1, threshold=1e-3, max_iters=1e3):
"""
Optimizes FastRoute objective using Newton’s method optimizer to
find a fast route between the starting point and finish point.
Arguments:
objective : an initialized FastRoute object with preset start and finis... | 5,335,313 |
def main():
"""Interact with the teragested parser and a shell script."""
pass | 5,335,314 |
def get_version(filename="telepresence/__init__.py"):
"""Parse out version info"""
base_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(base_dir, filename)) as initfile:
for line in initfile.readlines():
match = re.match("__version__ *= *['\"](.*)['\"]", line)
... | 5,335,315 |
def find_child_files(path, searchRecursively=False, wildCardPattern="."):
"""在当前目录中查找文件,若选择searchRecursively则代表着搜索包含子目录, wildCardPattern意思是只搜索扩展名为".xxx"的文件,也可留空代表搜索全部文件. """
all_search_list = ['.','.*','*','']
tmp = list()
if not exists_as_dir(path):
return tmp
for fpath, _, fnames in os.wal... | 5,335,316 |
def check_tx_success(result):
"""
Checks if function :meth:`UcanServer.write_can_msg_ex` successfully wrote all CAN message(s).
:param ReturnCode result: Error code of the function.
:return: True if CAN message(s) was(were) written successfully, otherwise False.
:rtype: bool
"""
return resu... | 5,335,317 |
def cache_contains_keys(connection: 'Connection', cache_info: CacheInfo, keys: Iterable,
query_id: Optional[int] = None) -> 'APIResult':
"""
Returns a value indicating whether all given keys are present in cache.
:param connection: connection to Ignite server,
:param cache_info:... | 5,335,318 |
def add_hosts_to_cluster(cluster_host_list):
"""
Add hosts to cluster
:param cluster_host_list: List of hosts to add to the cluster
:return:
"""
global host_add_failure, api_failure_message
host_add_failure = 'False'
body = cm_client.ApiHostRefList(cluster_host_list)
try:
ap... | 5,335,319 |
def discount_cumsum_trun(x, discount, length):
"""
compute discounted cumulative sums of vectors.
truncate x in length array
:param x:
vector x,
[x0,
x1,
x2,
x3,
x4]
:param length:
vector length,
[3,
2]
:return:
... | 5,335,320 |
def wg_install_scripts(names):
""" Install scripts. """
global wg_scripts_to_install
for name in names.split(" "):
wg_scripts_to_install.append(name)
wg_install_next_script() | 5,335,321 |
def test_scale_merged_intensities_phenix(hewl_merged, ref_hewl, mean_intensity_method):
"""
Compare phenix.french_wilson to scale_merged_intensities(). Current
test criteria are that >95% of I, SigI, F, and SigF are within 2%.
"""
mtz = hewl_merged.dropna()
scaled = scale_merged_intensities(
... | 5,335,322 |
def get_canonical(flop):
"""
Returns the canonical version of the given flop.
Canonical flops are sorted. The first suit is 'c' and, if applicable,
the second is 'd' and the third is 'h'.
Args:
flop (tuple): three pokertools.Card objects
Returns
A tuple of three pokertools.Car... | 5,335,323 |
def normalize_path(path):
"""Normalize and return absolute path.
Expand user symbols like ~ and resolve relative paths.
"""
return os.path.abspath(os.path.expanduser(os.path.normpath(path))) | 5,335,324 |
def _version(lib_name):
"""
Returns the version of a package.
If version cannot be determined returns "available"
"""
lib = importlib.import_module(lib_name)
if hasattr(lib, "__version__"):
return lib.__version__
else:
return "available" | 5,335,325 |
def DeltaDeltaP(y, treatment, left_mask):
"""Absolute difference between ATEs of two groups."""
return np.abs(
ATE(y[left_mask], treatment[left_mask])
- ATE(y[~left_mask], treatment[~left_mask])
) | 5,335,326 |
def test_recycling(pool):
"""
Test no errors are raised for multiple rounds of getting and putting. Kind
of a "catch all" to make sure no errors crop up when resources are
recycled.
"""
# Recycle pool repeatedly in single thread.
for _ in range(5):
rs = [pool.get_resource() for _ in ... | 5,335,327 |
def p_assignment_operator(p):
"""assignment_operator : '='
| MUL_ASSIGN
| DIV_ASSIGN
| MOD_ASSIGN
| ADD_ASSIGN
| SUB_ASSIGN
| LEFT_ASSIGN
... | 5,335,328 |
def test_source_int_name_remote():
"""
test when file_client remote and
source_interface_name is set and
interface is down
"""
interfaces = {
"bond0.1234": {
"hwaddr": "01:01:01:d0:d0:d0",
"up": False,
"inet": [
{
"b... | 5,335,329 |
def flow_cli(ctx):
"""
Fate Flow Client
"""
ctx.ensure_object(dict)
if ctx.invoked_subcommand == 'init':
return
with open(os.path.join(os.path.dirname(__file__), "settings.yaml"), "r") as fin:
config = yaml.safe_load(fin)
if not config.get('api_version'):
raise Value... | 5,335,330 |
def start(isdsAppliance, serverID='directoryserver', check_mode=False, force=False):
"""
Restart the specified appliance server
"""
if force is True or _check(isdsAppliance, serverID, action='start') is True:
if check_mode is True:
return isdsAppliance.create_return_object(changed=True... | 5,335,331 |
def test_and_get_codenode(codenode, expected_code_type, use_exceptions=False):
"""
Pass a code node and an expected code (plugin) type. Check that the
code exists, is unique, and return the Code object.
:param codenode: the name of the code to load (in the form label@machine)
:param expected_code_t... | 5,335,332 |
def reverse_crop(
im_arr: np.array, crop_details: dict
) -> Dict[str, Tuple[Image.Image, int]]:
"""Return the recovered image and the number of annotated pixels per
lat_view. If the lat_view annotation has no annotations, nothing is added
for that image."""
width = 360
height = 720 # TODO: add ... | 5,335,333 |
def get_dates_keyboard(dates):
"""
Метод получения клавиатуры дат
"""
buttons = []
for date in dates:
button = InlineKeyboardButton(
text=date['entry_date'],
callback_data=date_callback.new(date_str=date['entry_date'], entry_date=date['entry_date'])
)
... | 5,335,334 |
def test_match_fn():
"""Test match fn"""
# Define vars
domain = "duckduckgo.com"
regexp = "duck"
# Run scenario
assert dns_matches(domain, regexp) == True | 5,335,335 |
def fetch_price(zone_key='FR', session=None, target_datetime=None,
logger=logging.getLogger(__name__)):
"""Requests the last known power price of a given country
Arguments:
----------
zone_key: used in case a parser is able to fetch multiple countries
session: request session passed... | 5,335,336 |
async def help_test_update_with_json_attrs_not_dict(
hass, mqtt_mock_entry_with_yaml_config, caplog, domain, config
):
"""Test attributes get extracted from a JSON result.
This is a test helper for the MqttAttributes mixin.
"""
# Add JSON attributes settings to config
config = copy.deepcopy(con... | 5,335,337 |
def test_vw_load_paused():
"""
test process is not loaded after predictor is started with paused state
"""
model = DeployedModel(**get_vw_payload(1))
model.status = ModelStatus.paused
assert VWPredictor(model=model, verify_on_load=False).process is None | 5,335,338 |
def cmd_asydns(url, generate, revoke, verbose):
"""Requests a DNS domain name based on public and private
RSA keys using the AsyDNS protocol https://github.com/portantier/asydns
Example:
\b
$ habu.asydns -v
Generating RSA key ...
Loading RSA key ...
{
"ip": "181.31.41.231",
... | 5,335,339 |
def get_stats(method='histogram', save=True, train=True):
"""
Computes statistics, histogram, dumps the object to file and returns it
"""
if os.path.exists(FILE_STATS):
return pickle.load(open(os.path.join(FILE_STATS), "rb"))
elif train:
dataset = _get_dataset()
print("Compu... | 5,335,340 |
def merge_synset(wn, synsets, reason, lexfile, ssid=None, change_list=None):
"""Create a new synset merging all the facts from other synsets"""
pos = synsets[0].part_of_speech.value
if not ssid:
ssid = new_id(wn, pos, synsets[0].definitions[0].text)
ss = Synset(ssid, "in",
PartOf... | 5,335,341 |
def __correlate_uniform(im, size, output):
"""
Uses repeated scipy.ndimage.filters.correlate1d() calls to compute a uniform filter. Unlike
scipy.ndimage.filters.uniform_filter() this just uses ones(size) instead of ones(size)/size.
"""
# TODO: smarter handling of in-place convolutions?
ndi = get... | 5,335,342 |
def clean_all(record):
""" A really messy function to make sure that the citeproc data
are indeed in the citeproc format. Basically a long list of if/...
conditions to catch all errors I have noticed.
"""
record = clean_fields(record)
for arrayed in ['ISSN']:
if arrayed in record:
... | 5,335,343 |
def _create_model() -> Model:
"""Setup code: Load a program minimally"""
model = Model(initial_program, [], load=False)
engine = ApproximateEngine(model, 1, geometric_mean)
model.set_engine(engine)
return model | 5,335,344 |
def candidate_elimination(trainingset):
"""Computes the version space containig all hypothesis
from H that are consistent with the examples in the training set"""
G = set()#set of maximally general h in H
S = set()#set of maximally specific h in H
G.add(("?","?","?","?","?","?"))
S.add(("0","0",... | 5,335,345 |
def mkdir(path_str):
"""
Method to create a new directory or directories recursively.
"""
return Path(path_str).mkdir(parents=True, exist_ok=True) | 5,335,346 |
def j2_raise(s):
"""Jinja2 custom filter that raises an error
"""
raise Exception(s) | 5,335,347 |
def create_project(name=None, description=None, source=None, artifacts=None, environment=None, serviceRole=None, timeoutInMinutes=None, encryptionKey=None, tags=None):
"""
Creates a build project.
See also: AWS API Documentation
:example: response = client.create_project(
name='string'... | 5,335,348 |
def get_image_with_projected_bbox3d(img, proj_bbox3d_pts=[], width=0, color=Color.White):
"""
Draw the outline of a 3D bbox on the image.
Input:
proj_bbox3d_pts: (8,2) array of projected vertices
"""
v = proj_bbox3d_pts
if proj_bbox3d_pts != []:
draw = ImageDraw.Draw(img)
for k in range(0,4):
... | 5,335,349 |
def process_spectrogram_params(fs, nfft, frequency_range, window_start, datawin_size):
""" Helper function to create frequency vector and window indices
Arguments:
fs (float): sampling frequency in Hz -- required
nfft (int): length of signal to calculate fft on -- required
... | 5,335,350 |
def Hellwig2022_to_XYZ(
specification: CAM_Specification_Hellwig2022,
XYZ_w: ArrayLike,
L_A: FloatingOrArrayLike,
Y_b: FloatingOrArrayLike,
surround: Union[
InductionFactors_CIECAM02, InductionFactors_Hellwig2022
] = VIEWING_CONDITIONS_HELLWIG2022["Average"],
discount_illuminant: Boo... | 5,335,351 |
def add_variants_task(req):
"""Perform the actual task of adding variants to the database after receiving an add request
Accepts:
req(flask.request): POST request received by server
"""
db = current_app.db
req_data = req.json
dataset_id = req_data.get("dataset_id")
samples = req_data... | 5,335,352 |
def build_exec_file_name(graph: str,
strt: str,
nagts: int,
exec_id: int,
soc_name: str = None):
"""Builds the execution file name of id `exec_id` for the given patrolling
scenario `{graph, nagts, strt}` .
A... | 5,335,353 |
def setup_comp_deps(hass, mock_device_tracker_conf):
"""Set up component dependencies."""
mock_component(hass, 'zone')
mock_component(hass, 'group')
yield | 5,335,354 |
def set_ticks(ax, tick_locs, tick_labels=None, axis='y'):
"""Sets ticks at standard numerical locations"""
if tick_labels is None:
tick_labels = tick_locs
ax_transformer = AxTransformer()
ax_transformer.fit(ax, axis=axis)
getattr(ax, f'set_{axis}ticks')(ax_transformer.transform(tick_locs))
... | 5,335,355 |
def prefix_parameter(par, prefix):
# type: (Parameter, str) -> Parameter
"""
Return a copy of the parameter with its name prefixed.
"""
new_par = copy(par)
new_par.name = prefix + par.name
new_par.id = prefix + par.id | 5,335,356 |
def extract_discovery(value:str) -> List[dict]:
"""处理show discovery/show onu discovered得到的信息
Args:
value (str): show discovery/show onu discovered命令返回的字符串
Returns:
List[dict]: 包含字典的列表
"""
# ====================================================================================... | 5,335,357 |
def dict_to_networkx(data):
"""
Convert data into networkx graph
Args:
data: data in dictionary type
Returns: networkx graph
"""
data_checker(data)
G = nx.Graph(data)
return G | 5,335,358 |
def to_url_slug(string):
"""Transforms string into URL-safe slug."""
slug = urllib.parse.quote_plus(string)
return slug | 5,335,359 |
def test_readme():
"""README contains doctests, they all pass."""
result = doctest.testfile('../README.rst')
assert result.attempted != 0
assert result.failed == 0 | 5,335,360 |
def _jmi23_helper(model_ref, jmi2, ids):
"""
A helper function to recursively convert from JMI type 2 to JMI type 3.
"""
# Create array for lowest level elements
empties = []
# Loop through each id
for i in ids:
element = model_ref[i]
# Get the parent ID
if isinstan... | 5,335,361 |
def unique_everseen(iterable, key=None):
"""Return iterator of unique elements ever seen with preserving order.
Return iterator of unique elements ever seen with preserving order.
From: https://docs.python.org/3/library/itertools.html#itertools-recipes
Examples
--------
>>> from pygimli.utils... | 5,335,362 |
def is_wrapping(wrapper):
"""Determines if the given callable is a wrapper for another callable"""
return hasattr(wrapper, __WRAPPED) | 5,335,363 |
def sequence_view(sequence_id):
"""
Get a sequence based on the ID and show the details for this sequence
:param sequence_id: ID of the sequence
"""
from conekt.models.relationships.sequence_go import SequenceGOAssociation
current_sequence = Sequence.query.get_or_404(sequence_id)
go_assoc... | 5,335,364 |
def horner(n,c,x0):
"""
Parameters
----------
n : integer
degree of the polynomial.
c : float
coefficients of the polynomial.
x0 : float
where we are evaluating the polynomial.
Returns
-------
y : float
the value of the function ... | 5,335,365 |
def test_conv2d_kernel_size_larger_than_stride_and_split_h():
"""
Feature: same mode, stride < kernel_size, need exchange
Description: split n/c-in/c-out/h
Expectation: compile success
"""
context.set_auto_parallel_context(parallel_mode="semi_auto_parallel", device_num=32, global_rank=0)
str... | 5,335,366 |
def init_app(app):
"""
app.teardown_appcontext() tells Flask to call that function when cleaning
up after returning the response.
app.cli.add_command() adds a new command that can be called with the flask
command.
"""
app.teardown_appcontext(close_db)
app.cli.add_command(init_db_command... | 5,335,367 |
def start():
"""Starts the puzzle game"""
init_puzzle()
while not is_sorted():
prompt_move()
update_puzzle()
print("We have a winner!") | 5,335,368 |
def linlin(x, smi, sma, dmi, dma):
"""TODO
Arguments:
x {float} -- [description]
smi {float} -- [description]
sma {float} -- [description]
dmi {float} -- [description]
dma {float} -- [description]
Returns:
float -- [description]
"""
re... | 5,335,369 |
def _compression_safe_opener(fname):
"""Determine whether to use *open* or *gzip.open* to read
the input file, depending on whether or not the file is compressed.
"""
f = gzip.open(fname, "r")
try:
f.read(1)
opener = gzip.open
except IOError:
opener = open
finally:
... | 5,335,370 |
def gen_headers(value_type, value, header_type="PacketFilter", direction=None, notFilter=False):
"""
helper function constructs json header format
value: a STRING corresponding to value_type
direction: "src" or "dst"
Parameters
----------
value_type : string
a string of header f... | 5,335,371 |
def assert_token(
client: FlaskClient,
opaque_token: str,
expected_token: Dict[str, Any],
):
"""
Provided an opaque token, this function translates it to an
internal token and asserts on it's content.
:param client:
:param opaque_token:
:param expected_token:
:return... | 5,335,372 |
def read_payload(payload: str) -> OneOf[Issue, List[FileReport]]:
"""Transform an eslint payload to a list of `FileReport` instances.
Args:
payload: The raw payload from eslint.
Returns:
A `OneOf` containing an `Issue` or a list of `FileReport` instances.
"""
return one_of(lambda: ... | 5,335,373 |
def _ssim_per_channel(img1, img2, img3, max_val=1.0, mode='test',compensation=1):
"""Computes SSIM index between img1 and img2 per color channel.
This function matches the standard SSIM implementation from:
Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image
quality assessment: from e... | 5,335,374 |
def prepend(
iterable: Iterable[Any],
value: Any,
*,
times: int = 1,
) -> Iterator[Any]:
"""Return an iterator with a specified value prepended.
Arguments:
iterable: the iterable to which the value is to be prepended
value: the value to prepend to the iterable
... | 5,335,375 |
def set_passive_link_state(fw_conn):
"""Set Passive Link State To Auto
Args:
fw_conn (PanDevice): A panos object for device
"""
base_xpath = ("/config/devices/entry[@name='localhost.localdomain']"
"/deviceconfig/high-availability/group/mode/active-passive")
entry_element =... | 5,335,376 |
def list_platform_versions(Filters=None, MaxRecords=None, NextToken=None):
"""
Lists the platform versions available for your account in an AWS Region. Provides summary information about each platform version. Compare to DescribePlatformVersion , which provides full details about a single platform version.
... | 5,335,377 |
def apply_transform(transform, source, target,
fill_value=None, propagate_mask=False):
"""Applies the transformation ``transform`` to ``source``.
The output image will have the same shape as ``target``.
Args:
transform: A scikit-image ``SimilarityTransform`` object.
sou... | 5,335,378 |
def astra(tomo, center, recon, theta, **kwargs):
"""
Reconstruct object using the ASTRA toolbox
Extra options
----------
method : str
ASTRA reconstruction method to use.
num_iter : int, optional
Number of algorithm iterations performed.
proj_type : str, optional
ASTR... | 5,335,379 |
def _with_extension(base: str, extension: str) -> str:
"""
Adds an extension to a base name
"""
if "sus" in base:
return f"{extension}{base}"
else:
return f"{base}{extension}" | 5,335,380 |
def test_demo_inexecutable_script(storage, monkeypatch, capsys):
"""Test error message when user script is not executable."""
monkeypatch.chdir(os.path.dirname(os.path.abspath(__file__)))
script = tempfile.NamedTemporaryFile()
orion.core.cli.main(
[
"hunt",
"--config",
... | 5,335,381 |
def putin_rfid_no_order_api():
"""
无订单的情况下入库, 自动创建订单(类型为生产入库), 订单行入库
post req: withlock
{
lines: [{line_id:~, qty, location, lpn='', sku,
rfid_list[rfid1, rfid2, rfid3...],
rfid_details[{rfid1, weight, gross_weight, qty_inner}, {rfid2}, {rfid3}...}],
}...]
... | 5,335,382 |
def GuessLanguage(filename):
""" Attempts to Guess Langauge of `filename`. Essentially, we do a
filename.rsplit('.', 1), and a lookup into a dictionary of extensions."""
try:
(_, extension) = filename.rsplit('.', 1)
except ValueError:
raise ValueError("Could not guess language as '%s' does not have an \... | 5,335,383 |
def extract_data_size(series, *names):
"""
Determines series data size from the first available property, which
provides direct values as list, tuple or NumPy array.
Args:
series: perrot.Series
Series from which to extract data size.
names: (str,)
Se... | 5,335,384 |
def uintToQuint (v, length=2):
""" Turn any integer into a proquint with fixed length """
assert 0 <= v < 2**(length*16)
return '-'.join (reversed ([u16ToQuint ((v>>(x*16))&0xffff) for x in range (length)])) | 5,335,385 |
def alphanumeric_hash(s: str, size=5):
"""Short alphanumeric string derived from hash of given string"""
import hashlib
import base64
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | 5,335,386 |
def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs):
"""A reply handler for commands that haven't been added to the reply list.
Returns empty strings for stdout and stderr.
"""
return '', '' | 5,335,387 |
def process_pulled_tweets(tw_api, mongo_client):
"""Loop through pulled_list collection, if a tweet is valid, post it
and save it in posted_list, else move it to discard_list.
- Checks to pass to move to posted_list:
- tweet is not a retweeted one.
- tweet id is not found in posted_list.
... | 5,335,388 |
def require(section: str = "install") -> List[str]:
""" Requirements txt parser. """
require_txt = Path(".").parent / "requirements.txt"
if not Path(require_txt).is_file():
return []
requires = defaultdict(list) # type: Dict[str, List[str]]
with open(str(require_txt), "rb") as fh:
... | 5,335,389 |
def find_pkgutil_ns_hints(tree):
"""
Analyze an AST for hints that we're dealing with a Python module that defines a pkgutil-style namespace package.
:param tree:
The result of :func:`ast.parse()` when run on a Python module (which is
assumed to be an ``__init__.py`` file).
:returns:
... | 5,335,390 |
def announce_voter_cast_ballot(voter_number: int, registrar_url: str, key: str):
"""
Announce to the registrar that voter has cast their ballot and voted
Args:
voter_number: integer voter number from registrar
registrar_url: url to contact registrar
key: valid Fernet key, shared wit... | 5,335,391 |
def string_in_list_of_dicts(key, search_value, list_of_dicts):
"""
Returns True if search_value is list of dictionaries at specified key.
Case insensitive and without leading or trailing whitespaces.
:return: True if found, else False
"""
for item in list_of_dicts:
if equals(item[key], s... | 5,335,392 |
def get_data(station_id, elements=None, update=True, as_dataframe=False):
"""Retrieves data for a given station.
Parameters
----------
station_id : str
Station ID to retrieve data for.
elements : ``None``, str, or list of str
If specified, limits the query to given element code(s).... | 5,335,393 |
def display_stats(pelican_obj):
"""
Called when Pelican is (nearly) done to display the number of files processed.
"""
global gpx_count
plural = "" if gpx_count == 1 else "s"
print("%s Processed %s GPX file%s." % (LOG_PREFIX, gpx_count, plural)) | 5,335,394 |
def add_block(
matrix, block, block_i, block_j, factor, banded
): # pylint: disable=too-many-arguments
"""Add (in place) the block `block` in matrix `matrix`, at block position (i, j) (zero-based).
The block is first multiplied by `factor` (e.g., a sign).
If `banded` is True, fill in a banded matrix (... | 5,335,395 |
def Find_Peaks(profile, scale, **kwargs):
"""
Pulls out the peaks from a radial profile
Inputs:
profile : dictionary, contains intensity profile and pixel scale of
diffraction pattern
calibration : dictionary, contains camera parameters to scale data
... | 5,335,396 |
def empty_items(item_list, total):
"""
Returns a list of null objects. Useful when you want to always show n
results and you have a list of < n.
"""
list_length = len(item_list)
expected_total = int(total)
if list_length != expected_total:
return range(0, expected_total-list_length)
... | 5,335,397 |
def _read_string(fp):
"""Read the next sigproc-format string in the file.
Parameters
----------
fp : file
file object to read from.
Returns
-------
str
read value from the file
"""
strlen = struct.unpack("I", fp.read(struct.calcsize("I")))[0]
return fp.read(strl... | 5,335,398 |
def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent, detailFromGoogle={}):
"""
check for optional return parameters and add them to the result json
:param detail_json:
:param detail:
:param rating:
:param rating_n:
:param popul... | 5,335,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.