content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def euler_vec(z, y, x, n):
"""
Return (n,3,3) tensor with each (3,3) block containing an
Euler rotation with angles z, y, x. Optionally each of z, y, x
can be a vector of length n.
"""
L = np.zeros((n, 3, 3), "d")
cosx, sinx = np.cos(x), np.sin(x)
L[:, 0, 0] = 1
L[:, 1, 1] = L[:, 2, ... | 40,600 |
def reloadTexture(path):
"""
Remove a texture from the texture cache. Removing a texture from cache will
result in unloading the texture from the GPU memory, unless another
reference to it is kept.
"""
log.message('Reloading texture %s', path)
if path not in _textureCache:
log.error(... | 40,601 |
def ReadBenderEllipse( filename, dataFrame=False, headerLine=None, useDefaultColumnNames=True ):
"""Read in an ellipse fit generated by Bender/Saglia code and store it
in a dictionary (or, optionally, a ListDataFrame object). Columns are
converted to 1-D numpy arrays.
headerLine indicates which lin... | 40,602 |
def getQuote(symbolStringCSV, detailFlag = 'ALL' ):
"""
Returns the live quote of a single or many companies
symbolStringCSV <str> is a comma separated value of tickers
detailFlag <'ALL' or 'INTRADAY'> specifies whether all data is returned or just a subset with intraday
sample usage:
getQuote('TVIX, GOOG'... | 40,603 |
def get_user_resources_permissions_dict(user, request, resource_types=None, resource_ids=None,
inherit_groups_permissions=True, resolve_groups_permissions=False):
# type: (models.User, Request, Optional[List[Str]], Optional[List[int]], bool, bool) -> ResourcePermissionMap
... | 40,604 |
def set_build_platform():
""" Initialise the build platform. """
global build_platform
# Set the platform specific default specification.
platdefaults = {
"aix": "aix-xlc",
"bsd": "bsdi-g++",
"cygwin": "cygwin-g++",
"darwin": "macx-g++",
... | 40,605 |
def create_new_index(index_name: str):
"""
Алгоритм внутри по шагам
:param index_name: str: название текущей версии индекса
:return: new_index_name: str: название обновленного индекса
"""
print("*" * 10)
# получаем новое имя индекса
new_index_name = up_index_version(index_name)
prin... | 40,606 |
def _parse_slice_str(slice_str):
"""Parses the given string as a multidimensional array slice and returns a
list of slice objects and integer indices."""
is_valid = False
if len(slice_str) > 2:
is_valid = slice_str[0] == "[" and slice_str[-1] == "]"
sliced_inds = []
if is_valid:
slice_str_list = ... | 40,607 |
def test_irreg_topo(dans_grid2):
"""Test D8 routing on a toy irregular topo."""
with pytest.deprecated_call():
fr = FlowRouter(dans_grid2.mg)
fr.run_one_step()
assert_array_equal(dans_grid2.A_target_D8, dans_grid2.mg.at_node["drainage_area"])
assert_array_equal(
dans_grid2.frcvr_targ... | 40,608 |
def plot_many_directions(ax, angles,
color='black', marker='d', markersize=3,
label=None, label_position='right', weight='normal'):
"""Loop around `plot_direction`
Parameters
----------
ax : figure axes object
angles : list of dictionary {'phi':..... | 40,609 |
def test_create_record(client):
""" Test create_record """
with open('tests/mocks/create_record.json', 'r') as file_obj:
mock_record = json.load(file_obj)
assert mock_record
if mock_record:
response = client.simulate_post('/page/create_record', body=json.dumps(mock_record))
ass... | 40,610 |
def AverageZComparison(x, y):
""" Take the average of second and third element in an array and compare
which is bigger. To be used in conjunction with the sort function. """
xsum = x[1]+x[2]
ysum = y[1]+y[2]
if xsum < ysum:
return -1
if xsum > ysum:
return 1
return 0 | 40,611 |
def sparse_copy(src_fname, dst_fname, skip=0, seek=0,
length=0, api=None):
"""
Efficiently copy sparse file to or into another file.
src_fname: path to source file
dst_fname: path to destination file
skip: skip N bytes at thestart of src
seek: seek N bytes from the start of dst
... | 40,612 |
def convblock(in_channels, out_channels, kernel_size, stride=1, padding=0, use_bn=True):
"""
Returns convolution block
"""
if use_bn:
return [
nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding),
nn.BatchNorm2d(out_channels),
nn.ReLU(True)
... | 40,613 |
def init_db():
"""
cria banco de dados e tabelas
"""
db.create_all() | 40,614 |
def get_caffe_op_type(layer, input_channels=1, output_channels=1):
"""
Gets the relevant Toolkit Enum for the corresponding Caffe layer stage type.
:param layer:
The particular layer field of the caffe Net msg that we want to discover the type.
:return: StageType Enum
"""
if isConvolutio... | 40,615 |
def comp_volumes(self):
"""Compute the Lamination volumes (Vlam, Vvent, Vslot, Vwind)
Parameters
----------
self : LamSlotWind
A LamSlotWind object
Returns
-------
V_dict: dict
Lamination volume dictionnary (Vlam, Vvent, Vslot, Vwind) [m**3]
"""
V_dict = LamSlot.c... | 40,616 |
def validate_proper_filter(pathology_name: str, rules):
"""
Validates a given filter in jQuery format.
This function will check the validity of:
1. The type of the filter
2. The column name (if it exists in the metadata of the pathology)
3. The pathology name (if the pathology exists... | 40,617 |
def elliptical_orbit():
"""Draw an example of a planet with an elliptical orbit around its star."""
fig, axes = plt.subplots(1, 1)
orbit = Ellipse(xy=(0, 0), width=2, height=1.5, facecolor='lightblue')
axes.add_artist(orbit)
axes.plot([-1, 0], [0, 0])
axes.annotate(
'semi-major axis',... | 40,618 |
def get_date_range_for_date(date_str, interval):
"""
Given a date string, parse it and derive a range based on the given
interval. The interval is inclusive on the lower end, and exclusve on the
higher end. For example, given a date str of 2019-03-10 and a 'month'
interval, this will return a range ... | 40,619 |
def sigmaStarDFA(sigma=None):
"""
Given a alphabet S returns the minimal DFA for S*
:param sigma: set of symbols
:return: DFA
.. versionadded:: 1.2"""
if sigma is None:
raise
d = DFA()
d.setSigma(sigma)
i = d.addState()
d.setInitial(i)
d.addFinal(i)
for a in d.S... | 40,620 |
def card_pendulum_scale(scale):
"""Validate pendulum scale.
Args:
scale (int): Card pendulum scale.
Raises:
exceptions.PendulumScaleInvalid: Pendulum scale must be a integer
between 0 and 13.
"""
try:
scale = int(scale)
except ValueError:
raise excep... | 40,621 |
def submit_scheduled_messages():
""" Get from database on ongoing courses scheduled messages to submit """
data = frappe.db.sql("""select t1.sch_message, t1.start_when, timestampdiff(second, now(), t1.start_when) as age, now() from `tabDestination Item` t1 where t1.parent in (select t2.name from `tabTraining Cours... | 40,622 |
def forall_reduce(pred, l):
"""TODO : une version de forall utilisant UNIQUEMENT la fonction standard functools.reduce
"""
pass | 40,623 |
def test_initially_unprocessed(data_for_testing):
""" """
wb = DatabaseLandBalancer(database_name="test_db", biosphere="biosphere")
ab = ActivityLandBalancer(('test_db', 'A'), wb)
assert not ab._processed()
ab._identify_strategy()
assert not ab._processed()
ab._define_balancing_parameters()
... | 40,624 |
def feature_engineer(train, test, bureau, bureau_balance, credit_card_balance,
installments_payments, pos_cash_balance, previous_application):
"""
This function read all the data from the competition and do manual feature engineer to it.
:param train:
:param test:
:param bureau:... | 40,625 |
def is_intersection_line_line_xy(l1, l2):
"""Determine if two lines intersect in 2d lying in the XY plane.
Parameters:
l1 (tuple):
l2 (tuple):
Returns:
(bool): True if there is a intersection, False otherwise.
"""
raise NotImplementedError | 40,626 |
def timestamp_to_datetime(seconds, tz=None):
"""Returns a datetime.datetime of `seconds` in UTC
:param seconds: timestamp relative to the epoch
:param tz: timezone of the timestamp
"""
if tz is None:
tz = timezone.utc
dt = datetime.fromtimestamp(seconds, tz)
return dt.astimezone(tim... | 40,627 |
def initialize(plugins, exclude_regex=None, rootdir='.'):
"""Scans the entire codebase for high entropy strings, and returns a
SecretsCollection object.
:type plugins: tuple of detect_secrets.plugins.base.BasePlugin
:param plugins: rules to initialize the SecretsCollection with.
:type exclude_rege... | 40,628 |
def move_file(filename, destination_dir):
"""
Move file to destination directory
filename: The path of file to be moved
destination_dir: Directory to move image into
"""
os.rename(filename, destination_dir + "/" + filename.split("/")[-1]) | 40,629 |
def list_routes():
"""List all routes defined for the application."""
import urllib
for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.endpoint):
methods = ','.join(rule.methods)
print urllib.unquote("{:40s} {:40s} {}".format(rule.endpoint, methods,
... | 40,630 |
def recipe_cm360_segmentology(config, account, auth_read, auth_write, recipe_name, date_range, recipe_slug, advertisers):
"""CM360 funnel analysis using Census data.
Args:
account (string) - NA
auth_read (authentication) - Credentials used for reading data.
auth_write (authentication) - Aut... | 40,631 |
def decompose_job_id(job_id):
"""Thin wrapper around generic decompose_job_id to use our local SPACER."""
return utils_decompose_job_id(job_id, spacer=SPACER) | 40,632 |
def build(P , word_size , first_hidden_size , encoding_size) :
"""
create entity and relation encoding
"""
P["W_word_left_input"] = U.initial_weights(2*word_size , first_hidden_size)
P["W_word_right_input"] = U.initial_weights(2*word_size , first_hidden_size)
P["W_encoding_output"] = U.initial... | 40,633 |
def resample_to_wet_dry_medians(ds, wet_month=None, dry_month=None, inplace=True):
"""
Takes a xarray dataset/array and a list of wet, dry months which
to resample to. An annualised wet and dry season median image for
given wet, dry months will be created. For example: one wet, one
dry image for ... | 40,634 |
def _plot_error_part(ax, row, digit, offset, size):
"""Plots a single part of the error."""
# Plot the error part.
x = [offset, offset + size]
y1 = [row, row]
y2 = [row + 1, row + 1]
color = _digit_color(digit)
ax.fill_between(x, y1, y2, color=color, lw=0)
# Label the part if it is larg... | 40,635 |
def validate_path_for_get_public_key(path: list, slip44_id: int) -> bool:
"""
Checks if path has at least three hardened items and slip44 id matches.
The path is allowed to have more than three items, but all the following
items have to be non-hardened.
"""
length = len(path)
if length < 3 o... | 40,636 |
def generate_result(pic_type, img_path, predicted_breed=''):
"""
Generate a result of predicted dog breed for display in Jupyter Notebook.
Args:
pic_type (str): Type of picture, either 'dog', 'human' or 'error'
img_path (str): Path to the image provided by the user
predicted_breed (s... | 40,637 |
def main():
"""main function, parses params and runs command functions"""
# Commands dictionary
commands: Dict[str, Callable] = {
'hackerone-report-list': hackerone_report_list_command,
'hackerone-program-list': hackerone_program_list_command
}
params = demisto.params()
verify_... | 40,638 |
def concatSeriesMovies(dataFrame1, dataFrame2):
"""
Join, concat two dataFrames
Parameters:
dataFrame1: string
The name of the dataFrame the user wants to concat.
dataFrame2: string
The name of the dataFrame the user wants to concat.
Returns:
a new ... | 40,639 |
def Pattern7(s):
""" Compute the correlator for this pattern:
↓ ○
↑ ↑
and symmetry-equivalent patterns
"""
res = 0.0
s = np.pad(s, ((0, 0), (2, 2), (2, 2)))
L = s.shape[-1]
for i in range(L-2):
for j in range(L-2):
res += s[0, i, j] * s[0, i+1... | 40,640 |
def save_model(model, model_file):
"""Save XGBoost model for serving."""
joblib.dump(model, model_file)
logging.info("Model export success: %s", model_file) | 40,641 |
def list_camera_ports():
"""
Test the ports and returns a tuple with the available ports and the ones that are working
"""
non_working_ports = []
working_ports = []
available_ports = []
dev_port = 0
while len(non_working_ports) <= 3: # If there are more than 3 non working ports stop the ... | 40,642 |
def parse_taxid_names(file_path):
"""
Parse the names.dmp file and output a dictionary mapping names to taxids
(multiple different keys) and taxids to scientific names.
Parameters
----------
file_path : str
The path to the names.dmp file.
Returns
-------
name2taxid : dict
... | 40,643 |
def spec_to_in_spec_list(spec: np.array):
"""
Split full spectrogram song into list of sub-spectrograms, each of length 400ms
:param spec:
spec (np.array): 2D input numpy array spectrogram of given song (512 frequency bins x length of song (in 10ms)
:return:
in_spec_list (list): List of... | 40,644 |
def cache_trial_timing_bins(trials, trials_timing, bin_dur=.010, data_path='.'):
"""
todo: reinclude a check for bilaterals?
"""
cpath = os.path.join(data_path, 'caches', 'density')
tt = trials_timing
tt = add_uid(tt)
ttgb = tt.groupby('uid')
# load already cached trials and exclu... | 40,645 |
def dn_outfunc(e1, e2, W, V1=None, V2=None, b=None):
"""Applies a bilinear function based on given parameters.
This is a building block of Neural Tensor Network (see the reference paper
below). It takes two input variables and one or four parameters, and
outputs one variable.
To be precise, denote... | 40,646 |
def timsort2(lst: list) -> None:
"""Sort the given list using the version of timsort from Task 6.
"""
pass | 40,647 |
def action_can_be_queued(action_type):
"""
test the action_type whether can be queued
Inputs: action_type, int
Outputs: true or false
"""
need_args = actions.RAW_FUNCTIONS[action_type].args
result = False
for arg in need_args:
if arg.name == 'queued':
resu... | 40,648 |
def test_bad_headline():
"""Test that we raise an exception for this."""
with pytest.raises(CLIException):
cliparser(
get_test_file("CLI/CLIANC.txt").replace("WEATHER ITEM", "XXXX48"),
nwsli_provider=NWSLI_PROVIDER,
) | 40,649 |
def bench4(x):
"""A benchmark function for test purposes.
f(x) = float(x) ** 2
where x is a string. It has a single minima with f(x*) = 0 at x* = "0".
This benchmark is used for checking support of categorical variables.
"""
return float(x[0]) ** 2 | 40,650 |
def train_tokenizer(
train_path: str, output_path: str, strip_accents: bool =False,
lowercase: bool = False, vocab_size: int=30_000, min_frequency: int = 10, limit_alphabet:int = 400, num_files=40,
):
"""
Train tokenizer
Arguments:
clean_text (bool, optional, defaults to True) – Whether... | 40,651 |
def drop_columns_from_dataframe_if_all_elements_are_nan(df, elements_list=['', '']):
""" Takes two parameters:
df: Dataframe
elements_list: By default it will identify np.nan. If you want to add additional elements, as an example, you can do this ['', ' ']
"""
m = df.applymap(lambda i:... | 40,652 |
def drop_db(code, confirm_by_typing_db_code_again=None):
"""
Delete a history database.
Parameters
----------
code : str, required
the database code
confirm_by_typing_db_code_again : str, required
enter the db code again to confirm you want to drop the database, its config,
... | 40,653 |
def _nex_group(seq, core, spatial, c_num=4, s_num=4):
"""Build spatial stream index"""
# step 1
ant_num = c_num * s_num
seq_diff = np.diff(seq)
offset = np.where(seq_diff != 0)[0]
offset = np.r_[0, offset + 1]
count = np.diff(np.r_[offset, len(seq)])
offset = offset[count == ant_num]
... | 40,654 |
def create_table():
"""
创建表
:return:
"""
table_name = ["user", "category", "article"]
for table in table_name:
sql_table = "create class %s" % table
command(sql_table) | 40,655 |
async def test_async_init_timeout(circuit):
"""Test the async initialization time_out."""
async def w3():
await asyncio.sleep(0.1)
return 3
logger = TimeLogger('logger')
out = edzed.ValuePoll(
'out',
func=w3,
interval=10, # don't care
init_t... | 40,656 |
def compute_diffraction(
bundle,
key,
s,
eta,
L,
nlebedev=74,
nomega=12,
mode="xray",
form="raw",
anisotropy="cos2",
print_level=False,
):
"""Compute the I(s, eta) elastic scattering signal for a Bundle.
See aimsprop/notes/ued for details on this property.
... | 40,657 |
def convert_dict_id_values_to_strings(dict_list):
"""This function ensures that the ``id`` keys in a list of dictionaries use string values.
:param dict_list: List (or tuple) of dictionaries (or a single dictionary) containing API object data
:type dict_list: list, tuple, dict, None
:returns: A new dic... | 40,658 |
def delete_images(request):
"""
Deletes images which are passed via HTTP query.
"""
Image.objects.filter(pk__in=request.POST.getlist("images")).delete()
return HttpResponseRedirect(reverse("lfs_manage_global_images")) | 40,659 |
def is_requirements_file(location):
"""
Return True if the ``location`` is likely for a pip requirements file.
For example::
>>> is_requirements_file('dev-requirements.txt')
True
>>> is_requirements_file('requirements.txt')
True
>>> is_requirements_file('requirements.in')
True
>... | 40,660 |
def test_semple_data_():
"""test datA"""
from ..sample_data.__init__ import MOCK_DATA
assert type(MOCK_DATA) == list | 40,661 |
def bisect_steps_remaining():
"""Estimate of remaining steps, including the current one.
This is an approximation."""
# https://github.com/git/git/blob/566a1439f6f56c2171b8853ddbca0ad3f5098770/bisect.c#L1043
return floor(log(bisect_revisions(), 2)) | 40,662 |
def create_lstm_model(fingerprint_input, model_settings, model_size_info,
is_training):
"""Builds a model with a lstm layer (with output projection layer and
peep-hole connections)
Based on model described in https://arxiv.org/abs/1705.02411
model_size_info: [projection size, memo... | 40,663 |
def line_plot_poi(lines: dict, poi: list, poi_alpha=.3, **args):
"""
Plots up to 3 lines with points of interest, shaded red.
"""
assert len(lines) < 3 # For visibility.
fig, ax = plt.subplots()
sns.lineplot(data=Df(lines)).set(**args)
highlight = sns.color_palette()[3]
for a, b in po... | 40,664 |
def lostmode(disable,search,id,message):
"""Enable (or disable with --disable flag) lost mode for a device."""
global api
if search == None and id == None:
id = click.prompt('Which device?',type=int)
if search != None:
devices = api.get('mobiledevices/match/' + search + '%')
elif id... | 40,665 |
def tile(x: Tensor, count: int, dim=0) -> Tensor:
"""
Tiles x on dimension dim count times. From OpenNMT. Used for beam search.
:param x: tensor to tile
:param count: number of tiles
:param dim: dimension along which the tensor is tiled
:return: tiled tensor
"""
if isinstance(x, tuple):... | 40,666 |
def cancellable_request(handler: Callable[..., Coroutine[Any, Any, Optional[Any]]]):
"""this decorator periodically checks if the client disconnected and then will cancel the request and return a 499 code (a la nginx).
Usage:
decorate the cancellable route and add request: Request as an argument
@canc... | 40,667 |
def test_calc_heat_flux_evaporator():
"""Test calculation of cooling capacity for chiller 'Broad_01'."""
Q_dots_evap = ac.calc_heat_flux(
ddts=[50],
coef_s=24.121,
coef_r=-553.194,
method='kuehn_and_ziegler')
assert Q_dots_evap == [652.856] | 40,668 |
def add_central_server_member_delete_global_error_cert(case,
client, ss2_host,
ss2_username, ss2_password):
"""
Restores security server after member being deleted in central server
:param case:
... | 40,669 |
def get_country_models(model):
"""
Get all valid domain-specific models for a given model.
:param str model:
:return:
"""
domains = get_domain_for(model, country=None)
return ['{}{}-K9'.format(model, domain) for domain in domains] | 40,670 |
def FileExtensionMatch(filePath, supportedFileTypeList):
"""
Check whether the file extension matches any of the supported file types.
Parameters
----------
filePath : string
File path
supportedFileTypeList : list
List of supported file extensions
"""
return (os.path.splitext(filePath)... | 40,671 |
def _cprint_bad_contrast3(fgcolor, bgcolor, bold, underlined):
"""Returns 1 if one of the conditions of poor contrast is matched """
# black on black with LIGHT BG
_c1 = (fgcolor == 8) and (bgcolor == 0) and (CPRINT_PAR["light_background"])
if _c1:
return 1
else:
return 0 | 40,672 |
def download_from_mongo(context, sel_filter, projection):
"""
Download panda DataFrame from a mongoDB server
:param context: execution context
:param sel_filter: a SON object specifying elements which must be present for a document to be included in the
result set
:param proj... | 40,673 |
def paired_histogram( top, top_label, bot, bot_label, title='', figpath='' ):
"""
Makes a paired histogram of strand bias given two objects of the AmpliCat class
Assumes that we have already created the objects and read the csvs.
"""
# Set up figure
fig = plt.figure( figsize=(12,6) )
ax1... | 40,674 |
def sign2(screen, sign):
"""Displays hint 2"""
a = pygame.image.load('stuff/backgrounds/Frame.png')
b = pygame.transform.scale(a, (500, 100))
font = pygame.font.Font(None, 35)
message = font.render("Home Sweet Home", 1, (255, 255, 255))
if si... | 40,675 |
def create_group(current_session, groupname, description):
"""
Creates a group and returns it
"""
return gp.create_group(current_session, groupname, description) | 40,676 |
def call_api(endpoint):
"""
Build the API URL and request data
:param str endpoint: specific api endpoint to hit
:return response: server's reponse to the request
"""
url = BASE_URL + endpoint
try: # try to get json data
response = requests.get(url).json()
except ValueError: # ... | 40,677 |
def test_entropy_upper_bound(dist):
"""
H(X) <= log(|X|)
"""
h = H(dist)
logX = np.log2(len(dist.outcomes))
assert h <= logX + epsilon | 40,678 |
def initializeDiscFileTree( refreshGui ):
""" Called when first loading a disc or root folder, to clear/update the GUI. """
global unsavedDiscChanges
unsavedDiscChanges = []
Gui.isoFileTreeBg.place_forget() # Removes the background image if present
# Delete the current items in the tree
for item in Gu... | 40,679 |
def test_pop(dll_fixture):
"""Test the pop method on doubly linked list."""
dll_fixture.push('one')
dll_fixture.push('two')
dll_fixture.push('three')
assert dll_fixture.pop() == 'three' | 40,680 |
def test_callable_args(func, args):
"""
Return True when this function can be called with the given arguments.
"""
assert isinstance(args, (list, tuple))
signature = getattr(inspect, 'signature', None)
if signature is not None:
# For Python 3, use inspect.signature.
try... | 40,681 |
def get_kde_caseduration_json(df, parameters=None):
"""
Gets the estimation of KDE density for the case durations calculated on the log/dataframe
(expressed as JSON)
Parameters
--------------
df
Pandas dataframe
parameters
Possible parameters of the algorithm, including:
... | 40,682 |
def test_version_compare():
"""Test version comparison code, for parity with mozilla-central."""
numlist = enumerate(map(lambda v: Version(v), COMPARISONS))
for i, v1 in numlist:
for j, v2 in numlist:
if i < j:
assert v1 < v2, '%s is not less than %s' % (v1, v2)
... | 40,683 |
def render_text(name: str,
data: str,
font_size: int = 10,
fig_width_per_char: float = 0.1,
fig_height: float = 0.4,
img_height: int = None,
img_width: int = None,
**kwargs):
"""Render a text string.
... | 40,684 |
def index_closed(client, index_name):
"""Return True if index is closed"""
try:
# 1.0 params
index_metadata = client.cluster.state(
index=index_name,
metric='metadata',
)
except TypeError:
# 0.90 params:
index_metadata = client.cluster.state(
... | 40,685 |
def calculate_partial_volume(dirname, label, _isAccumulated=True):
"""
This function...
:param dirname:
:param label:
:param _isAccumulated:
:return:
"""
label = label.upper()
maskSum = 0.0
if _isAccumulated:
fileDir = _config.get("Results", "accumulated")
else:
... | 40,686 |
def say_hello():
""" Prints Hello, world message"""
print(hello()) | 40,687 |
def get_contributions_with_user_as_submitter(event, user):
"""Get a list of contributions in which the `user` has submission rights"""
return (_query_contributions_with_user_as_submitter(event, user)
.options(joinedload('acl_entries'))
.order_by(db.func.lower(Contribution.title))
... | 40,688 |
def makedirs(name):
"""helper function for python 2 and 3 to call os.makedirs()
avoiding an error if the directory to be created already exists"""
# stdlib
import errno
import os
try:
os.makedirs(name)
except OSError as ex:
if ex.errno == errno.EEXIST and os.path.isdir(name... | 40,689 |
def rewrite_string(
searcher: AbstractSearcher,
source: Text,
path: Text,
max_iterations=1,
) -> Text:
"""Applies any replacements to the input source, and returns the result."""
return formatting.apply_substitutions(
source, find_iter(
searcher,
source,
path,
... | 40,690 |
def build_path_result_tests(name):
"""
Build a test for API commands that respond with ``Err`` and
``Mountpoint`` fields.
:param unicode command_name: The command in the schema to validate.
:return: ``TestCase``.
"""
return build_schema_test(
name=str(name + "Tests"),
schem... | 40,691 |
def get_latest_released_dist():
"""Get the latest released distribution
"""
# construct the distribution downloading url
relative_path = get_relative_path_of_dist_storage(latest_product_release_api + "xml")
if relative_path is None:
raise Exception("Error occured while getting relative p... | 40,692 |
def get_mpls_autobw_template_detail_rpc(self, api_timeout=''):
"""
This is an auto-generated method for the PySwitchLib.
**Supported Versions**:
* SLXOS: 17r.1.01a, 17r.2.00, 17s.1.02
:type api_timeout: long or tuple(long, long)
:param api_timeout: Timeout for connection and response ... | 40,693 |
def empty(a):
"""Test whether the slice is empty."""
return a is None or volume(a)==0 | 40,694 |
def handle_server_error(exception):
"""
handles server internal core exceptions.
note that normally you should never call this method manually.
in any environment which debug mode is False, the original error
message will be replaced by a generic error message before being
sent to client for se... | 40,695 |
def nnPredict(w1, w2, data):
"""% nnPredict predicts the label of data given the parameter w1, w2 of Neural
% Network.
% Input:
% w1: matrix of weights of connections from input layer to hidden layers.
% w1(i, j) represents the weight of connection from unit i in input
% layer to unit ... | 40,696 |
def count_pairs(array: List[int], difference: int) -> int:
"""
Given an array of integers, count the number of unique pairs of integers that have a given difference.
These pairs are stored in a set in order to remove duplicates.
Time complexity: O(n^2).
:param array: is the array to count.
:par... | 40,697 |
def debug(msg: str) -> None:
"""Write debug message to stderr.
Debug message consists file name, line number and function name
of the calling routine.
Args:
msg: a custom message.
"""
parent_frame = inspect.stack()[1]
file = parent_frame[1]
line = parent_frame[2]
func = parent_frame[3]
sys.std... | 40,698 |
def decompress_deltas_18bit(buffer):
"""Parse packet deltas from 18-byte compression format."""
if bad_data_size(buffer, 18, "18-byte compressed packet"):
raise ValueError("Bad input size for byte conversion.")
deltas = np.zeros((2, 4))
# Sample 1 - Channel 1
minibuf = [(buffer[0] >> 6),
... | 40,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.