content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def init_log(logfile=None, file_size=5, debug=False):
"""
Initializes logging to file and console.
:param logfile: the name of the file
:param file_size: the max size of the file in megabytes, before wrapping occurs
:param debug: Boolean to enable verbose logging
:return: ``log`` object
""... | 5,337,200 |
def symmetric_mean_absolute_percentage_error(a, b):
"""
Calculates symmetric Mean Absolute Percentage Error (sMAPE).
Args:
a (): ctual values.
b (): Predicted values.
Returns: sMAPE float %.
"""
a = np.reshape(a, (-1,))
b = np.reshape(b, (-1,))
return 100.0 * np.mean(... | 5,337,201 |
def exec_quiet(handle, *args, **kwargs):
"""
Like exe.execute but doesnt print the exception.
"""
try:
val = handle(*args, **kwargs)
except Exception:
pass
else:
return val | 5,337,202 |
def link_documents_bundles_with_journals(
journal_path: str, issue_path: str, output_path: str
):
"""Busca pelo relacionamento entre periódicos e fascículos a partir
de arquivos JSON extraídos de uma base MST. O resultado é escrito
em um arquivo JSON contendo um objeto (dict) com identificadores de
... | 5,337,203 |
def make_modified_function_def(original_type, name, original, target):
"""Make the modified function definition.
:return: the definition for the modified function
"""
arguments = format_method_arguments(name, original)
argument_names = set(target.parameters)
unavailable_arguments = [p for p in ... | 5,337,204 |
def send_is_typing_event(msisdn):
"""
Sends IS_TYPING event to the user.
Args:
msisdn (str): The msisdn of the user in
E.164 format, e.g. '+14155555555'.
"""
agent_event = {
'eventType': 'IS_TYPING'
}
send_event_with_body(msisdn, agent_event, str(uuid.uuid4().int) + "a") | 5,337,205 |
async def test_non_json_response(aresponses):
"""Test that the proper error is raised when the response text isn't JSON."""
aresponses.add(
"www.airvisual.com",
"/api/v2/node/12345",
"get",
aresponses.Response(
text="This is a valid response, but it isn't JSON.",
... | 5,337,206 |
def fetch_tiles(server, tile_def_generator, output=pathlib.Path('.'), force=False):
"""
fetch and store tiles
@param server
server definition object
@param tile_def_generator
generator of tile definitions consisting of [x, y, z, bbox] tuples
@param ou... | 5,337,207 |
def _UTMLetterDesignator(lat):
"""
This routine determines the correct UTM letter designator for the
given latitude returns 'Z' if latitude is outside the UTM limits of
84N to 80S.
Written by Chuck Gantz- chuck.gantz@globalstar.com
"""
if 84 >= lat >= 72: return 'X'
elif 72 > lat >= 64: ... | 5,337,208 |
def is_ignored(file: str) -> bool:
"""
Check if the given file is ignored
:param file: the file
:return: if the file is ignored or not
"""
for ignored in config.get('input').get('ignored'):
ignored_regex = re.compile(ignored)
if re.match(ignored_regex, file):
return T... | 5,337,209 |
def plot_learning_curve(classifier, X, y, measurements=[0.1, 0.325, 0.55, 0.775, 1.], metric=None, n_jobs=-1,
save_to_folder=os.path.join(os.path.dirname(__file__), "ExperimentResults")):
"""
Calculates the learning curve for a given model (classifier or regressor). The methods takes the... | 5,337,210 |
def get_powerups_wf(original_wf):
"""
get user powerups setting.
"""
idx_list = get_fws_and_tasks(original_wf)
for idx_fw, idx_t in idx_list:
f0 = original_wf.fws[idx_fw].tasks[idx_t]
if not isinstance(f0, Iterable) or isinstance(f0, str) : continue
for k0 in f0:
... | 5,337,211 |
def enumerate_phone_column_index_from_row(row):
"""Enumerates the phone column from a given row. Uses Regexs
Parameters
----------
row : list
list of cell values from row
Returns
-------
int
phone column index enumerated from row
"""
# initial phone_column_index va... | 5,337,212 |
def fetch_words(url):
"""
Fetch a list of words from URL
Args:
url: The URL of a UTF-8 text doxument
Returns:
A list of strings containing the words from
the document.
"""
story = urlopen(url)
story_words = []
for line in story:
line_words = line.decode(... | 5,337,213 |
def pipe(func):
"""command pipe"""
@wraps(func)
def wrapper(*args, **kwargs):
if PIPE_LOCK.locked():
LOGGER.debug("process locked")
return None
window = sublime.active_window()
view = window.active_view()
status_key = "pythontools"
with PIPE... | 5,337,214 |
def dot_keys_to_nested(data: Dict) -> Dict:
"""old['aaaa.bbbb'] -> d['aaaa']['bbbb']
Args:
data (Dict): [description]
Returns:
Dict: [description]
"""
rules = defaultdict(lambda: dict())
for key, val in data.items():
if '.' in key:
key, _, param = key.partit... | 5,337,215 |
def vec2adjmat(source, target, weight=None, symmetric=True):
"""Convert source and target into adjacency matrix.
Parameters
----------
source : list
The source node.
target : list
The target node.
weight : list of int
The Weights between the source-target values
symm... | 5,337,216 |
def ll_(msg, t0=None):
"""
... ending logging msg giving a time lapse if starting time stamp given
"""
import time
import logging
logging.info(' {}{}'.format(msg, ' <--' if t0 else ''))
if t0:
logging.info(' ' + rTime_(time.time() - t0))
logging.info(' ') | 5,337,217 |
def do_confusion_parks(
qsos: QSOLoaderDR16Q,
dla_cnn: str = "data/dr16q/distfiles/DR16Q_v4.fits",
snr: float = -1.0,
dla_confidence: float = 0.98,
p_thresh: float = 0.98,
lyb: bool = True,
):
"""
plot the multi-DLA confusion matrix between our MAP predictions and Parks' predictions
... | 5,337,218 |
def configure(spec, host, port, user, password, dbname, prompt, attributes, memberships,
ownerships, privileges, live, verbose):
"""
Configure the role attributes, memberships, object ownerships, and/or privileges of a
database cluster to match a desired spec.
Note that attributes and mem... | 5,337,219 |
def is_valid(number):
"""Check if the number provided is a valid PAN. This checks the
length and formatting."""
try:
return bool(validate(number))
except ValidationError:
return False | 5,337,220 |
def remove_spaces(string: str):
"""Removes all whitespaces from the given string"""
if string is None:
return ""
return "".join(l for l in str(string) if l not in WHITESPACES) | 5,337,221 |
def decode_event_to_internal(abi, log_event):
""" Enforce the binary for internal usage. """
# Note: All addresses inside the event_data must be decoded.
decoded_event = decode_event(abi, log_event)
if not decoded_event:
raise UnknownEventType()
# copy the attribute dict because that data... | 5,337,222 |
def plot_msa_info(msa):
"""
Plot a representation of the MSA coverage.
Copied from https://github.com/sokrypton/ColabFold/blob/main/beta/colabfold.py
"""
msa_arr = np.unique(msa, axis=0)
total_msa_size = len(msa_arr)
print(f"\n{total_msa_size} Sequences Found in Total\n")
if total_msa... | 5,337,223 |
def run_ode_solver(system, slope_func, **options):
"""Computes a numerical solution to a differential equation.
`system` must contain `init` with initial conditions,
`t_0` with the start time, and `t_end` with the end time.
It can contain any other parameters required by the slope function.
`opti... | 5,337,224 |
def case_configuration(group_id, det_obj, edges):
"""
Get all the needed information of the detectors for the chosen edges, as well as only those trajectories that map
onto one of the edges.
Parameters
----------
group_id
det_obj
edges
Returns
-------
"""
ds = det_obj.d... | 5,337,225 |
def test_formats(format):
"""
Testing different formats for StreamGear
"""
StreamGear(output="output.mpd", format=format, logging=True) | 5,337,226 |
def _remarks(item: str) -> str:
"""Returns the remarks. Reserved for later parsing"""
return item | 5,337,227 |
def unauthorized():
# TODO: security
"""Redirect unauthorised users to Login page."""
flash('Please log in to access this page.', 'danger')
return redirect(url_for('auth.login', next=request.path)) | 5,337,228 |
def register_elastic_ip(ElasticIp=None, StackId=None):
"""
Registers an Elastic IP address with a specified stack. An address can be registered with only one stack at a time. If the address is already registered, you must first deregister it by calling DeregisterElasticIp . For more information, see Resource M... | 5,337,229 |
def delete_streaming_distribution(Id=None, IfMatch=None):
"""
Delete a streaming distribution. To delete an RTMP distribution using the CloudFront API, perform the following steps.
For information about deleting a distribution using the CloudFront console, see Deleting a Distribution in the Amazon CloudFron... | 5,337,230 |
async def monitor(obj, state, only, add_date, ignore):
"""Monitor a DistKV subtree"""
flushing = not state
seen = False
async with obj.client.watch(
obj.path, nchain=obj.meta, fetch=state, max_depth=0 if only else -1
) as res:
async for r in res:
if add_date and "value"... | 5,337,231 |
def _date_to_datetime(value):
"""Convert a date to a datetime for datastore storage.
Args:
value: A datetime.date object.
Returns:
A datetime object with time set to 0:00.
"""
assert isinstance(value, datetime.date)
return datetime.datetime(value.year, value.month, value.day) | 5,337,232 |
def DirType(d):
""" given a string path to a directory, D, verify it can be used.
"""
d = os.path.abspath(d)
if not os.path.exists(d):
raise ArgumentTypeError('DirType:%s does not exist' % d)
if not os.path.isdir(d):
raise ArgumentTypeError('DirType:%s is not a directory' % d)
if os.access(d, os.R_O... | 5,337,233 |
def get_posted_float(key):
"""
Retrieve a named float value from a POSTed form
:param key: Value key
:return: Value or None if not specified
"""
value = request.form[key]
return float(value) if value else None | 5,337,234 |
def te_ds(mass, norm_vel, x_ratios, source_distance, te_einstein, gamma, sigma_total, \
xval, val):
"""Returns the probability of a sampled value T_E by weighting from the
T_E probability distribution of the data """
if min(xval) < te_einstein <= max(xval):
omegac = gamma*norm_vel*np.sqrt(x_rati... | 5,337,235 |
def roulette(fitness_values, return_size, elite=0):
"""
Perform a roulette wheel selection
Return return_size item indices
"""
sorted_indices = np.argsort(fitness_values)
c_sorted = np.sort(fitness_values).cumsum()
c_sorted /= np.max(c_sorted)
sampled = [sorted_indices[np.sum... | 5,337,236 |
def working_dir(val, **kwargs): # pylint: disable=unused-argument
"""
Must be an absolute path
"""
try:
is_abs = os.path.isabs(val)
except AttributeError:
is_abs = False
if not is_abs:
raise SaltInvocationError("'{0}' is not an absolute path".format(val))
return val | 5,337,237 |
def convert(file, destination):
"""Convert a user.yaml FILE to the new format. If a DESTINATION is provided, saves the result as a file. Otherwise, print the result."""
with open(file, "r") as f:
user_yaml = f.read()
convert_old_user_yaml_to_new_user_yaml(user_yaml, destination) | 5,337,238 |
def import_blank_from_ipuz(ipuz, blank):
"""Load a blank grid from an ipuz file into the database."""
data = json.loads(ipuz.read().decode('latin_1'))
for y, row in enumerate(data['puzzle']):
for x, cell in enumerate(row):
if cell == "#":
block = Block(blank=blank, x=x, y... | 5,337,239 |
def apply_latency_predictor_cli(args):
"""apply latency predictor to predict model latency according to the command line interface arguments
"""
if not args.predictor:
logging.keyinfo('You must specify a predictor. Use "nn-meter --list-predictors" to see all supporting predictors.')
return
... | 5,337,240 |
def create_sample_tree():
"""
1
/ \
2 3
/ \
4 5
"""
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
return root | 5,337,241 |
def sp_normalize(adj_def, device='cpu'):
"""
:param adj: scipy.sparse.coo_matrix
:param device: default as cpu
:return: normalized_adj:
"""
adj_ = sp.coo_matrix(adj_def)
adj_ = adj_ + sp.coo_matrix(sp.eye(adj_def.shape[0]), dtype=np.float32)
rowsum = np.array(adj_.sum(axis=1)).re... | 5,337,242 |
def isTileEvent(x:int, y:int):
"""
checks if a given tile is an event or not quicker than generateTileAt
x: the x value of the target tile
y: the y value of the target tile
"""
perlRand = getPerlin(x, y, s=2.501)
if Math.floor(perlRand * 3400) == 421 and deriveTile(x, y)=='H':
return True
elif Math... | 5,337,243 |
def args_to_object(args,obj):
"""
Copy all fields from the argparse table "args" to the object "obj"
"""
for n, v in inspect.getmembers(args):
if not n.startswith('_'):
setattr(obj, n, v) | 5,337,244 |
def to_onehot_sym(ind, dim):
"""Return a matrix with one hot encoding of each element in ind."""
assert ind.ndim == 1
return theano.tensor.extra_ops.to_one_hot(ind, dim) | 5,337,245 |
def generate_potential_grasp(object_cloud):
"""
The object_cloud needs to be in table coordinates.
"""
# https://www.cs.princeton.edu/~funk/tog02.pdf picking points in triangle
nrmls = object_cloud.normals.copy()
# if object_cloud.points[:,2].max()<0.11:
# nrmls[nrmls[:,2]>0] *= -1
#... | 5,337,246 |
def ACP_O(model, Xtrain, Ytrain, Xtest, labels = [0,1], out_file = None, seed = 42, damp = 10**-3, batches = 1):
"""Runs ACP (ordinary) CP-IF to make a prediction for all points in Xtest
"""
N = len(Xtrain)
# Train model on D.
model_D = model
model_D = model_D.to(device)
model_D.fit(Xt... | 5,337,247 |
def set(ctx, username, password):
"""update user's password.\n
USERNAME: the user's name \n
PASSWORD: the new password of the user
"""
client = ctx.obj['client']
if not username or not password:
click.echo('user set must provide username and password.', err=True)
sys.exit(1)
... | 5,337,248 |
def erase_all_data():
""" Function to erase all data for a clean start. Use with caution!"""
JobStreams, Replicates, BaseDirNames, JobBaseNames, Runs, \
nJobStreams, nReplicates, nBaseNames = check_job_structure()
cwd = os.getcwd()
print("\nWe are about to erase all data in this direct... | 5,337,249 |
def func (x):
"""
sinc (x)
"""
if x == 0:
return 1.0
return math.sin (x) / x | 5,337,250 |
def grad_norm(model=None, parameters=None):
"""Compute parameter gradient norm."""
assert parameters is not None or model is not None
total_norm = 0
if parameters is None:
parameters = []
if model is not None:
parameters.extend(model.parameters())
parameters = [p for p in parameters if p.grad is no... | 5,337,251 |
def chain_from_iterable(iterables):
"""Alternate constructor for chain(). Gets chained inputs from a
single iterable argument that is evaluated lazily.
:param iterables: an iterable of iterables
"""
# chain_from_iterable(['ABC', 'DEF']) --> A B C D E F
for it in iterables:
for element ... | 5,337,252 |
def db_entry_trim_empty_fields(entry):
""" Remove empty fields from an internal-format entry dict """
entry_trim = copy.deepcopy(entry) # Make a copy to modify as needed
for field in [ 'url', 'title', 'extended' ]:
if field in entry:
if (entry[field] is None) or \
(type(e... | 5,337,253 |
def test_get_alert_attachments(mocker):
"""
Given:
- An app client object
- Alert-id = 1234
When:
- Calling function get_alert_attachments
Then:
- Ensure the return data is correct
"""
mock_client = OpsGenieV3.Client(base_url="")
mocker.patch.object(mock_clien... | 5,337,254 |
def loadconfig(PATH):
"""Load Latte's repo configuration from
the PATH. A dictionary of the config data is returned, otherwise None."""
try:
f = open(PATH, "r")
except FileNotFoundError:
return None
else:
confobj = SWConfig(f.read())
if confobj is None:
re... | 5,337,255 |
def _call_token_server(method, request):
"""Sends an RPC to tokenserver.minter.TokenMinter service.
Args:
method: name of the method to call.
request: dict with request fields.
Returns:
Dict with response fields.
Raises:
auth.AuthorizationError on HTTP 403 reply.
InternalError if the RPC ... | 5,337,256 |
def assert_array_equal(x: Tuple[int, int, int], y: Tuple[float, float, int]):
"""
usage.skimage: 3
"""
... | 5,337,257 |
def get_keywords(text):
"""Get keywords that relate to this article (from NLP service)
Args:
text (sting): text to extract keywords from
Returns:
[list]: list of extracted keywords
"""
extracted_keywords = []
request = {'text': text}
nlp_output = requests.post(env.get_keyword... | 5,337,258 |
def test_tiproviders_editor(kv_sec, mp_conf_ctrl):
"""TI Providers item editor."""
edit_comp = CETIProviders(mp_controls=mp_conf_ctrl)
edit_comp.select_item.label = "VirusTotal"
provider = edit_comp.select_item.label
# get the control for this provider
ctrl_path = f"TIProviders.{provider}.Args.A... | 5,337,259 |
def weather_config() -> str:
"""The function config_handle() is called
and the contents that are returned are
stored in the variable 'config file'.
This is then appropriately parsed so the
weather api key is accessed. This is then
returned at the end of the function."""
#A... | 5,337,260 |
def interpret_bit_flags(bit_flags, flip_bits=None, flag_name_map=None):
"""
Converts input bit flags to a single integer value (bit mask) or `None`.
When input is a list of flags (either a Python list of integer flags or a
string of comma-, ``'|'``-, or ``'+'``-separated list of flags),
the returne... | 5,337,261 |
def _check_web_services_response(response, msg=''):
"""
Log an error message if the specified response's
status code is not 200.
"""
if response.status_code == 404:
current_app.logger.error("{}".format(msg))
elif response.status_code != 200:
current_app.logger.error("{}\n{}".form... | 5,337,262 |
def test_update_post(client):
"""Test that dummy post is properly updated"""
POST["label"] = "YTA"
payload = dumps(dict(label="YTA"))
resp = client.put(f"{settings.api.version}/posts/{POST['id']}/", data=payload)
assert resp.status_code == HTTP_200_OK
assert resp.json() == POST | 5,337,263 |
def reparam(mu, std, do_sample=True, cuda=True):
"""Reparametrization for Normal distribution.
"""
if do_sample:
eps = torch.FloatTensor(std.size()).normal_()
if cuda:
eps = eps.cuda()
eps = Variable(eps)
return mu + eps * std
else:
return mu | 5,337,264 |
def simu_grid_graph(width, height, rand_weight=False):
"""Generate a grid graph.
To generate a grid graph. Each node has 4-neighbors. Please see more
details in https://en.wikipedia.org/wiki/Lattice_graph. For example,
we can generate 5x3(width x height) grid graph
0---1---2---3---4
... | 5,337,265 |
def solrctl():
"""
solrctl path
"""
for dirname in os.environ.get('PATH', '').split(os.path.pathsep):
path = os.path.join(dirname, 'solrctl')
if os.path.exists(path):
return path
return None | 5,337,266 |
def calculate_sensitivity_to_weighting(jac, weights, moments_cov, params_cov):
"""calculate the sensitivity to weighting.
The sensitivity measure is calculated for each parameter wrt each moment.
It answers the following question: How would the precision change if the weight of
the kth moment is i... | 5,337,267 |
def subword(w):
"""
Function used in the Key Expansion routine that takes a four-byte input word
and applies an S-box to each of the four bytes to produce an output word.
"""
w = w.reshape(4, 8)
return SBOX[w[0]] + SBOX[w[1]] + SBOX[w[2]] + SBOX[w[3]] | 5,337,268 |
def YumInstall(vm):
"""Installs the OpenJDK package on the VM."""
vm.InstallPackages('java-1.{0}.0-openjdk-devel'.format(FLAGS.openjdk_version)) | 5,337,269 |
def deaScranDESeq2(counts, conds, comparisons, alpha, scran_clusters=False):
"""Makes a call to DESeq2 with SCRAN to
perform D.E.A. in the given
counts matrix with the given conditions and comparisons.
Returns a list of DESeq2 results for each comparison
"""
results = list()
n_cells = len(co... | 5,337,270 |
def stop_gzweb(cloudsim_api, constellation_name):
"""
Stops the gzweb service and waits for its status to "stopped"
"""
cloudsim_api.stop_gzweb(constellation_name)
count=100
while count > 0:
print("count %s/100" % count)
time.sleep(5)
count -= 1
r = cloudsim_api.... | 5,337,271 |
def cylindrical_to_cartesian(a: ArrayLike) -> NDArray:
"""
Transform given cylindrical coordinates array :math:`\\rho\\phi z`
(radial distance, azimuth and height) to cartesian coordinates array
:math:`xyz`.
Parameters
----------
a
Cylindrical coordinates array :math:`\\rho\\phi z` ... | 5,337,272 |
def eigenarray_to_array( array ):
"""Convert Eigen::ArrayXd to numpy array"""
return N.frombuffer( array.data(), dtype='d', count=array.size() ) | 5,337,273 |
def _ncon_to_adjmat(labels: List[List[int]]):
""" Generate an adjacency matrix from the network connections. """
# process inputs
N = len(labels)
ranks = [len(labels[i]) for i in range(N)]
flat_labels = np.hstack([labels[i] for i in range(N)])
tensor_counter = np.hstack(
[i * np.ones(ranks[i], dtype=... | 5,337,274 |
def start_project(name, gcloud_project, database, tasks):
"""
This command creates a new project structure under the directory <name>.
"""
path = os.path.join(os.path.dirname(__file__), 'project_template')
loader = FileSystemLoader(path)
env = Environment(loader=loader)
os.mkdir(os.path.joi... | 5,337,275 |
def test_command_line_interface() -> None:
"""Test the CLI."""
runner = CliRunner()
result = runner.invoke(cli.proto_compile)
assert result.exit_code == 0
assert "Usage: proto-compile" in result.output
help_result = runner.invoke(cli.proto_compile, ["--help"])
assert help_result.exit_code ==... | 5,337,276 |
def search(name="", address="", description=""):
"""
Returns a list of Plan Objects
"""
plans = []
name = name.replace(' ','+')
address = address.replace(' ','+')
description = description.replace(' ','+')
Address_Search_URL = f"http://webgeo.kildarecoco.ie/planningenquiry/Public/GetPl... | 5,337,277 |
def _is_install_requirement(requirement):
""" return True iff setup should install requirement
:param requirement: (str) line of requirements.txt file
:return: (bool)
"""
return not (requirement.startswith('-e') or 'git+' in requirement) | 5,337,278 |
def test_amp_pro():
"""適当な量子状態をつくって、棒グラフを表示するテスト用関数。"""
n = 3
state = QuantumState(n)
#state.set_Haar_random_state()
show_amplitude(state)
show_probability(state)
X(0).update_quantum_state(state)
show_amplitude(state)
show_probability(state)
H(0).update_quantum_state(st... | 5,337,279 |
def confusion_matrices_runs_thresholds(
y, scores, thresholds, n_obs=None, fill=0.0, obs_axis=0
):
"""Compute confusion matrices over runs and thresholds.
`conf_mats_runs_thresh` is an alias for this function.
Parameters
----------
y : np.ndarray[bool, int32, int64, float32, float64]
t... | 5,337,280 |
def new_project(request):
"""
Function that enables one to upload projects
"""
profile = Profile.objects.all()
for profile in profile:
if request.method == 'POST':
form = ProjectForm(request.POST, request.FILES)
if form.is_valid():
pro = form.save(comm... | 5,337,281 |
def move_to_next_pixel(fdr, row, col):
""" Given fdr (flow direction array), row (current row index), col (current col index).
return the next downstream neighbor as row, col pair
See How Flow Direction works
http://desktop.arcgis.com/en/arcmap/latest/tools/spatial-analyst-toolbox/how-flow-direction-w... | 5,337,282 |
def AddBetaArgs(parser):
"""Declare beta flag and positional arguments for this command parser."""
flags.AddExternalMasterGroup(parser)
flags.AddInstanceResizeLimit(parser)
flags.AddNetwork(parser)
flags.AddAllocatedIpRangeName(parser)
labels_util.AddCreateLabelsFlags(parser) | 5,337,283 |
def test_timeout_write_property(mqtt_servient):
"""Timeouts can be defined on Property writes."""
exposed_thing = next(mqtt_servient.exposed_things)
prop_name = next(six.iterkeys(exposed_thing.properties))
td = ThingDescription.from_thing(exposed_thing.thing)
mqtt_mock = _build_hbmqtt_mock(_effect_... | 5,337,284 |
def test_method_delete_not_allowed(flask_app, api_version):
"""Test Depot ID 96556/3.
Verify the TAC API does not support HTTP DELETE and returns HTTP 405 METHOD NOT ALLOWED.
"""
rv = flask_app.delete(url_for('{0}.tac_api'.format(api_version), tac='35567907'))
assert rv.status_code == 405
asser... | 5,337,285 |
def test_negative_make_bucket_invalid_name( # pylint: disable=invalid-name
log_entry):
"""Test make_bucket() with invalid bucket name."""
# Get a unique bucket_name
bucket_name = _gen_bucket_name()
# Default location
log_entry["args"] = {
"location": "default value ('us-east-1')",
... | 5,337,286 |
def test_fetch_industry_headlines_happypath():
"""validate expected layout from yahoo raw feeds"""
feed = yahoo.news.fetch_finance_headlines_yahoo(
'AAPL',
uri=yahoo.news.INDUSTRY_NEWS_URL
)
print(feed[0])
print(feed[0].keys())
assert isinstance(feed, list)
[
helpers... | 5,337,287 |
def clean_text(post):
"""
Function to filter basic greetings and clean the input text.
:param post: raw post
:return: clean_post or None if the string is empty after cleaning
"""
post = str(post)
""" filtering basic greetings """
for template in TEMPLATES:
if template in str(pos... | 5,337,288 |
def turnIsLegal(speed, unitVelocity, velocity2):
"""
Assumes all velocities have equal magnitude and only need their relative angle checked.
:param velocity1:
:param velocity2:
:return:
"""
cosAngle = np.dot(unitVelocity, velocity2) / speed
return cosAngle > MAX_TURN_ANGLE_COS | 5,337,289 |
def convert_selection_vars_to_common_effects(G: ADMG) -> nx.DiGraph:
"""Convert all undirected edges to unobserved common effects.
Parameters
----------
G : ADMG
A causal graph with undirected edges.
Returns
-------
G_copy : ADMG
A causal graph that is a fully specified DAG... | 5,337,290 |
def plot_confusion_matrix(estimator, X, y_true, *, labels=None,
sample_weight=None, normalize=None,
display_labels=None, include_values=True,
xticks_rotation='horizontal',
values_format=None,
... | 5,337,291 |
def mean_binary_proto_to_np_array(caffe, mean_binproto):
"""
:param caffe: caffe instances from import_caffe() method
:param mean_binproto: full path to the mode's image-mean .binaryproto created from train.lmdb.
:return:
"""
# I don't have my image mean in .npy file but in binaryproto. ... | 5,337,292 |
def addnplay(tag):
"""
looks up song or album in MPD, adds them to the playlist,
plays them if the playlist has been empty.
adheres to toggle_clr_plist.
:param tag: string of song, album title, case sensitive
format: /^(s|a):[\w\s]+/
"""
with connection(client):
try... | 5,337,293 |
async def get_db() -> sqlalchemy.engine.base.Connection:
"""Get a SQLAlchemy database connection.
Uses this environment variable if it exists:
DATABASE_URL=dialect://user:password@host/dbname
Otherwise uses a SQLite database for initial local development.
"""
load_dotenv()
database_url = o... | 5,337,294 |
async def stop_project(ctx, services: List[str], show_status=True):
"""
Stops a project by stopping all it's services (or a subset).
If show_status is true, shows status after that.
"""
project = ctx.system_config["project"]
engine = ctx.engine
if len(services) < 1:
return
echo... | 5,337,295 |
def delete_channel(u, p, cid):
"""
Delete an existing service hook.
"""
c = Channel.query.filter_by(
id=cid,
project_id=p.id
).first()
if not c:
# Project or channel doesn't exist (404 Not Found)
return abort(404)
if c.project.owner.id != g.user.id or c.proj... | 5,337,296 |
def ridgeline(data, overlap=0, fill=True, labels=None, n_points=150, dist_scale=0.05):
"""
Creates a standard ridgeline plot.
data, list of lists.
overlap, overlap between distributions. 1 max overlap, 0 no overlap.
fill, matplotlib color to fill the distributions.
n_points, number of points to... | 5,337,297 |
def joint_img_freq_loss(output_domain, loss, loss_lambda):
"""Specifies a function which computes the appropriate loss function.
Loss function here is computed on both Fourier and image space data.
Args:
output_domain(str): Network output domain ('FREQ' or 'IMAGE')
loss(str): Loss type ('L... | 5,337,298 |
def verify_auth_token(untrusted_message):
"""
Verifies a Auth Token. Returns a
django.contrib.auth.models.User instance if successful or False.
"""
# decrypt the message
untrusted = URLSafeTimedSerializer(settings.SSO_SECRET).loads(
untrusted_message, max_age=300)
# do some extra va... | 5,337,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.