content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_new_attending(username_id, email, phone):
"""Creates a dictionary for a new attending physician
Every time the user wants to add a new attending physician
to the attending physician database, this function
must be called. This function reads in from the user the
physician’s user name, their... | 63,400 |
def getCaptureArea():
# Fix not aborting issue here.
"""
Get area to work with.
"""
p1 = Pos()
p2 = Pos()
kill_key = "f2"
def getPos(p):
nonlocal kill_key
while (not keyboard.is_pressed(kill_key)) and (not ABORT_SIGNALED):
# fix loop here
QSlee... | 63,401 |
def _check1d(from_bins, val, to_bins, target):
"""
Test 1D rebinning *from_bins* => *to_bins* of counts *val* => *target*.
The expected *target* must be precomputed in order to test that the right
value is produced.
Tests all combinations of increasing/decreasing source/target bin edges.
Yiel... | 63,402 |
def _validate_input(dataset: np.ndarray, explain_instance: Callable,
sample_size: int, explanations_number: int) -> bool:
"""
Validates input for submodular pick.
For the input parameters description, warnings and exceptions please see
the documentation of the :func:`fatf.transparen... | 63,403 |
def wcmp(a,b):
""" A strict ordering whisker segments in a frame """
return cmp( a.y[0], b.y[0] ) | 63,404 |
def plot_timeseries(df, **kwargs):
"""Plot time series of sales.
Time series plot of Mean Sales of Beverages per Region.
Parameters
----------
df : DataFrame
**kwargs : dict, optional
Keyword arguments for sales region and beverage type.
Returns
-------
s... | 63,405 |
def render_cit_ref(tpl: str, parts: List[str], data: Dict[str, str]) -> str:
"""
>>> render_cit_ref("cit_réf", ["Dictionnaire quelconque", "2007"], defaultdict(str))
'<i>Dictionnaire quelconque</i>, 2007'
>>> render_cit_ref("cit_réf", [], defaultdict(str,{"titre":"Dictionnaire quelconque", "date":"2007"... | 63,406 |
def bandpass(samples, sample_rate):
"""Applies a 20-30khz bandpass FIR filter"""
# 25-40KHz is the range of the pinger for the roboboat competition
fir = scipy.signal.firwin(
128, [19e3 / (sample_rate / 2), 41e3 / (sample_rate / 2)],
window='hann',
pass_zero=False)
return scipy.s... | 63,407 |
def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):
"""Lists all the blobs in the bucket that begin with the prefix.
This can be used to list all blobs in a "folder", e.g. "public/".
The delimiter argument can be used to restrict the results to only the
"files" in the given "folder". With... | 63,408 |
def utc_to_local_tt(y, m, d, hrs_utc):
"""Converts from a UTC time to a local time.
y,m,d: The year, month, day for which the conversion is desired.
hrs_tc: Floating point number with the number of hours since midnight in UTC.
Returns: A timetuple with the local time.
>>> os.envi... | 63,409 |
def get_model_list(class_list):
"""
Receives a list of strings with app_name.model_name format
and turns them into classes. If an item is already a class
it ignores it.
"""
for idx, item in enumerate(class_list):
if isinstance(item, six.string_types):
model_class = apps.get_m... | 63,410 |
def test_requests_bs4(monkeypatch):
"""test the requests and bs4 Lua interfaces"""
def get(url):
return {
'https://test.invalid/plain.txt':
Dummy(headers={'Content-Type': 'text/plain'},
text='<span>This</span> is <b>plain</b> text'),
'http://... | 63,411 |
def trim():
"""Remove transparent area around image."""
with Image(filename=asset('trimtest.png')) as img:
oldx, oldy = img.size
img.trim()
newx, newy = img.size
assert newx < oldx
assert newy < oldy
with Image(filename=asset('trim-color-test.png')) as img:
as... | 63,412 |
def feature_max_q(q1, q2, q3, q4):
"""
Computes the max values of each signal for each quarter-window, plus the
paired differences of max values of each signal for the quarter-windows,
i.e., feature_max(q1), feature_max(q2), feature_max(q3), feature_max(q4),
(feature_max(q1) - feature_max(q2)), (feature_max(q1) ... | 63,413 |
def notify_complete(job_id):
"""Notify trigger that job is complete."""
_LOGGER.info("Calling trigger to stop container")
uri = (
"https://myfunctionbilling.azurewebsites.net/api/DockerHTTPTrigger"
"?code=sdYZl5NvaT/N1Lo3HRlLsBD5iig2CJE6IR2csvYi5A3PgjzCTpNNLw=="
)
resp = requests.g... | 63,414 |
def get_heading(tank1,tank2):
"""returns heading of the tank in degrees, assuming tank1, tank2 are dict"""
x1,y1 = tank1["x"], tank2["y"]
x2,y2 = tank2["x"], tank2["y"]
heading = float(math.atan2((y2-y1)/(x2-x1))) #returns heading in radians
heading = float(math.degrees(heading))
heading = (he... | 63,415 |
def _scan_checkpoint_directory(checkpoint_dir: str) -> List[Checkpoint]:
"""
Construct checkpoint metadata directly from a directory.
State files are sometimes out of sync with directory contents. Insert
additional orphaned checkpoint files and prune missing files. To be
conservative, we prefer dat... | 63,416 |
def async_wrap(func: Callable):
"""Wrap a synchronous running function to make it run asynchronous."""
async def run(*args, loop=None, executor=None, **kwargs) -> Callable:
"""Run sync function async."""
if loop is None:
loop = asyncio.get_event_loop()
pfunc = partial(func, ... | 63,417 |
def is_gs_line(line):
"""Returns True if line is a GS line"""
return line.startswith('#=GS') | 63,418 |
def replace_lookups(pre: str, partition: str, active: str) -> JNDIParts:
"""Replace Log4J lookups.
See https://logging.apache.org/log4j/2.x/manual/lookups.html and
https://logging.apache.org/log4j/2.x/manual/configuration.html#PropertySubstitution
"""
jndi_parts = JNDIParts(
original=f"{pre... | 63,419 |
def init_weights(args, model) -> object:
"""
Initializes the neural network weights from known networks such as COCO, imagenet or from the last training.
Parameters
----------
:param args:
(object) Inputs the parameters passed to the command-line script as input --> weights
:param model... | 63,420 |
def bar(n):
"""Test helper for foo."""
return foo(n-1) | 63,421 |
def create_datapack_preview(result=None, task_uid=None, stage_dir=None, *args, **kwargs):
"""
Attempts to add a MapImageSnapshot (Preview Image) to a provider task.
"""
result = result or {}
try:
from eventkit_cloud.utils.image_snapshot import get_wmts_snapshot_image, fit_to_area
ch... | 63,422 |
def read_cd_files(prefix: Path, fname: str) -> dict:
"""
result[name] = path-to-the-file
name: e.g., 08-1413.jpg
pato-to-the-file: e.g., /cifs/toor/work/2011/cyclid data/./CD9/2008-06-19/08-1413.jpg
"""
result = {}
with open(fname) as f:
for line in f:
line = line.strip()... | 63,423 |
def _items(mappingorseq):
"""Wrapper for efficient iteration over mappings represented by dicts
or sequences::
>>> for k, v in _items((i, i*i) for i in xrange(5)):
... assert k*k == v
>>> for k, v in _items(dict((i, i*i) for i in xrange(5))):
... assert k*k == v
"""
... | 63,424 |
def train(create_tensor_dict_fn, create_model_fn, train_config, master, task,
num_clones, worker_replicas, clone_on_cpu, ps_tasks, worker_job_name,
is_chief, train_dir):
"""Training function for detection models.
Args:
create_tensor_dict_fn: a function to create a tensor input dictionary.
... | 63,425 |
def invert(K, neig=0, tol=1e-10):
"""Inverts a positive-definite matrix A using either an eigendecomposition or
a Cholesky decomposition, depending on the rapidness of decay of eigenvalues"""
if (neig <= 0 or neig > 0.05*K.shape[0]):
try:
return invert_cholesky(np.linalg.cholesky(K))
... | 63,426 |
def apply_capping(
df: pd.DataFrame,
metric: str,
sd_threshold: int = 5,
method: Union[str, CappingMethod] = CappingMethod.STANDARD,
metric_raw: str = None,
) -> pd.Series:
"""Calculates metrics capped at threshold of given SDs from mean (upper bound capping only). Intended for non-negative metr... | 63,427 |
def list_user_emails():
""" List user names and emails
Returns:
A JsonResponse that contains a list of user information (ID, name, and email)
"""
sess = GlobalDB.db().session
users = sess.query(User)
if not g.user.website_admin:
relevant_cgacs = [aff.cgac_id for aff in g... | 63,428 |
async def who(event: NewMessage.Event):
"""For .user command, get info about a user."""
if event.fwd_from:
return
args, user = parse_arguments(
event.pattern_match.group(1),
["id", "forward", "general", "bot", "misc", "all", "mention"],
)
args["forward"] = args.get("forward... | 63,429 |
def execute_task(testcase_id, job_type):
"""Run regression task and handle potential errors."""
try:
find_regression_range(testcase_id, job_type)
except errors.BuildSetupError as error:
# If we failed to setup a build, it is likely a bot error. We can retry
# the task in this case.
testcase = data... | 63,430 |
def member(ctx):
"""CRM configuration for nexthop group member resource"""
ctx.obj["crm"].res_type = 'nexthop_group_member' | 63,431 |
def calc_foo(scen,run,v):
"""Calculates something using CDO.
Input variables:
scen,run,v: strings indicating the scenario,
ensemble member run, and the variable name.
These variables are used to form the netcdf file names
that are processed with cdo.
"""
app="foo" #... | 63,432 |
def set_elixier_item_fach_sachgebiet(item, fach_sachgebiet):
""" .. aendert den Status des Elixier-Beitrags """
#id = item.id_local
item.fach_sachgebiet = fach_sachgebiet
item.save() | 63,433 |
def create_subnetList(topo, num):
"""
Create the subnet list of the certain Pod.
"""
subnetList = []
remainder = num % (topo.pod/2)
if topo.pod == 4:
if remainder == 0:
subnetList = [num-1, num]
elif remainder == 1:
subnetList = [num, num+1]
el... | 63,434 |
def phimat(phi):
"""
Build a Busing & Levy PHI matrix. Input is in radians
"""
result = np.zeros((3, 3,), dtype='float64')
result[0][0] = cos(phi)
result[0][1] = sin(phi)
result[1][0] = -sin(phi)
result[1][1] = cos(phi)
result[2][2] = 1.
return result | 63,435 |
def _get_cube_list_for_table(cell_data, row_labels, col_labels, col_units):
"""Create :class:`iris.cube.CubeList` representing a table."""
aux_coord = iris.coords.AuxCoord(row_labels, long_name='dataset')
cubes = iris.cube.CubeList()
for (idx, label) in enumerate(col_labels):
if label in ('ECS',... | 63,436 |
def _generate_spaxel_list(spectrum):
"""
Generates a list wuth tuples, each one addressing the (x,y)
coordinates of a spaxel in a 3-D spectrum cube.
Parameters
----------
spectrum : :class:`specutils.spectrum.Spectrum1D`
The spectrum that stores the cube in its 'flux' attribute.
Re... | 63,437 |
def __calc_info(im, method, **kwargs):
"""
Calculate the strict-orderable version of an image. Returns a floating-point 'images' or images
with an extra dimension giving a 'tuple' of data for each pixel.
If the method does not support GPU arrays but im is a GPU array, it will be copied off of the
G... | 63,438 |
def drop_all():
"""
Method for droping all the database tables
"""
cur.execute("DROP TABLE IF EXISTS questions CASCADE")
cur.execute("DROP TABLE IF EXISTS users CASCADE")
cur.execute("DROP TABLE IF EXISTS comments CASCADE")
cur.execute("DROP TABLE IF EXISTS meetups CASCADE")
cur.execute(... | 63,439 |
def setup():
"""Process command-line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-l",
"--length",
default=64,
type=int,
help="# of random characters for password (default 64)",
)
parser.add_argument(
"-e",
... | 63,440 |
def get_args():
"""
Read arguments from the command line and check they are valid.
"""
logger = logging.getLogger("stats.args")
parser = argparse.ArgumentParser(
description="Extract alignment statistics from a SAM/BAM file")
parser.add_argument("inputs",
metava... | 63,441 |
def get_frame_rate_list(fmt):
"""Get the list of supported frame rates for a video format.
This function works arround an issue with older versions of GI that does not
support the GstValueList type"""
try:
rates = fmt.get_value("framerate")
except TypeError:
import re
# Worka... | 63,442 |
def cosine_loss(X, mu_tilde, pi_tilde, alpha):
"""
Computes the Cosine loss.
Arguments:
X: array-like, shape=(batch_size, n_features)
Input batch matrix.
mu_tilde: array-like, shape=(batch_size, n_features)
Matrix in which each row represents the assigned mean vector.... | 63,443 |
def assert_unit_dual_quaternion(dq, *args, **kwargs):
"""Raise an assertion if the dual quaternion does not have unit norm.
See numpy.testing.assert_array_almost_equal for a more detailed
documentation of the other parameters.
"""
real = dq[:4]
dual = dq[4:]
real_norm = np.linalg.norm(real... | 63,444 |
def construct_loader(x, y, batch_size, shuffle=True):
"""Construct a data loader for the provided data.
Args:
x (list): A list of molecule features.
y (list): A list of the corresponding labels.
batch_size (int): The batch size.
shuffle (bool): If True the data will be loaded in... | 63,445 |
def cpp_texlist(listoflines):
"""function that parses a .tex file from https://github.com/cplusplus/draft.git
and extracts all section headings as well as all impldef statements into a flat list
The return value contains tuples,
tuple[0] ... line number (starting from 1) that matched the item
tuple... | 63,446 |
def show_index():
"""Display / route."""
context = {}
return flask.render_template("index.html", **context) | 63,447 |
def test_quantile_ok():
"""Test if quantile check works."""
X, y = np.zeros(2)
regressor = QuantileRegression(quantile=2.0)
with pytest.raises(ValueError):
regressor.fit(X, y) | 63,448 |
def create_header():
"""page header"""
header = html.Header(
html.Nav(
[
html.Div(
[html.Div([app.title], className="navbar-brand navbar-left")],
className="container",
)
],
className="navbar navb... | 63,449 |
def _set_obs_rep(adata, val, *, use_raw=False, layer=None, obsm=None, obsp=None):
"""
Set value for observation rep.
"""
is_layer = layer is not None
is_raw = use_raw is not False
is_obsm = obsm is not None
is_obsp = obsp is not None
choices_made = sum((is_layer, is_raw, is_obsm, is_obsp... | 63,450 |
def recalculate_workflow_tags(db, sample_id: str):
"""
Recalculate and apply workflow tags (eg. "ip", True) for a given sample.
:param db: the application database client
:param sample_id: the id of the sample to recalculate tags for
"""
analyses = db.analyses.find({"sample.id": sample_id}, ["... | 63,451 |
def update_regex_extractor(regex_extractor_id: int):
"""更新"""
data: dict = request.get_json()
regex_extractor = RegexExtractor.query.filter(
RegexExtractor.regex_extractor_id == regex_extractor_id
).first()
if not regex_extractor:
return dbu.inner_error("该不存在或已被删除")
dbu.update... | 63,452 |
def kill_jobs(q):
"""kill all the jobs in the queue."""
while not q.empty():
job_id = q.get()
cmd = "kill %s" % (job_id)
os.system(cmd) | 63,453 |
def web_supervisor_install():
""" Install Supervisor - Ex: (cmd)"""
requirements = '%s' % ' '.join([
'supervisor',
])
# install requirements
sudo('apt -y install {}'.format(requirements))
web_supervisor_bootstrap()
sys_etc_git_commit('Installed Supervisor') | 63,454 |
def count(_id):
"""Update a group """
if request.method == 'GET':
try:
group = get_group(_id)
if not group:
return jsonify({'code': 400, 'msg': 'can not found group by id [{0}]'.format(_id)})
else:
result = count_group(_id)
... | 63,455 |
def email_extractor(path):
""" Extracts email addresses from Enron E-mail files """
parser = email.parser.Parser()
outbox_re = [re.compile(r) for r in ['sent_items$', 'sent$', 'sent_mail$']]
for root, _, files in os.walk(path):
if not any(re.search(root) for re in outbox_re):
continu... | 63,456 |
def create_network_from_yml(directory_name):
"""
Creates a Network object form a yaml file.
"""
params_input = load_parameters(directory_name)
params = fill_out_dictionary(params_input)
for clss in params['arrival_distributions']:
dists = []
for dist in params['arrival_distributi... | 63,457 |
def gmail_filters():
"""Returns GMail labels object exposing labels API.
Args: None
Returns:
GMail labels object.
"""
return __gmail_v1__().settings().filters() | 63,458 |
def test_cereal_solid_download_cereal():
"""Example of a unit-test of a simple solid."""
res = execute_solid(download_cereals)
assert res.success
assert len(res.output_value()) == 77 | 63,459 |
def transition_matrix(embeddings, **kwargs):
"""
Calls similarity matrix. Builds a probabilistic transition matrix
from word embeddings.
"""
#ipdb.set_trace()
## Get Similarity matrix
L = similarity_matrix(embeddings, **kwargs)
Dinv = np.diag([1. / np.sqrt(L[i].sum()) if L[i].sum() ... | 63,460 |
def domain_nameservers_should_be_exactly(value: List[str] = None,
ns: List[str] = None) -> bool:
"""
Check the given nameservers are exactly the domain's nameservers.
"""
return set(value) == set(ns) | 63,461 |
def get_user_pagination(page=1, per_page=10, *args, **kwargs):
"""
获取列表(分页)
Usage:
items: 信息列表
has_next: 如果本页之后还有超过一个分页,则返回True
has_prev: 如果本页之前还有超过一个分页,则返回True
next_num: 返回下一页的页码
prev_num: 返回上一页的页码
iter_pages(): 页码列表
iter_pages(left_edge=2, left_curre... | 63,462 |
def convert_null_to_zero(event, field_or_field_list):
""" Converts the value in a field or field list from None to 0
:param event: a dict with the event
:param field_or_field_list: A single field or list of fields to convert to 0 if null
:return: the updated event
Examples:
.. code-block:: py... | 63,463 |
def test_my_func():
"""my_func returns expected result"""
result = my_func("one", "two")
assert result == "one:two" | 63,464 |
def is_mul(a):
"""Return `True` if `a` is an expression of the form b * c.
>>> x, y = Ints('x y')
>>> is_mul(x * y)
True
>>> is_mul(x - y)
False
"""
return is_app_of(a, Kind.MULT) | 63,465 |
def procura_frase_lacunas_respostas_dicionario():
"""Esta função retorna a frase, as lacunas e as respostas
correspondentes para o nível selecionado pelo usuário.
"""
frase = frases_lacunas_respostas_por_dificuldade[nivel]['frase']
lacunas = frases_lacunas_respostas_por_dificuldade[nivel]['lacunas']... | 63,466 |
def refresh():
"""Pull fresh data from Open AQ and replace existing data."""
DB.drop_all()
DB.create_all()
api = openaq.OpenAQ()
status, body = api.measurements(city='Atlantic City', country='US', parameter='pm25')
results = body['results']
for ii in range(len(results)):
db_record = ... | 63,467 |
def index():
"""Renders home page."""
return render_template('index.html') | 63,468 |
def save_tree_as_dict(clf, feature_names, label_names, save_path, node_index=0):
"""
Wrapper for rules, that includes saving to a path and
more descriptive argument names
"""
tree_dict = rules(clf, feature_names, label_names, node_index)
# save the dict as a text file
with open(save_path, ... | 63,469 |
def get_file_parts(filename, prefix="name"):
"""Assign a name to various parts of a file.
Parameters
----------
filename : str
A file name (no leading path is permitted).
prefix : str
Prefix to prepend to the key names.
Returns
-------
A dict mapping each part to a valu... | 63,470 |
def test_relay_projectconfig_cache_full_config(
call_endpoint, default_project, projectconfig_cache_set, task_runner
):
"""
When a relay fetches a full config, that config should end up in Redis.
"""
with task_runner():
result, status_code = call_endpoint(full_config=True)
assert st... | 63,471 |
def obtener_cantidad_dias_estancia_media_estimados_en_ciudad_en_rango_anios_mensualmente(Ciudad, AnioInicio, AnioFin):
"""
Dado una ciudad y un año obtiene los dias de estancia media estimados en dicha ciudad en ese rango de años dividido por meses
Dado una ciudad y un año obtiene los dias de estancia media... | 63,472 |
def setBit(int_type, offset, value):
"""following 2 functions derived from https://wiki.python.org/moin/BitManipulation, this one sets a specific bit"""
if value == 1:
mask = 1 << offset
return(int_type | mask)
if value == 0:
mask = ~(1 << offset)
return(int_type & mask) | 63,473 |
def parse_values(params, defaults):
"""Parses a Values parameter which should have only two values separated by
a comma. Used to override ON/OFF type messages.
"""
try:
split = params("Values").split(",")
if len(split) != 2:
return defaults
else:
return sp... | 63,474 |
def _get_activation_fn(activation):
"""Return an activation function given a string"""
if activation == "relu":
return F.relu
if activation == "gelu":
return F.gelu
if activation == "glu":
return F.glu
if activation == "leaky_relu":
return F.leaky_relu
raise Runti... | 63,475 |
def calc_pair_scale(seqs, obs1, obs2, weights1, weights2):
"""Return entropies and weights for comparable alignment.
A comparable alignment is one in which, for each paired state ij, all
alternate observable paired symbols are created. For instance, let the
symbols {A,C} be observed at position i and {A... | 63,476 |
def get_xml_config_gui_settings(xml_dict: Dict[Any, Any]) -> Dict[Any, Any]:
"""
Get the tool configuration from the config XML.
Parameters
----------
xml_dict: OrderedDictionary
Parsed XML Tool configuration
Returns
-------
OrderedDict
GUI settings extracted from the p... | 63,477 |
def deduplicate_list(list_with_dups):
"""
Removes duplicate entries from a list.
:param list_with_dups: list to be purged
:type lost_with_dups: list
:returns: a list without duplicates
:rtype: list
"""
return list(set(list_with_dups)) | 63,478 |
def pulpTest001(solver):
"""
Test that a variable is deleted when it is suptracted to 0
"""
x = LpVariable("x", 0, 4)
y = LpVariable("y", -1, 1)
z = LpVariable("z", 0)
c1 = x+y <= 5
c2 = c1 + z -z
print("\t Testing zero subtraction")
assert str(c2) | 63,479 |
def get_safe_name(name: str) -> str:
"""Returns the safe version of a username."""
return name.lower().replace(' ', '_') | 63,480 |
def make_aligned_utts(voice, transcriptions, sc_corpus, wav_dir, output_dir):
""" Make Word level utts and complete from 3-tier TextGrids...
"""
for sc_utt, uttname, wavfilename in zip(sc_corpus.utterances, sorted(transcriptions), sorted(glob(os.path.join(wav_dir, "*")))):
assert sc_utt.name == ut... | 63,481 |
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the Etherscan.io sensors."""
address = config.get(CONF_ADDRESS)
name = config.get(CONF_NAME)
token = config.get(CONF_TOKEN)
token_address = config.get(CONF_TOKEN_ADDRESS)
if token:
token = token.upper()
... | 63,482 |
def check_file_access(m): # pragma: no cover
"""Check if we can reach the file directly
or if we have to download it via PMS.
Args:
m (plexapi.video.Episode)
Return:
filepath or http to the file.
"""
LOG.debug('Checking if we can reach %s directly', m._pretty... | 63,483 |
def show_connection_command() -> None:
"""CLI command. List all connections."""
connection = Connection.get()
if not connection:
echo_info(
'No connection setup yet.\nUse "pano connection setup" to configure connection or edit pano.yaml file.'
)
exit(0)
echo_info(yam... | 63,484 |
def test_entity_key_complex(service):
"""Test complex key of entity"""
# pylint: disable=redefined-outer-name
responses.add(
responses.GET,
f"{service.url}/TemperatureMeasurements(Sensor='sensor1',Date=datetime'2017-12-24T18:00:00')",
headers={'Content-type': 'application/json'},
... | 63,485 |
def mplot(*args, **kwargs):
"""mpl multiplot"""
for x in args:
plt.plot(x, **kwargs)
plt.grid(True)
plt.show() | 63,486 |
def remove_sniffer(data, id):
"""Remove sniffer."""
filter = {}
data.client.delete("sniffer", id, **filter) | 63,487 |
def ImportExcel(request, **response_kwargs):
"""Receives excel, outputs json"""
o = []
if request.method == 'POST':
form = FileUploadForm(data=request.POST, files=request.FILES)
if form.is_valid():
workbook = xlrd.open_workbook(file_contents=request.FILES['file_source'].read())
... | 63,488 |
def resizewin(width, height):
"""
For resizing window
"""
if height == 0:
height = 1
glViewport(0, 0, width, height)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1.0 * width / height, 0.1, 100.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity() | 63,489 |
def adjust_factor(x, x_lims, b_lims=None):
"""
:param float x: current x value
:param float x_lims: box of x values to adjust
:param float b_lims: bathy adj at x_lims
:rtype: float
:returns: b = bathy adjustment
"""
if b_lims is None:
return 0
if x < x_lims[0] or x > x_lims[... | 63,490 |
def test_account_permission_logged_in_good_forever(
monkeypatch: MonkeyPatch, ndb_client: ndb.Client, api_client: Client
) -> None:
"""
If a user is logged in, we can automatically pull their linked auth, provided it is unexpired
Here, we expect success for a linked auth that never expires
"""
w... | 63,491 |
def init_operation(mocker):
"""Fixture to initialize an operation."""
mocker.patch.object(logoutput.LogOutput, "__init__", lambda x, y: None)
def _create():
return logoutput.LogOutput(None)
return _create | 63,492 |
def get_best_currencies(currency: str) -> Dict[str, Tuple[str, Any]]:
"""Get best sell and buy rates for available banks"""
parser_classes = get_parser_classes()
parsers = [parser(cache=default_cache) for parser in parser_classes
if parser.short_name != 'nbrb']
results = [(p.name, cache_p... | 63,493 |
def switch_version(path, version=None, use_sudo=False, user=None):
"""
Switch working tree to specified revno/revid (or latest if not specified).
:param path: Path of the working copy directory. Must exist.
:type path: str
:param version: revision to switch to
:type version: str
:param u... | 63,494 |
def computer_test(user, print_traceback, computer):
"""
Test the connection to a computer.
It tries to connect, to get the list of calculations on the queue and
to perform other tests.
"""
import traceback
from aiida.common.exceptions import NotExistent
from aiida.orm.backend import con... | 63,495 |
def time_iter(start, end):
"""iterates between the hour and minute values for 2 datetime objects
or (hour,minute) pairs. Yields a tuple of (hour,minute), does not return
a tuple for the end value."""
if type(start) == datetime.datetime:
start = (start.hour, start.minute)
if type(end) == datetime.datetime:
e... | 63,496 |
def bellman_ford(*args):
"""
bellman_ford(int const num_rows, int const [] Ap, int const [] Aj, int const [] Ax, int [] x, int [] z)
bellman_ford(int const num_rows, int const [] Ap, int const [] Aj, float const [] Ax, float [] x, int [] z)
bellman_ford(int const num_rows, int const [] Ap, int const [] ... | 63,497 |
def calc_LS_displacement(cor, Lval, Lvec, Lrho, Lpitch, position, prob):
"""Returns the amount of rotational displacement from L for an atom at the
given position.
"""
Lrot = Gaussian.GAUSS3C[prob] * calc_rmsd(Lval)
Lorigin = cor + Lrho
D = AtomMath.dmatrixu(Lvec, Lrot)
drot = n... | 63,498 |
def get_all_enabled_by_role(
*, db_session, role: ParticipantRoleType, project_id: int
) -> Optional[List[IncidentRole]]:
"""Gets all enabled incident roles."""
return (
db_session.query(IncidentRole)
.filter(IncidentRole.enabled == True) # noqa Flake8 E712
.filter(IncidentRole.role... | 63,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.