content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def safe_download(f):
"""
Makes a download safe, by trapping any app errors and redirecting
to a default landing page.
Assumes that the first 2 arguments to the function after request are
domain and app_id, or there are keyword arguments with those names
"""
@wraps(f)
def _safe_download(... | 1d48c48ac067fcc180af37b90949123c5dc864d9 | 11,500 |
def Moebius(quaternion_or_infinity, a,b=None,c=None,d=None):
"""
The Moebius transformation of a quaternion (z)
with parameters a,b,c and d
>>> import qmath
>>> a = qmath.quaternion([1,1,1,0])
>>> b = qmath.quaternion([-2,1,0,1])
>>> c = qmath.quaternion([1,0,0,0])
>>> d = qmath.quaterni... | 9bfd05268caa6aad1247886717932ca332212e4b | 11,501 |
def _passthrough_zotero_data(zotero_data):
"""
Address known issues with Zotero metadata.
Assumes zotero data should contain a single bibliographic record.
"""
if not isinstance(zotero_data, list):
raise ValueError('_passthrough_zotero_data: zotero_data should be a list')
if len(zotero_d... | cec2271a7a966b77e2d380686ecccc0307f78116 | 11,502 |
import json
def telebot():
"""endpoint responsible to parse and respond bot webhook"""
payload = json.loads(request.data)
message = payload.get('message', payload.get('edited_message',''))
msg_from = message.get('from')
user_id = msg_from.get('id')
user_first_name = msg_from.get('first_name','... | 3a42fee4a89e1be3fa1ec17da21738bfcefba4ba | 11,503 |
import os
def pkg_config(cfg):
"""Returns PkgConfig pkg config object."""
pkg_config_py = os.path.join(get_vta_hw_path(), "config/pkg_config.py")
libpkg = {"__file__": pkg_config_py}
exec(compile(open(pkg_config_py, "rb").read(), pkg_config_py, "exec"), libpkg, libpkg)
PkgConfig = libpkg["PkgConfi... | fd8e36f0694c46f9afef5108dbff4fdc38a3b543 | 11,504 |
def root(tmpdir):
"""Return a pytest temporary directory"""
return tmpdir | 9fa01d67461f8ce1e3d3ad900cf8a893c5a075aa | 11,505 |
from app.crud.core import ready
import logging
def _check_storage(log_fn: tp.Callable) -> bool:
"""See if the storage system is alive."""
try:
log_fn('Attempting to contact storage system', depth=1)
result = ready()
return result
except Exception as ex:
log_fn(ex, level=lo... | b20ca64094126a40fd8eb0ce76e3329c8b4da6cb | 11,506 |
def ignore_ip_addresses_rule_generator(ignore_ip_addresses):
"""
generate tshark rule to ignore ip addresses
Args:
ignore_ip_addresses: list of ip addresses
Returns:
rule string
"""
rules = []
for ip_address in ignore_ip_addresses:
rules.append("-Y ip.dst != {0}".fo... | 3ac43f28a4c8610d4350d0698d93675572d6ba44 | 11,507 |
def readmission(aFileName):
"""
Load a mission from a file into a list. The mission definition is in the Waypoint file
format (http://qgroundcontrol.org/mavlink/waypoint_protocol#waypoint_file_format).
This function is used by upload_mission().
"""
print "\nReading mission from file: %s" % aFil... | 08e92ef784340dcd9bbd3ca8bb85a9c8a9211841 | 11,508 |
def remove_stop_words(words):
"""Remove all stop words.
Args:
words (list): The list of words
Returns:
list: An updated word list with stopwords removed.
"""
# http://stackoverflow.com/questions/5486337/
# how-to-remove-stop-words-using-nltk-or-python
return [w for w in wor... | 29910d1c04cb27ac281428a5401501e4c0e633ae | 11,509 |
def synthetic_costs_1():
""" Uncertainty in 5 points at [0,0] on X1 can cause it to flip
to [1,0] if needed to misclassify
Uncertainty in 1 point at [1,1] on X2 can cause it to flip
to [1,0] if needed to misclassify
All other points certain
"""
costs = np.array([[1,4],[1,4],[... | 97753d9e816feba56b609685831df2d183ab408f | 11,510 |
def example_one(request, context=None):
""" Return web page for example one. """
if context is None:
context = {}
session = request.session.get("ApiSession", None)
if session is None:
return no_session_set(request)
session = Session.deserialize(session)
origin_codes = get_codes... | 25bc3fea514e4011c3be513868fd58d0c2b80d2f | 11,511 |
from typing import Any
def decode(cls: Any, value: bytes) -> Any:
"""Decode value in katcp message to a type.
If a union type is provided, the value must decode successfully (i.e.,
without raising :exc:`ValueError`) for exactly one of the types in the
union, otherwise a :exc:`ValueError` is raised.
... | 3036b69089e68d2a47c3ca110024bde6a026ba5d | 11,512 |
from typing import TextIO
def load_f0(fhandle: TextIO) -> annotations.F0Data:
"""Load an ikala f0 annotation
Args:
fhandle (str or file-like): File-like object or path to f0 annotation file
Raises:
IOError: If f0_path does not exist
Returns:
F0Data: the f0 annotation data
... | 7c0f47e63db1a6fee4718420d74799fa73740b52 | 11,513 |
def remove_fallen(lst):
"""removes fallen orcs from a list"""
return [x for x in lst if x.standing] | 9e621321909dc7aa13da3d2a7902bb4604ae62f6 | 11,514 |
def gc_resnet152(num_classes):
"""Constructs a ResNet-152 model.
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
"""
model = ResNet(GCBottleneck, [3, 8, 36, 3], num_classes=num_classes)
model.avgpool = nn.AdaptiveAvgPool2d(1)
return model | a1986afd48284471045b08322e008796ee7743bb | 11,515 |
def consume_entropy(generated_password: str, quotient: int, max_length: int) -> str:
"""
Takes the entropy (quotient) and the length of password (max_length) required
and uses the remainder of their division as the index to pick a character from
the characters list.
This process occurs recursively ... | 8ba58b34704e9db389241a255e9ec1963e508c99 | 11,516 |
def randomNormal(n, height, baseshape=[]):
"""
Generate random positions, normally distributed along z. Base shape can be:
[] (1D sim)
[Ly] (2D sim)
[Lx, Ly] (3D sim)
Where Lx, Ly are lengths along x, y.
"""
nDim = len(baseshape) + 1
pos = np.zeros([n,... | 96d703ecc059fe180b71f547dfee7f259d803a87 | 11,517 |
from typing import OrderedDict
def index(model_name=None):
"""
Index page.
"""
registered_models = mdb.registered_models
if model_name:
model = next((m for m in registered_models if m.__name__.lower() == model_name.lower()), None)
elif registered_models:
model = registered_mode... | b7cff0c56b0ccc2f5e911ce046210e1b7c8ae05c | 11,518 |
import os
from unittest.mock import call
def download(names, tempdir=None, extra_args=None):
"""Gather pip packages in `tempdir`
Arguments:
names (list): Names of packages to install, in pip-format,
e.g. ["six==1"]
tempdir (str, optional): Absolute path to where pip packages go un... | 2ac41052218b1de9308dc7a553a1637acf6e9938 | 11,519 |
def _parseCellContentsSection(fileAsList, lineIdx):
""" returns fractCoords from Cell Contents section of castep
Args:
fileAsList(str list): Each entry is 1 line of the castep input file
lineIdx(int): The index containing the line "cell contents"
Returns
fractCoords: nx4 iter with each contain... | 3baa1a200442ef8681a0741bfa2a60d9ca1e20b2 | 11,520 |
def get_avg_no_of_feat_values(contents):
"""
Helper to calculate numbers of different values
of categorical features, averaged for all features
"""
total = 0
for i in range(0, len(contents[0])):
total += len(set([x[i] for x in contents]))
return float(total) / float(len(contents[0])... | 4e913298d7f133eb08afe23e4999f5b20f455dc1 | 11,521 |
def plot_trend_line(axes_, xd, yd, c='r', alpha=1, cus_loc = None, text_color='black', return_params=False,
extra_text='', t_line_1_1=True, fit_function=None, fontsize_=12, add_text=True):
"""Make a line of best fit"""
#create clean series
x_, y_ = coincidence(xd,yd)
if fit_functi... | a4d6e41bf03524f257531bbb0f2bb43d1b3b6b8b | 11,522 |
from pathlib import Path
import yaml
def get_oil_type_atb(
oil_attrs, origin, destination, transport_data_dir, random_generator
):
"""Randomly choose type of cargo oil spilled from an ATB (articulated tug and barge) based on
AIS track origin & destination, and oil cargo attribution analysis.
Unlike t... | e7e6e51ece2bb5b4fffc70d2507c2e5ff062bbd8 | 11,523 |
def get_jwt():
"""
Get Authorization token and validate its signature
against the application's secret key, .
"""
expected_errors = {
KeyError: WRONG_PAYLOAD_STRUCTURE,
AssertionError: JWK_HOST_MISSING,
InvalidSignatureError: WRONG_KEY,
DecodeError: WRONG_JWT_STRUCTU... | 9c52369b38db9815769ea8277c3e3721ba20c1c9 | 11,524 |
def start_volume(name, force=False):
"""
Start a gluster volume
name
Volume name
force
Force the volume start even if the volume is started
.. versionadded:: 2015.8.4
CLI Example:
.. code-block:: bash
salt '*' glusterfs.start mycluster
"""
cmd = "volu... | 6dc936b4e09beb9713c32e4c93e8649999f82c3c | 11,525 |
def hist_equal(img, z_max=255):
"""
直方图均衡化,将暗的地方变量,亮的地方变暗
:param img:
:param z_max: 原图像最亮的地方减去最暗的地方的值
:return:
"""
if len(img.shape) == 2:
height, width = img.shape
n_chan = 1
elif len(img.shape) == 3:
height, width, n_chan = img.shape
print(img[:, :, 0].s... | e6aaf76ce8088b9519cd896d8236a84f01761976 | 11,526 |
def combine(*indices_lists):
"""
Return all the combinations from lists of indices
:param indices_lists: each argument is a list of indices (it must be a list)
:return: The combined list of indices
"""
if len([*indices_lists]) > 1:
return [i for i in product(*indices_lists)]
else:
... | 839762c9645e0c8d6ea31a21113a5efd6b97f1de | 11,527 |
import re
def get_endpoint(query):
"""
Regex to parse domain and API endpoint from a SoQL query via FROM
statement
:param query: str, SoQL-formatted query
:return
url, endpoint, query: str objects, domain, endpoint, and
original query sans F... | 4496c85f2e6f908bd5dcef7195b821998ef79c42 | 11,528 |
def load_data(filename: str) ->pd.DataFrame:
"""
Load house prices dataset and preprocess data.
Parameters
----------
filename: str
Path to house prices dataset
Returns
-------
Design matrix and response vector (prices) - either as a single
DataFrame or a Tuple[DataFrame, Se... | 26c785cb72b883cab03b9da6c7718b71e7ccea76 | 11,529 |
def version_match(required, candidate):
"""Test that an available version is a suitable match for a required
version.
To be suitable a version must be of the same major version as required
and be at least a match in minor/patch level.
eg. 3.3 is a match for a required 3.1 but 4.1 is not.
:par... | bc537fdae084a3c3ccb7b8336703ef4c2476de6e | 11,530 |
from typing import Optional
from datetime import datetime
def get_last_upgraded_at(module: base.Module) -> Optional[datetime.datetime]:
"""
Get the timestamp of the last time this module was upgraded.
"""
return settings.get_last_upgraded_at(module.name) | bf884bf4c249448929b987504d400d6ba1b12927 | 11,531 |
import collections
import re
import logging
def parse_header_file(header_file):
"""Parse a single header file to get all defined constants out of it."""
resolved_values = collections.OrderedDict()
raw_matches = {}
with open(header_file, "r") as fd:
all_file_lines = collections.OrderedDict(
... | 1681939a78efe6426cdea1577a8781a7f046c02d | 11,532 |
import platform
def get_linux_distribution(get_full_name, supported_dists):
"""Abstract platform.linux_distribution() call which is deprecated as of
Python 3.5 and removed in Python 3.7"""
try:
supported = platform._supported_dists + (supported_dists,)
osinfo = list(
platfor... | 01ceea04eeb4e8130e9ce5899a116af557d9f954 | 11,533 |
def check_disabled(func):
"""
Decorator to wrap up checking if the Backdrop
connection is set to disabled or not
"""
@wraps(func)
def _check(*args, **kwargs):
if _DISABLED:
return
else:
return func(*args, **kwargs)
return _check | 53d6b0b44558d09ed73556f6854f004c6767856c | 11,534 |
def bbox_from_points(points):
"""Construct a numeric list representing a bounding box from polygon coordinates in page representation."""
xys = [[int(p) for p in pair.split(',')] for pair in points.split(' ')]
return bbox_from_polygon(xys) | 75742907d85990ee3bbfa133d9ba51f70b3f76ee | 11,535 |
def return_true():
"""Return True
Simple function used to check liveness of workers.
"""
return True | 3c4b469ce28aef47723a911071f01bea9eb4cf27 | 11,536 |
import os
def create_list(input_list):
"""Construct the list of items to turn into a table. File and string inputs supported"""
if os.path.isfile(input_list):
with open(input_list, 'r', encoding='UTF-8') as ifile:
return [line.rstrip() for line in ifile]
return input_list.split(',') | 7158fa8241ae6328f931f4e7a9dfe08f3d12c6a2 | 11,537 |
def get_active_test_suite():
"""
Returns the test suite that was last ran
>>> get_active_test_suite()
"Hello"
"""
return TEST_RUNNER_STATE.test_suite | dc578da283429480a872175ff1cd5462bf803925 | 11,538 |
def header_from_stream(stream, _magic=None) -> (dict, list, int):
"""
Parse SAM formatted header from stream.
Dict of header values returned is structured as such: {Header tag:[ {Attribute tag: value}, ]}.
Header tags can occur more than once and so each list item represents a different tag line.
:p... | e0e071f38787950fa499344c63cc4040e5fccb23 | 11,539 |
def walk_binary_file_or_stdin(filepath, buffer_size = 32768):
"""
Yield 'buffer_size' bytes from filepath until EOF, or from
standard input when 'filepath' is '-'.
"""
if filepath == '-':
return walk_binary_stdin(buffer_size)
else:
return walk_binary_file(filepath, buffer_size) | 290ea9e159c8f0e3df6713b8abcd0c141cb4858a | 11,540 |
def register_device() -> device_pb2.DeviceResponse:
"""
Now that the client credentials are set, the device can be registered. The device is
registered by instantiating an OauthService object and using the register() method.
The OauthService requires a Config object and an ISecureCredentialStore object... | 5a3958456f55315fa91be4e60324be3e5d9d3af8 | 11,541 |
def _sto_to_graph(agent: af.SubTaskOption) -> subgraph.Node:
"""Convert a `SubTaskOption` to a `Graph`."""
node_label = '{},{},{}'.format(agent.name or 'SubTask Option',
agent.subtask.name or 'SubTask',
agent.agent.name or 'Policy')
return subgraph... | 311f591be99bc045d2572b22f9cd3462bce2b10c | 11,542 |
def filter_input(self, forced=False, context=None):
"""
Passes each hunk (file or code) to the 'input' methods
of the compressor filters.
"""
content = []
for hunk in self.hunks(forced, context=context):
content.append(hunk)
return content | 1ea0ac16cf1e20732ad8c37b6126c80fe94d2ee5 | 11,543 |
def delete(request, user):
""" Deletes a poll """
poll_id = request.POST.get('poll_id')
try:
poll = Poll.objects.get(pk=poll_id)
except:
return JsonResponse({'error': 'Invalid poll_id'}, status=404)
if poll.user.id != user.id:
return JsonResponse({'error': 'You cannot delet... | 36a46e1b72cd06178ac00706c24451736fd454cd | 11,544 |
from typing import Optional
def get_nodes(collection: str, node_link: Optional[str] = None):
"""Get the Node based on its ID or kind"""
# pylint: disable=too-many-locals,too-many-return-statements,too-many-branches
user_id = to_object_id(g.user._id)
can_view_others_operations = g.user.check_role(IAMP... | 55a8b56988496d355a16e8aa0c1a8a79280af987 | 11,545 |
def get_loader(path):
"""Gets the configuration loader for path according to file extension.
Parameters:
path: the path of a configuration file, including the filename
extension.
Returns the loader associated with path's extension within LOADERS.
Throws an UnknownConfigurationExce... | a122c67d6ebacf2943ec69765d5feab649f5c341 | 11,546 |
def mat_stretch(mat, target):
"""
Changes times of `mat` in-place so that it has the same average BPM and
initial time as target.
Returns `mat` changed in-place.
"""
in_times = mat[:, 1:3]
out_times = target[:, 1:3]
# normalize in [0, 1]
in_times -= in_times.min()
in_times /= ... | 204efb1d8a19c7efe0efb5710add62436a4b5cee | 11,547 |
def parse_range(cpu_range):
"""Create cpu range object"""
if '-' in cpu_range:
[x, y] = cpu_range.split('-') # pylint: disable=invalid-name
cpus = range(int(x), int(y)+1)
if int(x) >= int(y):
raise ValueError("incorrect cpu range: " + cpu_range)
else:
cpus = [int... | 51079648ffddbcba6a9699db2fc4c04c7c3e3202 | 11,548 |
def causal_parents(node, graph):
"""
Returns the nodes (string names) that are causal parents of the node (have the edge type "causes_or_promotes"), else returns empty list.
Parameters
node - name of the node (string)
graph - networkx graph object
"""
node_causal_parents = []
if list(gra... | 4618e9649d3ea37c9a3a0d8faf7a44b00e386f1c | 11,549 |
def create_app(settings_override=None):
"""
Create a test application.
:param settings_override: Override settings
:type settings_override: dict
:return: Flask app
"""
app = Flask(__name__)
params = {
'DEBUG': True,
'WEBPACK_MANIFEST_PATH': './build/manifest.json'
}
... | 38393418415d29e3068398dca9bdce8b8b88eec6 | 11,550 |
async def user_me(current_user=Depends(get_current_active_user)):
"""
Get own user
"""
return current_user | 40c5bb5a45cad8154489db3fc0da3c0fe54d783d | 11,551 |
from typing import Optional
from typing import Tuple
import crypt
def get_password_hash(password: str, salt: Optional[str] = None) -> Tuple[str, str]:
"""Get user password hash."""
salt = salt or crypt.mksalt(crypt.METHOD_SHA256)
return salt, crypt.crypt(password, salt) | ea3d7e0d8c65e23e40660b8921aa872dc9e2f53c | 11,552 |
def start_at(gra, key):
""" start a v-matrix at a specific atom
Returns the started vmatrix, along with keys to atoms whose neighbors are
missing from it
"""
symb_dct = atom_symbols(gra)
ngb_keys_dct = atoms_sorted_neighbor_atom_keys(
gra, symbs_first=('X', 'C',), symbs_last=('H',), ord... | baa4d463316d47611a696bea456f8e1d0e4b5755 | 11,553 |
def associate_kitti(detections,
trackers,
det_cates,
iou_threshold,
velocities,
previous_obs,
vdc_weight):
"""
@param detections:
"""
if (len(trackers) == 0):
return np.empty((... | 8f3fb7628940cacd68de4f93b8469e212a12d854 | 11,554 |
import json
import uuid
import time
def seat_guest(self, speech, guest, timeout):
"""
Start the view 'seatGuest'
:param speech: the text that will be use by the Local Manager for tablet and vocal
:type speech: dict
:param guest: name of the guest to seat
:type guest: string
:param timeout... | 42a8ccd03638dfb48072c1d1b10c0c05a8f867ec | 11,555 |
def retreive_retries_and_sqs_handler(task_id):
"""This function retrieve the number of retries and the SQS handler associated to an expired task
Args:
task_id(str): the id of the expired task
Returns:
rtype: dict
Raises:
ClientError: if DynamoDB query failed
"""
try:
... | c432d9f73f8d1de8fbcf48b35e41a2879ca25954 | 11,556 |
import torch
def decompose(original_weights: torch.Tensor, mask, threshould: float) -> torch.Tensor:
"""
Calculate the scaling matrix. Use before pruning the current layer.
[Inputs]
original_weights: (N[i], N[i+1])
important_weights: (N[i], P[i+1])
[Outputs]
scaling_matrix: (P[i+1], N[... | 844562c839b95eb172197f22781f2316639b2d95 | 11,557 |
def calc_Kullback_Leibler_distance(dfi, dfj):
"""
Calculates the Kullback-Leibler distance of the two matrices.
As defined in Aerts et al. (2003). Also called Mutual Information.
Sort will be ascending.
Epsilon is used here to avoid conditional code for checking that neither P nor Q is equal to 0.
... | fd66434557598717db7cc73ca9a88fde9ab7e73d | 11,558 |
def test_python_java_classes():
""" Run Python tests against JPY test classes """
sub_env = {'PYTHONPATH': _build_dir()}
log.info('Executing Python unit tests (against JPY test classes)...')
return jpyutil._execute_python_scripts(python_java_jpy_tests, env=sub_env) | 11a9e43126799738a7c8e5cf8614cbe63d15cd2f | 11,559 |
def trim_datasets_using_par(data, par_indexes):
"""
Removes all the data points needing more fitting parameters than available.
"""
parameters_to_fit = set(par_indexes.keys())
trimmed_data = list()
for data_point in data:
if data_point.get_fitting_parameter_names() <= parameters_to_fi... | 5a06f7f5662fb9d7b5190e0e75ba41c858a85d0b | 11,560 |
def _parse_field(field: str) -> Field:
"""
Parse the given string representation of a CSV import field.
:param field: string or string-like field input
:return: a new Field
"""
name, _type = str(field).split(':')
if '(' in _type and _type.endswith(')'):
_type, id_space = _type.split... | 413cc12675e57db57da75dd9044c1884e638282c | 11,561 |
import time
import scipy
def removeNoise(
audio_clip,
noise_thresh,
mean_freq_noise,
std_freq_noise,
noise_stft_db,
n_grad_freq=2,
n_grad_time=4,
n_fft=2048,
win_length=2048,
hop_length=512,
n_std_thresh=1.5,
prop_decrease=1.0,
verbose=False,
visual=False,
):
... | 3d92ae7427ab33cc875219b3f005ca86802dd4c2 | 11,562 |
import logging
def validate_wra_params(func):
"""Water Risk atlas parameters validation"""
@wraps(func)
def wrapper(*args, **kwargs):
validation_schema = {
'wscheme': {
'required': True
},
'geostore': {
'type': 'string',
... | 8c15b74e4a5fc9cffc54cb6fa53325fb2405ca7d | 11,563 |
from simulator import simulate
import logging
import json
def handle_request(r):
"""Handle the Simulator request given by the r dictionary
"""
print ("handle_request executed .. ")
print (r)
# Parse request ..
config = SimArgs()
config.machine = r[u'machine']
config.overlay = [r[u'top... | 73a55ec93bfdf398b896b3c208a476296c1c04f5 | 11,564 |
def number_empty_block(n):
"""Number of empty block"""
L = L4 if n == 4 else L8
i = 0
for x in range(n):
for y in range(n):
if L[x][y] == 0:
i = i + 1
return i | 1dc7f228cdcbf4c3a1b6b553bff75ba1bb95bdbe | 11,565 |
def compute_referendum_result_by_regions(referendum_and_areas):
"""Return a table with the absolute count for each region.
The return DataFrame should be indexed by `code_reg` and have columns:
['name_reg', 'Registered', 'Abstentions', 'Null', 'Choice A', 'Choice B']
"""
ans = referendum_and_areas.... | fb02c28b5caca9147a27bd2f205c07d377d8561c | 11,566 |
def fixed_rho_total_legacy(data, rho_p, rho_s, beads_2_M):
"""
*LEGACY*: only returns polycation/cation concentrations. Use updated version
(`fixed_rho_total()`), which returns a dictionary of all concentrations.
Computes the polycation concentration in the
supernatant (I) and coacervate (II) phase... | a13419c5dc95702e93dca48822e2731bd05745b5 | 11,567 |
import os
def is_valid_file(parser, filename):
"""Check if file exists, and return the filename"""
if not os.path.exists(filename):
parser.error("The file %s does not exist!" % filename)
else:
return filename | 4e9e2a49749c65fd5457578fd162baf350b94fe3 | 11,568 |
def portfolio():
"""Function to render the portfolio page."""
form = PortfolioCreateForm()
if form.validate_on_submit():
try:
portfolio = Portfolio(name=form.data['name'], user_id=session['user_id'])
db.session.add(portfolio)
db.session.commit()
except (D... | adc84381bf6397023fc943f9c2edb1e34879400d | 11,569 |
def svn_client_get_simple_provider(*args):
"""svn_client_get_simple_provider(svn_auth_provider_object_t provider, apr_pool_t pool)"""
return apply(_client.svn_client_get_simple_provider, args) | dcdaaa1b448443e7b3cdb8984dc31d8a009c5606 | 11,570 |
def svn_client_invoke_get_commit_log(*args):
"""
svn_client_invoke_get_commit_log(svn_client_get_commit_log_t _obj, char log_msg, char tmp_file,
apr_array_header_t commit_items,
void baton, apr_pool_t pool) -> svn_error_t
"""
return apply(_client.svn_client_invoke_get_commit_log, args) | 5c4e8f30309037eabb74c99e77f1b0f4f3172428 | 11,571 |
import random
def find_valid_nodes(node_ids, tree_1, tree_2):
"""
Recursive function for finding a subtree in the second tree
with the same output type of a random subtree in the first tree
Args:
node_ids: List of node ids to search
tree_1: Node containing full tree
tree_2: N... | 88cfd535487ba460e3c212c9c85269abd68f6ef2 | 11,572 |
import torch
def pytorch_local_average(n, local_lookup, local_tensors):
"""Average the neighborhood tensors.
Parameters
----------
n : {int}
Size of tensor
local_lookup : {dict: int->float}
A dictionary from rank of neighborhood to the weight between two processes
local_tensor... | 294a4d63ce5eff42ccd3abe1354640f6f934e96f | 11,573 |
def get_rr_Ux(N, Fmat, psd, x):
"""
Given a rank-reduced decomposition of the Cholesky factor L, calculate L^{T}x
where x is some vector. This way, we don't have to built L, which saves
memory and computational time.
@param N: Vector with the elements of the diagonal matrix N
@param Fmat:... | 9a0aaa95d904b9bc993d295a49d95a48d0f6245f | 11,574 |
def get_poll_options(message: str) -> list:
"""
Turns string into a list of poll options
:param message:
:return:
"""
parts = message.split(CREATE_POLL_EVENT_PATTERN)
if len(parts) > 1:
votes = parts[-1].split(",")
if len(votes) == 1 and votes[0] == ' ':
return []... | fd1209403038d5b1ca75d7abd8567bb47fd6bd9a | 11,575 |
def get_avg_percent_bonds(bond_list, num_opts, adj_lists, num_trials, break_co_bonds=False):
"""
Given adj_list for a set of options, with repeats for each option, find the avg and std dev of percent of each
bond type
:param bond_list: list of strings representing each bond type
:param num_opts: num... | 74c34afea07ab98941c70b571197fe0ea43bcb88 | 11,576 |
from io import StringIO
def current_fig_image():
"""Takes current figure of matplotlib and returns it as a PIL image.
Also clears the current plot"""
plt.axis('off')
fig = plt.gcf()
buff = StringIO.StringIO()
fig.savefig(buff)
buff.seek(0)
img = Image.open(buff).convert('RGB')
plt... | 6da91a7157db0cd0df8ebc1e4f3d6007f35f2621 | 11,577 |
def get_bgp_peer(
api_client, endpoint_id, bgp_peer_id, verbose=False, **kwargs
): # noqa: E501
"""Get eBGP peer # noqa: E501
Get eBGP peer details # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> resp... | 3a9fa41b2918c1537402d8894fe3315ff90241e8 | 11,578 |
def rewrite_elife_funding_awards(json_content, doi):
""" rewrite elife funding awards """
# remove a funding award
if doi == "10.7554/eLife.00801":
for i, award in enumerate(json_content):
if "id" in award and award["id"] == "par-2":
del json_content[i]
# add fundin... | aba819589e50bc847d56a0f5a122b2474425d39c | 11,579 |
def remove_subnet_from_router(router_id, subnet_id):
"""Remove a subnet from the router.
Args:
router_id (str): The router ID.
subnet_id (str): The subnet ID.
"""
return neutron().remove_interface_router(router_id, {
'subnet_id': subnet_id
}) | 4b7e9123f148fddaa3d53bcabe1f37b35c974162 | 11,580 |
def direct_to_template(request, template):
"""Generic template direction view."""
return render_to_response(template, {}, request) | 5a030f302450829d397fbc27f73bd24470bfe50b | 11,581 |
from datetime import datetime
def now():
"""Return the current time as date object."""
return datetime.now() | 79ddcf3c2e22ff57626520e0b41af8b0f58972d6 | 11,582 |
def is_valid_node_name(name):
"""
Determine if a name is valid for a node.
A node name:
- Cannot be empty
- Cannot start with a number
- Cannot match any blacklisted pattern
:param str name: The name to check.
:return: True if the name is valid. False otherwise.
:rtype: bool
""... | 6a935f7172e96fd418084543da0fe81d6bb77be5 | 11,583 |
def trajCalc(setup):
""" Creates trajectory between point A and the ground (B) based off of the initial position and the angle of travel
Arguments:
setup: [Object] ini file parameters
Returns:
A [list] lat/lon/elev of the tail of the trajectory
B [list] lat/lon/elev of the head of the traject... | 30614d0193aacdd594400fbbda396bca40a75156 | 11,584 |
from typing import Dict
async def health() -> Dict[str, str]:
"""Health check function
:return: Health check dict
:rtype: Dict[str: str]
"""
health_response = schemas.Health(name=settings.PROJECT_NAME,
api_version=__version__)
return health_response.dict() | ffda9fa5795c02bd197ed8715d44b384781c866f | 11,585 |
def projection_v3(v, w):
"""Return the signed length of the projection of vector v on vector w.
For the full vector result, use projection_as_vec_v3().
Since the resulting vector is along the 1st vector, you can get the
full vector result by scaling the 1st vector to the length of the result of
thi... | 3aeb8783a5eb680f0e2085d6a0f3b8b80511b10f | 11,586 |
def custom_djsettings(settings):
"""Custom django settings to avoid warnings in stdout"""
settings.TEMPLATE_DEBUG = False
settings.DEBUG = False
return settings | fc57786b22255235af6df7cec665696aeb1e882b | 11,587 |
import math
import collections
def bleu(pred_seq, label_seq, k):
"""计算BLEU"""
pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')
len_pred, len_label = len(pred_tokens), len(label_tokens)
score = math.exp(min(0, 1 - len_label / len_pred))
for n in range(1, k + 1):
num_m... | ae7485687a44afc9ced6f2f4ed5ac8fe0d67b295 | 11,588 |
def report_by_name(http_request, agent_name):
"""
A version of report that can look up an agent by its name. This will
generally be slower but it also doesn't expose how the data is stored and
might be easier in some cases.
"""
agent = get_list_or_404(Agent, name=agent_name)[0]
return report... | ee9daf5b7e7e5f15af3e507f55e0a5e2a1388aca | 11,589 |
def create_application(global_config=None, **local_conf):
"""
Create a configured instance of the WSGI application.
"""
sites, types = load_config(local_conf.get("config"))
return ImageProxy(sites, types) | c8d3c7158902df00d88512a23bb852bb226b5ba4 | 11,590 |
def dimensionState(moons,dimension):
"""returns the state for the given dimension"""
result = list()
for moon in moons:
result.append((moon.position[dimension],moon.velocity[dimension]))
return result | e67a37e4a1556d637be74992fc3801ee56f0e6f9 | 11,591 |
def login():
"""Log in current user."""
user = get_user()
if user.system_wide_role != 'No Access':
flask_login.login_user(user)
return flask.redirect(common.get_next_url(
flask.request, default_url=flask.url_for('dashboard')))
flask.flash(u'You do not have access. Please contact your administra... | f229ebbd0f77789784b2e8d05bb643d9b5cb1da1 | 11,592 |
def init_module():
"""
Initialize user's module handler.
:return: wrapper handler.
"""
original_module, module_path, handler_name = import_original_module()
try:
handler = original_module
for name in module_path.split('.')[1:] + [handler_name]:
handler = getattr(handl... | 148ed89ea8a9f67c9cef5bc209a803840ff9de56 | 11,593 |
from typing import List
def process(lines: List[str]) -> str:
""" Preprocess a Fortran source file.
Args:
inputLines The input Fortran file.
Returns:
Preprocessed lines of Fortran.
"""
# remove lines that are entirely comments and partial-line comments
lines = [
rm_t... | f3fd3bc75be544cd507dae87b80364c9b1c12f7c | 11,594 |
def _summary(function):
"""
Derive summary information from a function's docstring or name. The summary is the first
sentence of the docstring, ending in a period, or if no dostring is present, the
function's name capitalized.
"""
if not function.__doc__:
return f"{function.__name__.capi... | a3e3e45c3004e135c2810a5ec009aa78ef7e7a04 | 11,595 |
def findrun(base,dim,boxsize):
""" find all files associated with run given base directory
and the resolution size and box length """
if not os.path.isdir(base):
print base, 'is not a valid directory'
sys.exit(1)
#retreive all files that match tag and box size
#note this will inclu... | c14f885943a33df96cda28a4a84fdce332149167 | 11,596 |
def demand_mass_balance_c(host_odemand, class_odemand, avail, host_recapture):
"""Solve Demand Mass Balance equation for class-level
Parameters
----------
host_odemand: int
Observerd host demand
class_odemand: int
Observed class demand
avail: dict
Availability of demand ... | 7fda78ce632f1a26ec875c37abe5db40615aa351 | 11,597 |
from typing import Optional
def serve_buffer(
data: bytes,
offered_filename: str = None,
content_type: str = None,
as_attachment: bool = True,
as_inline: bool = False,
default_content_type: Optional[str] = MimeType.FORCE_DOWNLOAD) \
-> HttpResponse:
"""
... | aa41df168e3f84468293ca6653c06402e6c395fc | 11,598 |
def get_single_image_results(gt_boxes, pred_boxes, iou_thr):
"""Calculates number of true_pos, false_pos, false_neg from single batch of boxes.
Args:
gt_boxes (list of list of floats): list of locations of ground truth
objects as [xmin, ymin, xmax, ymax]
pred_boxes (dict): dict of d... | ec97189c8c75686aa172292179228621e244982f | 11,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.