content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def validate_policy_spec(policy_spec):
"""
:param PolicySpecification policy_spec:
"""
# validate policy values
if policy_spec.policy:
p = policy_spec.policy
# validate key pair values
if policy_spec.policy.key_pair:
if len(policy_spec.policy.key_pair.key_types) ... | 5,346,400 |
def zeros(shape, dtype=None):
"""
Create a Tensor filled with zeros, closer to Numpy's syntax than ``alloc``.
"""
if dtype is None:
dtype = config.floatX
return alloc(numpy.array(0, dtype=dtype), *shape) | 5,346,401 |
def station_location_from_rinex(rinex_path: str) -> Optional[types.ECEF_XYZ]:
"""
Opens a RINEX file and looks in the headers for the station's position
Args:
rinex_path: the path to the rinex file
Returns:
XYZ ECEF coords in meters for the approximate receiver location
approxi... | 5,346,402 |
def UpdatePDB(pdb_filename, verbose=True, build_dir=None, toolchain_dir=None):
"""Update a pdb file with source information."""
dir_blacklist = { }
if build_dir:
# Blacklisting the build directory allows skipping the generated files, for
# Chromium this makes the indexing ~10x faster.
build_dir = (os... | 5,346,403 |
def get_profiles():
"""Return the paths to all profiles in the local library"""
paths = APP_DIR.glob("profile_*")
return sorted(paths) | 5,346,404 |
def main(ctx, *args, **kwargs):
"""
This script generate a Dockerfile from Dockertemplate (jinja template).
"""
if ctx.invoked_subcommand is None:
ctx.forward(generate) | 5,346,405 |
def split(array, nelx, nely, nelz, dof):
"""
Splits an array of boundary conditions into an array of collections of
elements. Boundary conditions that are more than one node in size are
grouped together. From the nodes, the function returns the neighboring
elements inside the array.
"""
if l... | 5,346,406 |
def test_no_source(test_dir: str) -> None:
"""cp d_file -> d_file.back should fail if d_file does not exist"""
d_file = os.path.join(test_dir, "d_file")
sys.argv = ["pycp", d_file, "d_file.back"]
with pytest.raises(SystemExit):
pycp_main() | 5,346,407 |
async def test_setup(hass):
"""Test the general setup of the integration."""
# Set up some mock feed entries for this test.
mock_entry_1 = _generate_mock_feed_entry(
"1234",
"Title 1",
15.5,
(38.0, -3.0),
locality="Locality 1",
attribution="Attribution 1",
... | 5,346,408 |
def sanitize_app_name(app):
"""Sanitize the app name and build matching path"""
app = "".join(c for c in app if c.isalnum() or c in ('.', '_')).rstrip().lstrip('/')
return app | 5,346,409 |
def send_email(ses_connection, signed_url, email_from, email_subject, email_to,
email_cc, email_rt, email_date):
"""
Function designed to send an email
:param signed_url: The Signed URL
:param email_from: The "from" email address
:param email_subject: The Subject of the email
:par... | 5,346,410 |
def get_rinex_file_version(file_path: pathlib.PosixPath) -> str:
""" Get RINEX file version for a given file path
Args:
file_path: File path.
Returns:
RINEX file version
"""
with files.open(file_path, mode="rt") as infile:
try:
version = infile.readline... | 5,346,411 |
def get_hm_port(identity_service, local_unit_name, local_unit_address,
host_id=None):
"""Get or create a per unit Neutron port for Octavia Health Manager.
A side effect of calling this function is that a port is created if one
does not already exist.
:param identity_service: reactive E... | 5,346,412 |
def benchmark(ctx, report=False):
"""
Run and generate benchmarks for current code
"""
import benchmarks
benchmarks.main(report=report) | 5,346,413 |
def total_length(neurite):
"""Neurite length. For a morphology it will be a sum of all neurite lengths."""
return sum(s.length for s in neurite.iter_sections()) | 5,346,414 |
def _solarize(img, magnitude):
"""solarize"""
return ImageOps.solarize(img, magnitude) | 5,346,415 |
def calculateCurvature(yRange, left_fit_cr):
"""
Returns the curvature of the polynomial `fit` on the y range `yRange`.
"""
return ((1 + (2 * left_fit_cr[0] * yRange * ym_per_pix + left_fit_cr[1]) ** 2) ** 1.5) / np.absolute(
2 * left_fit_cr[0]) | 5,346,416 |
def assert_all_finite(X):
"""Throw a ValueError if X contains NaN or infinity.
Input MUST be an np.ndarray instance or a scipy.sparse matrix."""
# First try an O(n) time, O(1) space solution for the common case that
# there everything is finite; fall back to O(n) space np.isfinite to
# prevent fal... | 5,346,417 |
def find_file_in_sequence(file_root: str, file_number: int = 1) -> tuple:
"""
Returns the Nth file in an image sequence where N is file_number (-1 for first file).
Args:
file_root: image file root name.
file_number: image file number in sequence.
Returns:
tuple (filename,sequen... | 5,346,418 |
def testing_server_error_view(request):
"""Displays a custom internal server error (500) page"""
return render(request, '500.html', {}) | 5,346,419 |
def main_epilog() -> str:
"""
This method builds the footer for the main help screen.
"""
msg = "To get help on a specific command, see `conjur <command> -h | --help`\n\n"
msg += "To start using Conjur with your environment, you must first initialize " \
"the configuration. See `conjur in... | 5,346,420 |
def apt_update(fatal=False):
"""Update local apt cache"""
cmd = ['apt-get', 'update']
_run_apt_command(cmd, fatal) | 5,346,421 |
def sigma_M(n):
"""boson lowering operator, AKA sigma minus"""
return np.diag([np.sqrt(i) for i in range(1, n)], k=1) | 5,346,422 |
def protected_view(context, request):
""" """
raise HTTPForbidden() | 5,346,423 |
def windowing_is(root, *window_sys):
"""
Check for the current operating system.
:param root: A tk widget to be used as reference
:param window_sys: if any windowing system provided here is the current
windowing system `True` is returned else `False`
:return: boolean
"""
windowing = r... | 5,346,424 |
def init_columns_entries(variables):
"""
Making sure we have `columns` & `entries` to return, without effecting the original objects.
"""
columns = variables.get('columns')
if columns is None:
columns = [] # Relevant columns in proper order
if isinstance(columns, str):
columns ... | 5,346,425 |
def _run_ic(dataset: str, name: str) -> Tuple[int, float, str]:
"""Run iterative compression on all datasets.
Parameters
----------
dataset : str
Dataset name.
name : str
FCL name.
Returns
-------
Tuple[int, float, str]
Solution size, time, and certificate.
... | 5,346,426 |
def test_report_scaled_data(dials_data, tmpdir):
"""Test that dials.report works on scaled data."""
result = procrunner.run(
[
"dials.report",
dials_data("l_cysteine_4_sweeps_scaled") / "scaled_30.refl",
dials_data("l_cysteine_4_sweeps_scaled") / "scaled_30.expt",
... | 5,346,427 |
def notch(Wn, Q=10, analog=False, output="ba"):
"""
Design an analog or digital biquad notch filter with variable Q.
The notch differs from a peaking cut filter in that the gain at the
notch center frequency is 0, or -Inf dB.
Transfer function: H(s) = (s**2 + 1) / (s**2 + s/Q + 1)
Parameter
... | 5,346,428 |
def dict_to_unyt(dict_obj) -> None:
"""Recursively convert values of dictionary containing units information to unyt quantities"""
for key, value in dict_obj.items():
if isinstance(value, dict):
if "array" not in value and "unit" not in value:
dict_to_unyt(value)
... | 5,346,429 |
def dvpool(name: str) -> None:
"""
Delete a variable from the kernel pool.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/dvpool_c.html
:param name: Name of the kernel variable to be deleted.
"""
name = stypes.string_to_char_p(name)
libspice.dvpool_c(name) | 5,346,430 |
def test_config_key_error():
"""An unknown key should throw a key error"""
c = core.Config()
with pytest.raises(KeyError):
c['doesNotExist'] | 5,346,431 |
def test_BBPSSW_psi_minus_psi_minus():
"""
psi- psi-
0b0
[0. +0.j 0.5+0.j 0.5+0.j 0. +0.j]
0b1
[0.+0.j 0.+0.j 0.+0.j 0.+0.j]
0b10
[0.+0.j 0.+0.j 0.+0.j 0.+0.j]
0b11
[ 0. +0.j -0.5+0.j -0.5+0.j 0. +0.j]
"""
counter = 0
for i in range(100):
... | 5,346,432 |
def Torus(radius=(1, 0.5), tile=(20, 20), device='cuda:0'):
"""
Creates a torus quad mesh
Parameters
----------
radius : (float,float) (optional)
radii of the torus (default is (1,0.5))
tile : (int,int) (optional)
the number of divisions of the cylinder (default is (20,20))
... | 5,346,433 |
def check_new_value(new_value: str, definition) -> bool:
"""
checks with definition if new value is a valid input
:param new_value: input to set as new value
:param definition: valid options for new value
:return: true if valid, false if not
"""
if type(definition) is list:
if new_va... | 5,346,434 |
def covid_API(cases_and_deaths: dict) -> dict:
"""
Imports Covid Data
:param cases_and_deaths: This obtains dictionary from config file
:return: A dictionary of covid information
"""
api = Cov19API(filters=england_only, structure=cases_and_deaths)
data = api.get_json()
return dat... | 5,346,435 |
def cnn(train_x, train_y, test1_x, test1_y, test2_x, test2_y):
"""
Train and evaluate a feedforward network with two hidden layers.
"""
# Add a single "channels" dimension at the end
trn_x = train_x.reshape([-1, 30, 30, 1])
tst1_x = test1_x.reshape([-1, 30, 30, 1])
tst2_x = test2_x.re... | 5,346,436 |
def gather_gltf2(export_settings):
"""
Gather glTF properties from the current state of blender.
:return: list of scene graphs to be added to the glTF export
"""
scenes = []
animations = [] # unfortunately animations in gltf2 are just as 'root' as scenes.
active_scene = None
for blende... | 5,346,437 |
def getOneRunMountainCarFitness_modifiedReward(tup):
"""Get one fitness from the MountainCar or MountainCarContinuous
environment while modifying its reward function.
The MountainCar environments reward only success, not progress towards
success. This means that individuals that are trying to drive up... | 5,346,438 |
def ArtToModel(art, options):
"""Convert an Art object into a Model object.
Args:
art: geom.Art - the Art object to convert.
options: ImportOptions - specifies some choices about import
Returns:
(geom.Model, string): if there was a major problem, Model may be None.
The string will... | 5,346,439 |
def simulate_data(N, intercept, slope, nu, sigma2=1, seed=None):
"""Simulate noisy linear model with t-distributed residuals.
Generates `N` samples from a one-dimensional linear regression with
residuals drawn from a t-distribution with `nu` degrees of freedom, and
scaling-parameter `sigma2`. The true ... | 5,346,440 |
def _link_irods_folder_to_django(resource, istorage, foldername, exclude=()):
"""
Recursively Link irods folder and all files and sub-folders inside the folder to Django
Database after iRODS file and folder operations to get Django and iRODS in sync
:param resource: the BaseResource object representing... | 5,346,441 |
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
"""
52ms 93.76%
13.1MB 83.1%
:param self:
:param head:
:param n:
:return:
"""
if not head:
return head
dummy = ListNode(0)
dummy.next = head
fast = dummy
while n:
fast = fast.next
... | 5,346,442 |
def validate_template(
template: Any, allow_deprecated_identifiers: bool = False
) -> Tuple[PackageRef, str]:
"""
Return a module and type name component from something that can be interpreted as a template.
:param template:
Any object that can be interpreted as an identifier for a template.
... | 5,346,443 |
def call_status():
"""
Route received for webhook about call
"""
if 'mocean-call-uuid' in request.form:
call_uuid = request.form.get('mocean-call-uuid')
logging.info(f'### Call status received [{call_uuid}] ###')
for k, v in request.form.items():
logging.info(f'\t{... | 5,346,444 |
def read_data(filename,**kwargs):
"""Used to read a light curve or curve object in pickle format.
Either way, it'll come out as a curve object.
Parameters
----------
filename : str
Name of the file to be read (ascii or pickle)
Returns
-------
curve : :class:`~sntd.curve` or... | 5,346,445 |
def test_invalid_unit_spec_nonalphabetic_unit_name():
"""Tests a unit specification file with a unit name 's3cond'.
"""
this_dir = get_cwd()
path = os.path.join(this_dir, "test_files", "non_alphabetic_unit_name.txt")
with pytest.raises(SyntaxError):
up = unit_parser(path) | 5,346,446 |
def get_masters(domain):
""" """
content = request.get_json()
conf = {
'check_masters' : request.headers.get('check_masters'),
'remote_api' : request.headers.get('remote_api'),
'remote_api_key' : request.headers.get('remote_api_key')
}
masters = pdns_get_masters(
remo... | 5,346,447 |
def draw_all_objects():
"""For all objects, draw theirs sprites"""
window.clear()
for x_offset in (-window.width, 0, window.width):
for y_offset in (-window.height, 0, window.height):
# Remember the current state
gl.glPushMatrix()
# Move everything drawn from now... | 5,346,448 |
async def reddit(ctx,subreddit='wholesome'):
"""posts random reddit post with given argument"""
await ctx.send(embed=await pyrandmeme(subreddit)) | 5,346,449 |
def SplitGeneratedFileName(fname):
"""Reverse of GetGeneratedFileName()
"""
return tuple(fname.split('x',4)) | 5,346,450 |
def test_env_lag_14(request, env_complex):
"""Verify env_lag fixture adds LAGs into LagsAdmin table in complex setup.
"""
fixtures.env_lag(request, env_complex)
for _switch in env_complex.switch.values():
_switch.clearconfig()
lags = set(x['lagId'] for x in env_complex.switch[1].ui.get_tabl... | 5,346,451 |
def save_questions(questions, seperator="\n=========\n"):
"""
save all the question variations for future reference
"""
with open("questions.txt", "w") as f:
question_variations = [seperator.join(question) for question in questions]
output = seperator.join(question_variations)
f.... | 5,346,452 |
def pre_deploy_synapses(event):
"""
Создание пустого вектора нейронов.
"""
agent = event.pool.context['agent']
net = agent.context['net']
net.pre_deploy_synapses() | 5,346,453 |
def test_folder_with_multiple_images():
"""[summary]
"""
# Empty dir
empty_dir(TEST_DIRECTORY_PATH)
# Build catalog
catalog_path, label_paths, img_paths = build_catalog(TEST_DIRECTORY_PATH)
# Get all images from folder
paths = get_all_images_from_folder(TEST_DIRECTORY_PATH)
# Asse... | 5,346,454 |
def chooseBestFeatureToSplit(dataSet):
"""
选择最优划分特征
输入: 数据集
输出: 最优特征
"""
numFeatures = len(dataSet[0])-1
baseEntropy = calcShannonEnt(dataSet) #原始数据的熵
bestInfoGain = 0
bestFfeature = -1
for i in range(numFeatures): #循环所有特征
featList = [example[i] for example in dataSet]
... | 5,346,455 |
def evaluate_model(model: torch.nn.Module, dataloader: torch.utils.data.DataLoader, device: torch.device):
"""Function for evaluation of a model `model` on the data in `dataloader` on device `device`"""
# Define a loss (mse loss)
mse = torch.nn.MSELoss()
# We will accumulate the mean loss in variable `l... | 5,346,456 |
def get_DOE_quantity_byfac(DOE_xls, fac_xls, facilities='selected'):
"""
Returns total gallons of combined imports and exports
by vessel type and oil classification to/from WA marine terminals
used in our study.
DOE_xls[Path obj. or string]: Path(to Dept. of Ecology transfer dataset)
faci... | 5,346,457 |
def number_finder(page, horse):
"""Extract horse number with regex."""
if 'WinPlaceShow' in page:
return re.search('(?<=WinPlaceShow\\n).[^{}]*'.format(horse), page).group(0)
elif 'WinPlace' in page:
return re.search('(?<=WinPlace\\n).[^{}]*'.format(horse), page).group(0) | 5,346,458 |
def ssd_300_mobilenet0_25_coco(pretrained=False, pretrained_base=True, **kwargs):
"""SSD architecture with mobilenet0.25 base networks for COCO.
Parameters
----------
pretrained : bool or str
Boolean value controls whether to load the default pretrained weights for model.
String value r... | 5,346,459 |
async def all_items(connection: asyncpg.Connection, /) -> AsyncIterator[types.Item]:
"""Returns an :class:`AsyncGenerator` of all :class:`types.Item` in the database."""
for record in await tables.Items.fetch(connection):
yield await _item(connection, record) | 5,346,460 |
async def test_exclude_filters(hass):
"""Test exclusion filters."""
request = get_new_request("Alexa.Discovery", "Discover")
# setup test devices
hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"})
hass.states.async_set("script.deny", "off", {"friendly_name": "Blocked scri... | 5,346,461 |
def test_get_instance_handle(participant, publisher):
"""
This test checks:
- Publisher::get_instance_handle
- Publisher::guid
"""
ih = publisher.get_instance_handle()
assert(ih is not None)
assert(ih.isDefined())
guid = participant.guid()
assert(guid is not None)
assert(ih ... | 5,346,462 |
def retry( delays=(0, 1, 1, 4, 16, 64), timeout=300, predicate=never ):
"""
Retry an operation while the failure matches a given predicate and until a given timeout
expires, waiting a given amount of time in between attempts. This function is a generator
that yields contextmanagers. See doctests below f... | 5,346,463 |
def get_project_by_id(client: SymphonyClient, id: str) -> Project:
"""Get project by ID
:param id: Project ID
:type id: str
:raises:
* FailedOperationException: Internal symphony error
* :class:`~psym.exceptions.EntityNotFoundError`: Project does not exist
:return: Project
:rt... | 5,346,464 |
def write_trans_output(k, output_fname, output_steps_fname, x, u, time, nvar):
"""
Output transient step and spectral step in a CSV file"""
# Transient
if nvar > 1:
uvars = np.split(u, nvar)
results_u = [np.linalg.norm(uvar, np.inf) for uvar in uvars]
results = [
time... | 5,346,465 |
def test_singular_dimensions_2d(periodic):
""" test grids with singular dimensions """
dim = np.random.randint(3, 5)
g1 = UnitGrid([dim], periodic=periodic)
g2a = UnitGrid([dim, 1], periodic=periodic)
g2b = UnitGrid([1, dim], periodic=periodic)
data = np.random.random(dim)
expected = g1.get... | 5,346,466 |
def test_setext_headings_extra_16():
"""
Test case extra 16: SetExt heading containing an URI autolink
"""
# Arrange
source_markdown = """look at <http://www.google.com> for answers
---"""
expected_tokens = [
"[setext(2,1):-:3::(1,1)]",
"[text(1,1):look at :]",
"[uri-au... | 5,346,467 |
def flatten(l):
"""Recursively flatten a list of irregular lists.
Taken from: https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists"""
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
yield from flatten(el)
else:... | 5,346,468 |
def browser(browserWsgiAppS):
"""Fixture for testing with zope.testbrowser."""
assert icemac.addressbook.testing.CURRENT_CONNECTION is not None, \
"The `browser` fixture needs a database fixture like `address_book`."
return icemac.ab.calendar.testing.Browser(wsgi_app=browserWsgiAppS) | 5,346,469 |
def mixture_fit(samples,
model_components,
model_covariance,
tolerance,
em_iterations,
parameter_init,
model_verbosity,
model_selection,
kde_bandwidth):
"""Fit a variational Bayesian non-p... | 5,346,470 |
def chunks(codes, n):
"""
Breaks a list of codes into roughly equal n-sized pieces.
"""
for i in xrange(0, len(codes), n):
yield codes[i:i+n] | 5,346,471 |
def add_project_template_files():
"""Adds the project template files to the sample project.
Raises:
IOError: An error occurred copying the project template files.
"""
firebase_feature = FEATURE_ARGS_ARRAY[0].lower()
common_ios_project_file = os.path.join(
ROOT_DIRECTORY, "common/project_template_fi... | 5,346,472 |
def print_tab_seperated(results):
"""
prints the resulting dict
@param results: dict (maps metadata_name to a a list consisting of no. correct results and no of obtained
results for each threshold )
"""
for k, v in results.items():
print(k)
for correct, obtained in v:
... | 5,346,473 |
def apply_k8s_specs(specs, mode=K8S_CREATE): # pylint: disable=too-many-branches,too-many-statements
"""Run apply on the provided Kubernetes specs.
Args:
specs: A list of strings or dicts providing the YAML specs to
apply.
mode: (Optional): Mode indicates how the resources should be created.
K... | 5,346,474 |
def patch_dependencies(monkeypatch):
"""
This function is called before each test.
"""
monkeypatch.setattr(SpotifyClient, "init", new_initialize)
monkeypatch.setattr(
asyncio.subprocess, "create_subprocess_exec", fake_create_subprocess_exec
) | 5,346,475 |
def local_coherence(Q, ds=1):
""" estimate the local coherence of a spectrum
Parameters
----------
Q : numpy.array, size=(m,n), dtype=complex
array with cross-spectrum, with centered coordinate frame
ds : integer, default=1
kernel radius to describe the neighborhood
Returns
... | 5,346,476 |
def find_best_lexer(text, min_confidence=0.85):
"""
Like the built in pygments guess_lexer, except has a minimum confidence
level. If that is not met, it falls back to plain text to avoid bad
highlighting.
:returns: Lexer instance
"""
current_best_confidence = 0.0
current_best_lexer = ... | 5,346,477 |
def volta(contador, quantidade):
"""
Volta uma determinada quantidade de caracteres
:param contador: inteiro utilizado para determinar uma posição na string
:param quantidade: inteiro utilizado para determinar a nova posição na string
:type contador: int
:type quantidade: int
:return: retorn... | 5,346,478 |
def p_relop_gt(p: yacc.YaccProduction):
"""REL_OP : GREATER_THAN"""
pass | 5,346,479 |
def keep_room(session, worker_id, room_id):
"""Try to keep a room"""
# Update room current timestamp
query = update(
Room
).values({
Room.updated: func.now(),
}).where(
and_(Room.worker == worker_id,
Room.id == room_id)
)
proxy = session.execute(query)
... | 5,346,480 |
def get_rounds(number: int) -> List[int]:
"""
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return list(range(number, number + 3)) | 5,346,481 |
def parse_pasinobet(url):
"""
Retourne les cotes disponibles sur pasinobet
"""
selenium_init.DRIVER["pasinobet"].get("about:blank")
selenium_init.DRIVER["pasinobet"].get(url)
match_odds_hash = {}
match = None
date_time = None
WebDriverWait(selenium_init.DRIVER["pasinobet"], 15).until... | 5,346,482 |
def create_toolbutton(parent, icon=None, tip=None, triggered=None):
"""Create a QToolButton."""
button = QToolButton(parent)
if icon is not None:
button.setIcon(icon)
if tip is not None:
button.setToolTip(tip)
if triggered is not None:
button.clicked.connect(triggered... | 5,346,483 |
def for_logging(filename: str = 'logs/app.log',
filemode: str = 'w+',
level: int = logging.DEBUG,
log_format: str = '%(asctime)s :: %(levelname)-5s :: %(threadName)-24s :: %(name)-24s - %(message)s',
stdout: bool = True):
"""
Preconfigures the defa... | 5,346,484 |
def __basic_query(model, verbose: bool = False) -> pd.DataFrame:
"""Execute and return basic query."""
stmt = select(model)
if verbose:
print(stmt)
return pd.read_sql(stmt, con=CONN, index_col="id") | 5,346,485 |
def format_data_preprocessed(data, dtype = np.float):
"""
The input data preprocessing
data the input data frame
preprocessing whether to use features preprocessing (Default: False)
dtype the data type for ndarray (Default: np.float)
"""
train_flag = np.array(data['train_flag'])
print '... | 5,346,486 |
def run_SVM_KNN_thread(word2vec_src):
"""
Run SVM->KNN+word embedding experiment !
This is the baseline method.
:return:None
"""
classX1 = []
classX2 = []
classX3 = []
classX4 = []
classY1 = []
classY2 = []
classY3 = []
classY4 = []
classTX1 = []
classTX2 = []
classTX3 = []
classTX4 = ... | 5,346,487 |
def route_yo(oauth_client=None):
"""Sends a Yo!
We can defer sender lookup to the Yo class since it should be obtained
from the request context. Requiring an authenticated user reduces the
likelihood of accidental impersonation of senders.
Creating pseudo users is handled here. It should be limite... | 5,346,488 |
def get_word_idxs_1d(context, token_seq, char_start_idx, char_end_idx):
"""
0 based
:param context:
:param token_seq:
:param char_start_idx:
:param char_end_idx:
:return: 0-based token index sequence in the tokenized context.
"""
spans = get_1d_spans(context,token_seq)
idxs ... | 5,346,489 |
def create_b64_from_private_key(private_key: X25519PrivateKey) -> bytes:
"""Create b64 ascii string from private key object"""
private_bytes = private_key_to_bytes(private_key)
b64_bytes = binascii.b2a_base64(private_bytes, newline=False)
return b64_bytes | 5,346,490 |
def safe_makedirs(path):
"""Safely make a directory, do not fail if it already exists or is created during execution.
:type path: string
:param path: a directory to create
"""
# prechecking for existence is faster than try/except
if not exists(path):
try:
makedirs(pat... | 5,346,491 |
def auto_declare_viewsets(serializers_module, context):
""" Automatically declares classes from serializers
:param serializers_module: Passes the module to search serializer classes.
:param context: Context module to export classes, should passes locals().
"""
for serializer in serializers_module.__... | 5,346,492 |
def create_fake_record(filename):
"""Create records for demo purposes."""
data_to_use = _load_json(filename)
data_acces = {
"access_right": fake_access_right(),
"embargo_date": fake_feature_date(),
}
service = Marc21RecordService()
draft = service.create(
data=data_to_u... | 5,346,493 |
def update_file_contents(job_id: int, relative_file_path: str, contents: str) -> None:
"""
This function works only with Job Type
"""
path_to_files = get_path_to_files(Type.Job, job_id)
filepath = os.path.join(path_to_files, relative_file_path)
with open(filepath, 'w') as file_:
file_.wr... | 5,346,494 |
def load(filename):
"""Eval every expression from a file.
:param filename: the name of the file to load
"""
if not filename.endswith('.scm'):
filename = filename + '.scm'
inport = InPort(open(filename))
while True:
try:
x = parse(inport)
if x is eof_object... | 5,346,495 |
def load_configuration():
"""
This function loads the configuration from the
config.json file and then returns it.
Returns: The configuration
"""
with open('CONFIG.json', 'r') as f:
return json.load(f) | 5,346,496 |
def config_parse(profile_name):
"""Parse the profile entered with the command line. This profile is in the profile.cfg file.
These parameters are used to automate the processing
:param profile_name: Profile's name"""
import configparser
config = configparser.ConfigParser()
config.read(os.path.d... | 5,346,497 |
def scrape(webpage, linkNumber, extention):
"""
scrapes the main page of a news website using request and beautiful soup and
returns the URL link to the top article as a string
Args:
webpage: a string containing the URL of the main website
linkNumber: an integer... | 5,346,498 |
def Scheduler(type):
"""Instantiate the appropriate scheduler class for given type.
Args:
type (str): Identifier for batch scheduler type.
Returns:
Instance of a _BatchScheduler for given type.
"""
for cls in _BatchScheduler.__subclasses__():
if cls.is_scheduler_for(type):
... | 5,346,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.