content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def event_message(iden, event):
"""Return an event message."""
return {"id": iden, "type": "event", "event": event} | 14,300 |
def match(command):
"""Match function copied from cd_mkdir.py"""
return (
command.script.startswith('cd ') and any((
'no such file or directory' in command.output.lower(),
'cd: can\'t cd to' in command.output.lower(),
'does not exist' in command.output.lower()
... | 14,301 |
def db_remove_game(game: str, channel: str) -> bool:
"""Removes a game from the database, for a specific channel
"""
if db_check_game_exists(game, channel):
cursor.execute(
"DELETE FROM deathcount "
"WHERE channel=(?) AND game=(?)",
(channel.lower(), game.lower(... | 14,302 |
def get_unique_id():
"""Return an ID that will be unique over the current segmentation
:return: unique_id
:rtype: int
"""
global UNIQUE_ID
UNIQUE_ID = UNIQUE_ID + 1
return UNIQUE_ID | 14,303 |
def human_study_csv_entity(datadir, src, tgt, nsample):
"""process model output for the entity control experiment, and
generate csv files for human study of entity control.
This function will yield a `human_study_entity.csv` file in the
`datadir` directory
Args:
datadir: the dataset director... | 14,304 |
def logout_route():
"""logout route"""
logout_user()
return redirect(url_for('app.index_route')) | 14,305 |
def setup_command_line_parser():
"""
Sets up command line argument parser. Additional arguments could be added
easily. For example if the version needed to be passed in with -v you
could add it as a positional argument like so:
parser.add_argument("-v", "--version", help="Current ver... | 14,306 |
def test_fenced_code_blocks_extra_03x():
"""
Test case extra 03: variation of 1 where list already opened but no new list item
NOTE: Small change to output to remove newline at pre/code at end.
"""
# Arrange
source_markdown = """- ```
some text
some other text
```
"""
expected_tokens = ... | 14,307 |
def get_repo_name(
name: str, in_mode: str, include_host_name: bool = False
) -> str:
"""
Return the full/short name of a Git repo based on the other name.
:param in_mode: the values `full_name` or `short_name` determine how to interpret
`name`
"""
repo_map = get_complete_repo_map(in_mo... | 14,308 |
def uvSnapshot(aa=1,b="int",euv=1,ff="string",g="int",n="string",o=1,r="int",umx="float",umn="float",uvs="string",vmx="float",vmn="float",xr="int",yr="int"):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/uvSnapshot.html
-----------------------------------------
uvSnapshot is NOT ... | 14,309 |
def binary_search_hi(a,d,lo,hi):
"""
Created for leetcode prob 34
"""
if d!=a[lo]:
raise Exception("d should be a[lo]")
while hi>lo:
mid=(lo+hi)//2+1
if a[mid]==d:
lo=mid
else:
hi=mid-1
if a[hi]==d:
return hi
else:
retur... | 14,310 |
def log_to_file(csifile='csifile.dat'):
"""Implement log_to_file in Python"""
f = open(csifile, 'wb')
# show frequency
count = 0
SLOW_MSG_CNT = 1
# /usr/include/linux/connector.h
# #define CN_NETLINK_USERS 10 /* Highest index + 1 */
CN_NETLINK_USERS = 10
CN_IDX_IWLAGN = CN_NETLINK... | 14,311 |
def delete(task_id):
"""Remove task in db with given id."""
with _tasks_db():
tasks.delete(task_id) | 14,312 |
def check_subscription(func):
"""Checks if the user signed up for a paid subscription """
@wraps(func)
def wrapper(*args, **kwargs):
if current_user.is_authenticated():
subscription = current_user.subscription
if not subscription.active and subscription.plan.name != 'Free':
... | 14,313 |
def spikesbetter(P):
"""
same as the custom cython function _dice6, a python implementation for easy use on other computers
does spin selection procedure based on given array of probabilities
--------------------------------------------------------------------
Inputs:
P: probability of silence a... | 14,314 |
def generate_edits(diff):
"""Generate edit commands from an RCS diff block.
DIFF is a string holding an entire RCS file delta. Generate a tuple
(COMMAND, INPUT_POS, ARG) for each block implied by DIFF. Tuples
describe the ed commands:
('a', INPUT_POS, LINES) : add LINES at INPUT_POS. LINES is a
... | 14,315 |
def questionnaire():
"""
Questions to ask if no arguments given.
"""
mcc = questionnaire_3digit("MCC")
mnc = questionnaire_3digit("MNC")
device = scriptutils.questionnaire_device()
bundles = utilities.i2b("CHECK BUNDLES?: ")
if bundles:
download = False
upgrade = False
... | 14,316 |
def main():
"""Entry point for gameoflife."""
# Command line argument parser
parser = ArgumentParser(prog='gameoflife',
description="Conway's Game of Life",
epilog='Suggestions and bug reports are greatly '
'apprecia... | 14,317 |
def onUrlFound(__url):
"""
Called by onPacketFound, if the packet contains a url.
"""
_url_ = resolveUrl(_url)
logger.info(_url_) | 14,318 |
def t3x1_y(y):
"""
Translation in y.
"""
return t3x1(0.0, y, 0.0) | 14,319 |
def write_primer_info(primers, prefix):
"""
Write tsv of primer metadata
"""
if primers is None:
primers = {}
outfile = prefix + '.tsv'
header = ['primer_set', 'amplicon_size_consensus',
'amplicon_size_avg', 'amplicon_size_sd',
'primer_id', 'primer_type', 'se... | 14,320 |
def perm_data_time(x, indices):
"""
Permute data matrix, i.e. exchange node ids,
so that binary unions form the clustering tree.
"""
if indices is None:
return x
N, M, Q = x.shape
Mnew = len(indices)
assert Mnew >= M
xnew = np.empty((N, Mnew, Q))
for i,j in enumerate(ind... | 14,321 |
def make_regress_files(regress_files, out_dir=None, regress_dir=None, clean=None):
"""
Copy ``regress_files`` from ``out_dir`` to ``regress_dir``, maintaining the
relative directory structure.
The ``clean`` parameter specifies a dict of rules for "cleaning" files so that
uninteresting diffs are eli... | 14,322 |
def test_auth_proj_no_token():
"""Token required by endpoint decorator"""
response = requests.get(dds_cli.DDSEndpoint.AUTH_PROJ)
assert response.status_code == 400
response_json = response.json()
assert response_json.get("message")
assert "JWT Token not found in HTTP header" in response_json.ge... | 14,323 |
def check_chromium() -> bool:
"""Check if chromium is placed at correct path."""
return chromium_executable().exists() | 14,324 |
def draw_lane(image, extracted_lane: Dict = {}, output_path: Optional[str] = None):
"""render extracted lane"""
# TODO: refactor separate concern moving out the saving to a file
lane_annotation_image = image.copy()
if "right" in extracted_lane:
lane_annotation_image = draw_lines(
lan... | 14,325 |
def plot_edges(lattice : Lattice,
labels : np.ndarray = 0,
color_scheme : np.ndarray = ['k','r','b'],
subset : np.ndarray = slice(None, None, None),
directions : np.ndarray = None,
ax = None,
arrow_h... | 14,326 |
def menu_items_api(restaurant_id):
"""Route handler for api endpoint retreiving menu items for a restaurant.
Args:
restaurant_id: An int representing the id of the restaurant whose menu
items are to be retrieved
Returns:
response: A json object containing all menu items for a g... | 14,327 |
def run(indata):
"""indata: event detection DataArray or DataSet"""
if isinstance(indata, xr.DataArray):
events = indata
else:
events = indata["Event_ID"]
logging.info("events array defined.")
# turn events into time x space by stacking lat & lon:
events_stacked = events.stack(z=(... | 14,328 |
def goto_location(session: Session, args: Any) -> None:
"""https://scalameta.org/metals/docs/integrations/new-editor/#goto-location"""
if isinstance(args, list) and args:
open_location(session.window, args[0]) | 14,329 |
def format_trace_id(trace_id: int) -> str:
"""Format the trace id according to b3 specification."""
return format(trace_id, "032x") | 14,330 |
def get_count_name(df):
"""Indicate if a person has a 'Name'
Parameters
----------
df : panda dataframe
Returns
-------
Categorical unique code
"""
# Feature that tells whether a passenger had a cabin on the Titanic
df['Words_Count'] = df['Name'].apply(lambda x: len(x.split... | 14,331 |
def register_action(request):
"""
从这个django.contrib/auth.models 库里倒入里User方法。(其实User是orm方式操作用户表的实例)
然后我们直接用User.objects.create_user方法生成一个用户,参数为用户名和密码。然后保存这个生成的用户 就是注册成功了
但是如果用户表中已存在这个用户名,那么,这个生成语句就会报错。所以我们用try来捕获这个异常,如果发送错误那就是“用户已经存在”,如实给用户返回这句话。如果没问题,那么就返回 注册成功
:param request:
:return:
"""
... | 14,332 |
async def run_blocking_io(func: Callable, *args, **kwargs) -> Any:
"""|coro|
Run some blocking function in an event loop.
If there is a running loop, ``'func'`` is executed in it.
Otherwise, a new loop is being created and closed at the end of the execution.
Example:
.. code-block:: python3... | 14,333 |
def parse_config(cfg, section):
""" parse config data structure, return data of required section """
def is_valid_section(s):
valid_sections = ["info", "project", "variables", "refdata"]
return s in valid_sections
cfg_data = None
if is_valid_section(section):
try:
c... | 14,334 |
def _predict_states(freqs):
"""Use frequencies to predict states across a chromosome.
Normalize so heterozygote blocks are assigned state 0 and homozygous
are assigned state 1.
"""
from hmmlearn import hmm
freqs = np.column_stack([np.array(freqs)])
model = hmm.GaussianHMM(2, covariance_type... | 14,335 |
def save_npz_dict(save_list=None, name='model.npz'):
"""Input parameters and the file name, save parameters as a dictionary into .npz file.
Use ``tl.files.load_and_assign_npz_dict()`` to restore.
Parameters
----------
save_list : list of parameters
A list of parameters (tensor) to be saved... | 14,336 |
def test_add_constant():
"""Test the add_constant function."""
a = rs.randn(10, 5)
wanted = np.column_stack((a, np.ones(10)))
got = stat.add_constant(a)
assert_array_equal(wanted, got) | 14,337 |
def tp(*args) -> np.ndarray:
"""Tensor product.
Recursively calls `np.tensordot(a, b, 0)` for argument list
`args = [a0, a1, a2, ...]`, yielding, e.g.,
tp(a0, a1, a2) = tp(tp(a0, a1), a2)
Parameters
----------
args : sequence
Sequence of tensors
Returns
-------
np.... | 14,338 |
def main():
"""Run a simple test
"""
version = get_version()
if version:
print('Found tesseract OCR version %s' % version)
print('Available languages:', get_list_of_langs())
else:
print('Tesseract is not available') | 14,339 |
def delete():
"""Remove the current user's avatar image."""
user = _get_current_user_or_404()
try:
avatar_service.remove_avatar_image(user.id)
except ValueError:
# No avatar selected.
# But that's ok, deletions should be idempotent.
flash_notice(gettext('No avatar image ... | 14,340 |
def aws_aws_page():
"""main endpoint"""
form = GenericFormTemplate()
return render_template(
'aws_page.html',
form=form,
text=util.get_text(module_path(), config.language),
options=g.user.get_options(),
) | 14,341 |
def popen_program(cmd, minimized=False, pipe=False, shell=False, **kwargs):
"""Run program and return a subprocess.Popen object."""
LOG.debug(
'cmd: %s, minimized: %s, pipe: %s, shell: %s',
cmd, minimized, pipe, shell,
)
LOG.debug('kwargs: %s', kwargs)
cmd_kwargs = build_cmd_kwargs(
cmd,
min... | 14,342 |
def precompute(instr):
"""
Args:
instr:
Returns:
"""
qecc = instr.qecc
if qecc.name == '4.4.4.4 Surface Code' and qecc.circuit_compiler.name == 'Check2Circuits':
precomputed_data = code_surface4444(instr)
elif qecc.name == 'Medial 4.4.4.4 Surface Code' and qecc.circuit_... | 14,343 |
def remove_url(txt):
"""Replace URLs found in a text string with nothing
(i.e. it will remove the URL from the string).
Parameters
----------
txt : string
A text string that you want to parse and remove urls.
Returns
-------
The same txt string with url's removed.
... | 14,344 |
def use_database(fn):
"""
Ensure that the correct database context is used for the wrapped function.
"""
@wraps(fn)
def inner(self, *args, **kwargs):
with self.database.bind_ctx(self.models):
return fn(self, *args, **kwargs)
return inner | 14,345 |
def write_csv(obj, filename):
"""
Convert dictionary items to a CSV file the dictionary format:
::
{'result category 1':
[
# 1st line of results
{'header 1' : value_xxx,
'header 2' : value_yyy},
... | 14,346 |
def format_help(title, lines, os_file):
"""Nicely print section of lines.
:param title: help title, if exist
:param lines: strings to format
:param os_file: open filehandle for output of RST file
"""
close_entry = False
if title:
os_file.write("**" + title + ":**" + "\n\n")
co... | 14,347 |
def getImapMailboxEmail(server, user, password, index, path="INBOX", searchSpec=None):
"""
imap_headers(server, user, password, index, path="INBOX", searchSpec=None)
Load specified email header from an imap server. index starts from 0.
Example
WITH RECURSIVE
... | 14,348 |
def trace(msg, html=False, attachment=None, launch_log=False):
"""Write the message to the log file using the ``TRACE`` level."""
write(msg, "TRACE", html, attachment, launch_log) | 14,349 |
def test_lj2atomen():
"""Test om de potentiaal tussen 2 atomen te berekenen"""
afstand = 1.5
pot = 4*((1/afstand)**12 - (1/afstand)**6)
potf = f90.ljpot2atomen(afstand)
assert round(pot, 7) == round(potf, 7) | 14,350 |
def create_storage(uri=None):
"""factory to create storage based on `uri`, the ANYVAR_STORAGE_URI
environment value, or in-memory storage.
The URI format is one of the following:
* in-memory dictionary:
`memory:`
Remaining URI elements ignored, if provided
* Python shelf (dbm) persistence... | 14,351 |
def test_python_module_ctia_positive_malware(
module_headers, module_tool_client):
"""Perform testing for malware entity of custom threat intelligence python
module
ID: CCTRI-164-056ef37c-171d-4b1d-ae3d-4601aaa465bb
Steps:
1. Send POST request to create new malware entity using custom... | 14,352 |
def nmatches_mem(txt, pat, t, p, mem):
"""Find number of matches with recursion + memoization using a dictionary
(this solution will also crash when recursion limit is reached)
nmatches_mem(text, pattern, len(text), len(pattern), {})
"""
if (t,p) in mem:
return mem[t, p]
... | 14,353 |
def get_size_stats(args):
"""
Calculate size for each of the iterator.
It recusively iterate though a directory to find a specific extension file and report their size in preferred format.
"""
lang_size_dict = {}
for (dirpath, dirnames, filenames) in os.walk(args.data_folder_path):
for f... | 14,354 |
def main():
""" main with an infinite loop"""
username, password, address = get_conf()
checker = Checker(username, password, address)
while True:
checker.store_next_events()
checker.print_next_events()
checker.notify_if_in_less(hours=20)
time.sleep(60 * DEFAULT_CHECK_PERI... | 14,355 |
def data_get():
"""
Get shared data from this server's local store.
"""
consistency = request.json["consistency"]
name = request.json["name"]
field = request.json["field"]
value = ""
error = "ok"
if consistency == "strict":
store = globalvars.get_data_store(globalvars.STRICT_... | 14,356 |
def pad_sequences(sequences, maxlen=None, value=0):
"""
pad sequences (num_samples, num_timesteps) to same length
"""
if maxlen is None:
maxlen = max(len(x) for x in sequences)
outputs = []
for x in sequences:
x = x[:maxlen]
pad_range = (0, maxlen - len(x))
x = n... | 14,357 |
def test_ct():
"""Test if Ct calculation work"""
sample_time = np.loadtxt('ref.txt', usecols=[0])
reference_ct = np.loadtxt('ref.txt', usecols=[1])
instance = trial.xixihaha.Kubo(delta=1 , tau=1)
calculate_ct = instance.calculate_Ct(time=sample_time)[:,1]
assert np.allclose(calculate_ct ,... | 14,358 |
def test_filter_by_patron(app, patron_pid, qs, should_raise):
"""Test the function filter_by_patron."""
search = RecordsSearch()
if should_raise:
with pytest.raises(UnauthorizedSearchError):
_filter_by_patron(patron_pid, search, qs)
else:
_search, _qs = _filter_by_patron(patr... | 14,359 |
def reset_password():
"""
Three main states of this controller
1. by default just show the email field
2. in a second step, also show the field for the code and new password
3. in a third step, if code is correct, redirect to login
:return: template to be rendered
"""
... | 14,360 |
def download(request, path):
"""
Downloads a file.
This is inspired by django.views.static.serve.
?disposition={attachment, inline}
"""
decoded_path = urllib.unquote(path)
if path != decoded_path:
path = decoded_path
if not SHOW_DOWNLOAD_BUTTON.get():
return serve_403_erro... | 14,361 |
def spacegroup_a_to_spacegroup_b(atoms, spgroup_a, spgroup_b, target_b_contribution, create_replicas_by,
min_nb_atoms=None, target_nb_atoms=None, max_diff_nb_atoms=None, radius=None,
target_replicas=None, max_rel_error=0.01, **kwargs):
"""Remove cent... | 14,362 |
def empty_surface(fill_color, size=None, flags=0):
"""Returns an empty surface filled with fill_color.
:param fill_color: color to fill the surface with
:type fill_color: pygame.Color
:param size: the size of the new surface, if None its created
to be the same size as the screen
:type size... | 14,363 |
def getNetAddress(ip, netmask):
"""
Get the netaddress from an host ip and the netmask.
:param ip: Hosts IP address
:type ip: str
:param netmask: Netmask of the network
:type netmask:
:returns: Address of the network calculated using hostIP and netmask
:rtype: str
"""
ret... | 14,364 |
def wait_for_mysqld(config, mysqld):
"""Wait for new mysql instance to come online"""
client = connect(config, PassiveMySQLClient)
LOG.debug("connect via client %r", config['socket'])
while mysqld.process.poll() is None:
try:
client.connect()
client.ping()
LOG... | 14,365 |
def begin_operation(name: str) -> dict:
"""
Gets the stats for the current operation.
Parameters
----------
name: str
name of the operation
Returns
-------
dict
dictionary with the operation stats
Examples
--------
>>> from pymove.utils.mem import begin_oper... | 14,366 |
def create_or_load_vocabulary(data_path,training_data_path,vocab_size,test_mode=False,tokenize_style='word',fine_tuning_stage=False,model_name=None):
"""
create or load vocabulary and label using training data.
process as: load from cache if exist; load data, count and get vocabularies and labels, save to f... | 14,367 |
def diff(
macros: List[str],
citations: List[str],
styles: Optional[str],
) -> Iterable[AtomicIterable]:
"""Display changes in local template files."""
raise NotImplementedError | 14,368 |
def balance_intent_data(df):
"""Balance the data for intent detection task
Args:
df (pandas.DataFrame): data to be balance, should contain "Core Relations" column
Returns:
pandas.DataFrame: balanced data
"""
relation_counter = build_counter(df, "Core Relations")
# augment each... | 14,369 |
def ddm_iadd(a, b):
"""a += b"""
for ai, bi in zip(a, b):
for j, bij in enumerate(bi):
ai[j] += bij | 14,370 |
def plot_with_bbox(image, fv, size_correction = None):
"""
Graph the bounding boxes on an image
Take the feature vectors, corresponding to the
element class and parameters of the bounding box
and plot it
Parameters
----------
image : np.array
... | 14,371 |
def npareamajority(values, areaclass):
"""
numpy area majority procedure
:param values:
:param areaclass:
:return:
"""
uni,ind = np.unique(areaclass,return_inverse=True)
return np.array([np.argmax(np.bincount(values[areaclass == group])) for group in uni])[ind] | 14,372 |
def calcReward(eventPos, carPos, closeReward, cancelPenalty, openedPenalty):
"""
this function calculates the reward that will be achieved assuming event is picked up
:param eventPos: position of events
:param carPos: position of cars
:param closeReward: reward if event is closed
:param cancelPe... | 14,373 |
def b64encode(s: Any, altchars: Any = None) -> bytes:
"""Encode bytes using the standard Base64 alphabet.
Argument ``s`` is a :term:`bytes-like object` to encode.
Optional ``altchars`` must be a byte string of length 2 which specifies
an alternative alphabet for the '+' and '/' characters. This allow... | 14,374 |
def select_programs(args, filter_paused=True, force=False):
"""
Return a list of selected programs from command line arguments
"""
if not (args.all ^ bool(args.names)):
if args.all:
log.error("You may not specify a program name when you use the -a/--all option (See -h/--help for mor... | 14,375 |
def test_mat_lu_det():
"""Test that the mat_lu() function returns correctly a matrix determinant"""
my_mats = [
[[2, 4, 6, 8], [1, 9, 2, 0], [7, 1, 2, 3], [8, 11, 3, 2]],
[[3, 6, 3], [8, 2, 1], [5, 3, 2]],
[[4, 1], [3, 2]],
[[0, 3, 2, 1], [0, 0, 3, 6], [0, 0, 0, 18], [0, 0, 0, 12]],
[[9, 2, ... | 14,376 |
def three_comp_two_objective_functions(obj_vars, hz: int,
ttes: SimpleTTEMeasures,
recovery_measures: SimpleRecMeasures):
"""
Two objective functions for recovery and expenditure error
that get all required params as arguments
... | 14,377 |
def scale(data, new_min, new_max):
"""Scales a normalised data series
:param data: The norrmalised data series to be scaled
:type data: List of numeric values
:param new_min: The minimum value of the scaled data series
:type new_min: numeric
:param new_max: The new maxim... | 14,378 |
def default_config() -> ClientConfig:
"""
:return: Default configuration for the experiment
"""
simulation_config = SimulationConfig(render=False, sleep=0.8, video=True, log_frequency=1,
video_fps=5, video_dir=default_output_dir() + "/videos", num_episodes=1000,
... | 14,379 |
def get_same_padding(kernel_size: int, stride: int, dilation: int) -> int:
"""Calculates the padding size to obtain same padding.
Same padding means that the output will have the
shape input_shape / stride. That means, for
stride = 1 the output shape is the same as the input,
and str... | 14,380 |
def move_child_position(context, request):
""" Move the child from one position to another.
:param context: "Container" node in which the child changes its position.
:type context: :class:kotti.resources.Node or descendant
:param request: Current request (of method POST). Must contain either
... | 14,381 |
def test_hawk_tail():
"""Test module hawk_tail.py by downloading
hawk_tail.csv and testing shape of
extracted data has 838 rows and 2 columns
"""
test_path = tempfile.mkdtemp()
x_train, metadata = hawk_tail(test_path)
try:
assert x_train.shape == (838, 2)
except:
shutil.rmtree(test_path)
r... | 14,382 |
def get_current_version(package: str) -> str:
"""
Query PyPi index to find latest version of package
:param package: str - name of pacahe
:return: str - version if available
"""
url = f'{PYPI_BASE_URL}/pypi/{package}/json'
headers = {
'Content-Type': 'application/json'
}
res... | 14,383 |
def get_model_path(model_name):
"""
Returns path to the bird species classification model of the given name.
Parameters
----------
model_name : str
Name of classifier model. Should be in format
``<model id>_<taxonomy version>-<taxonomy md5sum>``.
*v0.3.1 UPDATE: model names... | 14,384 |
def mconcat(xs : [a]) -> a:
"""
mconcat :: (Monoid m) => [m] -> m
Fold a list using the monoid.
"""
return Monoid[xs[0]].mconcat(xs) | 14,385 |
def maybe_zero_out_padding(inputs, kernel_size, nonpadding_mask):
"""If necessary, zero out inputs to a conv for padding positions.
Args:
inputs: a Tensor with shape [batch, length, ...]
kernel_size: an integer or pair of integers
nonpadding_mask: a Tensor with shape [batch, length]
Returns:
Ten... | 14,386 |
def display_json(value):
"""
Display input JSON as a code
"""
if value is None:
return display_for_value(value)
if isinstance(value, str):
value = json.loads(value)
return display_code(json.dumps(value, indent=2, ensure_ascii=False, cls=DjangoJSONEncoder)) | 14,387 |
def get_rgba_from_color(rgba):
"""Return typle of R, G, B, A components from given color.
Arguments:
rgba - color
"""
r = (rgba & 0xFF000000) >> 24
g = (rgba & 0x00FF0000) >> 16
b = (rgba & 0x0000FF00) >> 8
a = (rgba & 0x000000FF)
return r, g, b, a | 14,388 |
def beauty_factor(G):
"""Return the "beauty factor" of an arbitrary graph, the minimum distance
between a vertex and a non-incident edge."""
V, E = G[0], G[1]
dists = []
for (i, u) in enumerate(V):
for (j, k) in E:
if i == j or i == k:
continue
v, w = ... | 14,389 |
def simulationTwoDrugsVirusPopulations():
"""
Run simulations and plot graphs examining the relationship between
administration of multiple drugs and patient outcome.
Plots of total and drug-resistant viruses vs. time are made for a
simulation with a 300 time step delay between administering the 2... | 14,390 |
def line_plane_cost(line, plane):
"""
A cost function for a line and a plane
"""
P = normalised((line|plane)*I5)
L = normalised(meet(P, plane))
return line_cost_function(L, line) | 14,391 |
def run_covid_update(update_name: str) -> None:
"""Enacts a scheduled update and either repeats or deletes it.
Updates COVID data for the area specified in config.json, and
schedules a new update if the update repeats, otherwise the
update is removed.
Args:
update_name: The identif... | 14,392 |
def register_document_to_documentsbundle(bundle_id, payload):
"""
Relaciona documento com seu fascículo(DocumentsBundle).
Utiliza a endpoint do Kernel /bundles/{{ DUNDLE_ID }}
"""
try:
response = hooks.kernel_connect(
"/bundles/%s/documents" % bundle_id, "PUT", payload)... | 14,393 |
def test_alt():
"""Setup input for running Alternate Live Load.
Inputs the Alternate loading with the following inputs:
span_lengths = [5.0,6.0,7.0,8.0,9.0,10.0,11.0,12.0,13.0,14.0,16.0,
18.0,20.0,24.0,28.0,32.0,36.0,40.0,45.0,50.0,55.0,
60.0,70.0,80.0,90.0,100.0,120.0,140.0,... | 14,394 |
def let_it_roll(path):
"""
takes a list of image files and returns a video
"""
pass | 14,395 |
def test_save_unregistered_email(mock_email_address_qs):
"""
If the provided email address doesn't exist in the system, saving
should do nothing.
"""
address = "test@example.com"
mock_email_address_qs.get.side_effect = models.EmailAddress.DoesNotExist
data = {"email": address}
serialize... | 14,396 |
def force_full_index(dataframe: pd.DataFrame, resampling_step: int = None,
resampling_unit: str = "min", timestamp_start: int = None,
timestamp_end: int = None) -> pd.DataFrame:
""" forces a full index. Missing index will be replaced by Nan.
Note: resampling should... | 14,397 |
def legislature_to_number(leg):
"""
Takes a full session and splits it down to the values for
FormatDocument.asp.
session = '49th-1st-regular'
legislature_to_number(session) --> '49Leg/1s'
"""
l = leg.lower().split('-')
return '%sLeg/%s%s' % (l[0][0:2], l[1][0], l[2][0]) | 14,398 |
def pin_tags(pb, config_file):
"""
Tag every item in pinboard with the name of it's
originating website
"""
all_bookmarks = pb.posts.all()
# Boolean to determine wheter to do additional filtering
# Only run if filter config file exists
domain_map = None
if config_file and os.path.is... | 14,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.