content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def create_model_helper(base_model_fn, sequential_inputs, is_training):
"""Helper function for creating model function given base model function.
This function creates a model function that adaptively slices the input
features for improved running speed.
Note that the base model function is required to have i... | 5,287,100 |
def check_not_finished_board(board: list) -> bool:
"""
Check if skyscraper board is not finished, i.e., '?' present on the game board.
Return True if finished, False otherwise.
>>> check_not_finished_board(['***21**', '4?????*', '4?????*', '*?????5', '*?????*', \
'*?????*', '*2*1***'])
False
... | 5,287,101 |
def transform(params):
"""Convert from ConfigSpace params to Orion params"""
return {k: (v if v is not _NoneValue else None) for k, v in params.items()} | 5,287,102 |
def get_orphan_users(email_to_user_profile, user_emails, source_priority):
""" Gets all users that don't exist in the Workday report anymore and terminate them in XSOAR. """
events = []
orphan_users = [email for email, user in email_to_user_profile.items()
if email not in user_emails an... | 5,287,103 |
def get_postmasters_directories():
""" detect all postmasters running and get their pids """
pg_pids = []
postmasters = {}
pg_proc_stat = {}
# get all 'number' directories from /proc/ and sort them
for f in glob.glob('/proc/[0-9]*/stat'):
# make sure the particular pid is accessible to ... | 5,287,104 |
def template_test():
"""Return a test template"""
return render_template_string(
templates.TEMPLATE, my_string="Wheeeee!", my_list=[0, 1, 2, 3, 4, 5]
) | 5,287,105 |
def find_overlap_percentage(nominator, denominator):
"""This function is used to find overlap percentage between 2 lists"""
common_skills_set = set(nominator).intersection(denominator)
common_skills_list = list(common_skills_set)
if common_skills_list:
overlap_percentage = len(common_skills_list... | 5,287,106 |
def test_update_application(client, user):
"""
Tests that using the application PUT endpoint functions
:param client: mongodb client
:param user: the test user object
"""
user, auth = user
application = {
"id": 3,
"jobTitle": "test_edit",
"companyName": "test_edit",
... | 5,287,107 |
def extant_file(value):
"""
'Type' for argparse - checks that file exists but does not open.
"""
if not os.path.exists(value):
# Argparse uses the ArgumentTypeError to give a rejection message like:
# error: argument input: x does not exist
raise argparse.ArgumentTypeError("{0} d... | 5,287,108 |
def display(guess):
"""display the progress of the genetic algorithm"""
timeDiff = datetime.datetime.now() - startTime
fitness = get_fitness(guess)
print("{}\t{}\t{}".format(guess, fitness, timeDiff)) | 5,287,109 |
def report_withot_driver_part():
"""Returns part from correct final report"""
return [" 10. Pierre Gasly | SCUDERIA TORO ROSSO HONDA | 0:01:12.941",
" 11. Carlos Sainz | RENAULT | 0:01:12.950"] | 5,287,110 |
def get_rationed_resizing(
resized: Union[int, float], length: int, other_length: int
) -> Tuple[int, int]:
"""
Get resized lengths for `length` and `other_length` according to
the ratio between `resized` and `length`.
Parameters
----------
resized : int or float
Already resized len... | 5,287,111 |
def pyprep_reference(matprep_artifacts):
"""Get the robust re-referenced signal for comparison with MATLAB PREP.
This fixture uses an artifact from MATLAB PREP of the CleanLined EEG signal
right before MATLAB PREP calls ``performReference``. As such, the results
of these tests will not be affected by a... | 5,287,112 |
def list_average(value_list: list[int|float]) -> None:
"""Return the average of a list of ints or floats."""
return list_sum(value_list) / len(value_list) | 5,287,113 |
def data_context_connectivity_context_connectivity_serviceuuid_include_nodetopology_uuidnode_uuid_get(uuid, topology_uuid, node_uuid): # noqa: E501
"""data_context_connectivity_context_connectivity_serviceuuid_include_nodetopology_uuidnode_uuid_get
returns tapi.topology.NodeRef # noqa: E501
:param uuid: ... | 5,287,114 |
def delete_restaurant(request, id):
"""
Delete dish.
Roure for 'remove/d/<int:id>'.
"""
Restaurant.objects.get(id=id).delete()
messages.info(request, "Deleted")
return redirect(f"/management") | 5,287,115 |
def is_part_of_branch(action):
"""
Checks if action is part of branch action.
:return: Boolean
"""
try:
branch_action = get_parent_by_tag(element=action, tag="steps_Behaviour")
except AttributeError: # parent with tag="steps_Behaviour" cannot be found --> is not in branch
return... | 5,287,116 |
def get_sprite_pos(map_dim, sprite_dim, clip_sprites):
"""Returns a sprite position for a given map and sprite."""
map_w, map_h = map_dim
sprite_w, sprite_h = sprite_dim
if clip_sprites:
x_pos = randint(-sprite_w, map_w)
y_pos = randint(-sprite_h, map_h)
else:
x_pos = randin... | 5,287,117 |
def reorder(fields, order, key):
"""
Reorders `fields` list sorting its elements in order they appear in `order` list.
Elements that are not defined in `order` list keep the original order.
:param fields: elements to be reordered
:param order: iterable that defines a new order
:param key: a fun... | 5,287,118 |
def generate_tiles(src_info, st_data_dir, url, wkt, no_data_value,
intermediate):
"""Generate tiles for emissivity standard deviation from ASTER data
Args:
src_info <SourceInfo>: Information about the source data
st_data_dir <str>: Location of the ST data files
url <s... | 5,287,119 |
def create(
model_path: str, model_type: str = "smpl", **kwargs
) -> Union[SMPL, SMPLH, SMPLX, MANO, FLAME]:
"""Method for creating a model from a path and a model type
Parameters
----------
model_path: str
Either the path to the model you wish to load or a folder,
where each subfol... | 5,287,120 |
def _upload_to_statusdb(run):
"""Triggers the upload to statusdb using the dependency flowcell_parser.
:param Run run: the object run
"""
couch_conf = CONFIG['statusdb']
couch_connection = statusdb.StatusdbSession(couch_conf).connection
db = couch_connection[couch_conf['xten_db']]
parser = ... | 5,287,121 |
def noisify_dfc2018_asymmetric(y_train, noise, random_state=None):
""" mistakes in labelling the land cover classes in 2018 DFC Houstan HSI dataset
class 0 --> class 1, class 3
class 1 --> class 5
class 3 --> class4, class 7
class 4 --> class 3, class7, class 10
class 7 --> class9, class 10, (cl... | 5,287,122 |
def run_openmdao_suite(argv=None):
"""This function is exported as a script that is runnable as part of
an OpenMDAO virtual environment as openmdao test.
This function wraps nosetests, so any valid nose args should also
work here.
"""
if argv is None:
argv = sys.argv
#Add any defau... | 5,287,123 |
def encoding_quality(
image: Union[str, Image.Image],
output_path: Optional[str] = None,
quality: int = 50,
metadata: Optional[List[Dict[str, Any]]] = None,
bboxes: Optional[List[Tuple]] = None,
bbox_format: Optional[str] = None,
) -> Image.Image:
"""
Changes the JPEG encoding quality le... | 5,287,124 |
def extCheck( extention: str ) -> str:
"""
Ensures a file extention includes the leading '.'
This is just used to error trap the lazy programmer who wrote it.
:param extention: file extention
:type extention: str
:return: Properly formatted file extention
:rtype: str
"""
if extentio... | 5,287,125 |
def clear_all_models(retain=['Language']):
"""Convenience function for removing all OLD models from the database.
The retain parameter is a list of model names that should not be cleared.
"""
for model_name in get_model_names():
if model_name not in retain:
models = get_models_by_nam... | 5,287,126 |
def ui_routes():
"""Import all static routes"""
return [static] | 5,287,127 |
def create_transaction(sender: str, recipient: str, amount: float):
"""insert new transaction to mempool"""
transaction = transactions.create_transaction(
sender=sender,
recipient=recipient,
amount=amount,
type="transfer",
)
return transaction | 5,287,128 |
def load_data(in_file, max_example=None, relabeling=True):
"""
load CNN / Daily Mail data from {train | dev | test}.txt
relabeling: relabel the entities by their first occurence if it is True.
"""
documents = []
questions = []
answers = []
num_examples = 0
f = open(in_file, ... | 5,287,129 |
def sort_dict(original, parent_path=''):
"""Transforms a dict into the format Authy requires"""
flattened_dict = ''
for key in sorted(original):
value = original[key]
if parent_path:
flattened_key = parent_path + '[{0}]'.format(key)
else:
flattened_key = key... | 5,287,130 |
def makeA(laplacian_matrix):
"""
This function create the all neighbor permutations.
The output A multiply by Y will be [ Y_i - Y_j ].T for all j > i
So the maximum will be C^n_2. But it will be less than this value
because of the sparseness of L.
Returns
-------
A : sparse matrix, shap... | 5,287,131 |
def service(
klass: Optional[C] = None,
*,
singleton: Optional[bool] = None,
scope: Optional[Scope] = Scope.sentinel(),
wiring: Optional[Wiring] = Wiring(),
) -> Union[C, Callable[[C], C]]:
"""
.. deprecated:: 1.3
Use :py:func:`.injectable` instead which is a drop-in replacement.
... | 5,287,132 |
def svn_diff_output_fns_invoke_output_diff_modified(_obj, output_baton, original_start, original_length, modified_start, modified_length, latest_start, latest_length):
"""svn_diff_output_fns_invoke_output_diff_modified(svn_diff_output_fns_t _obj, void * output_baton, apr_off_t original_start, apr_off_t original_len... | 5,287,133 |
def test_new_market(new_market):
"""
GIVEN a Market model
WHEN a new Market is created
THEN check the name, description are defined correctly
"""
assert new_market.name == 'Test Market'
assert new_market.description == 'Test Market' | 5,287,134 |
def test_profiler1():
"""
forward velocity, trapezoid, no overshoot
"""
DT = 0.02
profiler = TrapezoidalProfile(cruise_v=10, a=20, target_pos=50, tolerance=.5, current_target_v=0)
t = 0
pos = 0
if log_trajectory:
logger = DataLogger("test_profiler1.csv")
logger.log_whi... | 5,287,135 |
def check_output(*popenargs, **kwargs):
"""Run command with arguments and return its output as a byte string."""
if 'stdout' in kwargs or 'stderr' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
logging.debug('Trying to execute %s', popenargs)
process = subproc... | 5,287,136 |
def test_readme_example_three():
"""Get price prediction and positions from a signal transformer"""
pipeline = make_pipeline(
scikit_signal_factory(normalised_close), PricePredictionFromSignalRegression(), PositionsFromPricePrediction()
)
pipeline.fit_transform(simulated_market_data_4_years_gen... | 5,287,137 |
def delete_items(dictionary, key_list):
"""
This function performs a deep copy of a dictionary, checks if the
specified keys are included in the copy, and deletes key-value pairs
accordingly.
Parameters:
dictionary (dict): a dictionary
key_list (list): a list of the keys to be delete... | 5,287,138 |
def test_cli_universions_verbosity():
"""Test 'universions universions'."""
expected = ".".join(universions.__version__.split(".")[0:3])
output = check_output(["universions", "universions", "-v"])
assert str(output, encoding="utf-8").strip() == expected
output = check_output(["universions", "univers... | 5,287,139 |
def build_deterministic_service_from_transitions(
transition_function: TransitionFunction,
initial_state: State,
final_states: Set[State],
) -> Service:
"""
Initialize a service from transitions, initial state and final states.
The set of states and the set of actions are parsed from the transi... | 5,287,140 |
async def test_form(hass):
"""Test that the form is served with valid input."""
with patch(
"homeassistant.components.airzone.async_setup_entry",
return_value=True,
) as mock_setup_entry, patch(
"homeassistant.components.airzone.AirzoneLocalApi.get_hvac",
return_value=HVAC_M... | 5,287,141 |
def spreadLambdaProtocol(switching_values, steps, switching_types='auto', kind='cubic', return_tab_function=True):
"""
Takes a list of lambda values (either for sterics or electrostatics) and transforms that list
to be spread out over a given `steps` range to be easily compatible with the OpenMM Discrete1DF... | 5,287,142 |
def some_method(a1, a2):
"""
some_method returns the larger num
:param a1: num1
:param a2: num2
:return: 1 or 2
"""
if a1 > a2:
return 1
elif a1 < a2:
return 2
else:
return 0 | 5,287,143 |
def main():
"""
MAIN CODE
"""
set_debug(True)
print("---------------------------")
print("| Use Case 2 Workflow |")
print("---------------------------")
# GET INPUT PARAMETERS
args = parse_input_parameters()
if not os.path.exists(args.results_folder):
os.makedirs(a... | 5,287,144 |
def restartATS(conf:Configuration) -> bool:
"""
A convenience function for calling :func:`setATSStatus` for restarts.
:param conf: An object representing the configuration of :program:`traffic_ops_ort`
:returns: whether or not the restart was successful (or unnecessary)
"""
doRestart = ( conf.mode is Configurat... | 5,287,145 |
def test_get_scenarios_for_string(scitype_string):
"""Test retrieval of scenarios by string."""
scenarios = retrieve_scenarios(obj=scitype_string)
assert isinstance(scenarios, list), "return of retrieve_scenarios is not a list"
assert np.all(
isinstance(x, TestScenario) for x in scenarios
)... | 5,287,146 |
def generate_res_count_graph(
name: str,
cloudwatch_data_source: str,
loadbalancer: str,
target_group: str,
grid_pos: GridPos,
notifications: List[str],
) -> Graph:
"""
Generate res graph
"""
xx2_alias = "2xx"
xx3_alias = "3xx"
xx4_alias = "4xx"
xx5_alias = "5xx"
... | 5,287,147 |
def cost(prog):
"""Find the cost of a program tree."""
if type(prog) == VecOp:
return COSTS["VecOp"] + sum([cost(p) for p in prog.children])
elif type(prog) == Op:
return COSTS["Op"] + sum([cost(p) for p in prog.children])
elif type(prog) == Lit:
return COSTS["Lit"]
elif type... | 5,287,148 |
def transform_instance_annotations(
annotation, transforms, image_size, *, keypoint_hflip_indices=None
):
"""
Apply transforms to box, segmentation and keypoints annotations of a single instance.
It will use `transforms.apply_box` for the box, and
`transforms.apply_coords` for segmentation polygons... | 5,287,149 |
def to_timestamp(value):
"""
Convert a time zone aware datetime to a POSIX timestamp (with fractional
component.)
"""
return (value - epoch).total_seconds() | 5,287,150 |
def set_var(args, env):
"""Set the symbols in the argument list to the given expression."""
for item in args:
env.set(item[0], item[1].reduce()) | 5,287,151 |
def backends_mapping(custom_backend, private_base_url, lifecycle_hooks):
"""
Create 2 separate backends:
- path to Backend 1: "/echo-api"
- path to Backend 2: "/httpbin"
"""
return {"/echo-api": custom_backend("backend_one", endpoint=private_base_url("echo_api"), hooks=lifecycle_hooks),
... | 5,287,152 |
def test_mulitple_wheels(initproj, cmd, whl_dir):
"""Test installing with multiple external wheels"""
test_dir = str(
initproj(
"alright_app-0.2.0",
filedefs={
"tox.ini": """
[tox]
envlist = py
[testenv]
... | 5,287,153 |
def load_squad_context_parsing_info(set_type="train"):
"""
Load parsing information for context (paragraphs) in SQuAD-2.0.
"""
ctx2parse = dict()
file_path = DATA_PATH + "squad/%s.ctx.parse.jsonl" % set_type
for ln in open(file_path):
cur_obj = json.loads(ln)
ctx2parse[cur_obj["c... | 5,287,154 |
def post(json_attributes):
"""HTTP POST request."""
url = f"{API_URL}/v1/summaries/plain-text"
response = requests.post(url, json=json_attributes)
return response | 5,287,155 |
def love(size,shape,color):
""" Draws a single heart"""
t.pensize(5)
t.pencolor(color)
t.fillcolor(color)
radius = size * sin(shape * pi / 180) / (1 + sin((90 - shape) * pi / 180))
t.fill(True)
t.left(shape)
t.forward(size)
t.circle(radius, 180 + shape)
t.right(180)
t.circle(... | 5,287,156 |
def main():
"""Load pre-trained model from disk
"""
# construct the argument parse and parse the arguments
args = argparse.ArgumentParser()
args.add_argument("-d", "--dataset", required=True, help="path to input dataset")
args.add_argument("-m", "--model", required=True, help="path to pre-traine... | 5,287,157 |
def get_credentials(args):
""" Return current or assumed role credentials """
sess = boto3.session.Session(profile_name=args.profile)
sts = sess.client('sts')
# Find out who we are
ret = sts.get_caller_identity()
if not 'Account' in ret:
raise Exception('STS: Get Caller Identity fa... | 5,287,158 |
def p_paren_expr_list(p):
"""
expr_list : LPAREN expr_list RPAREN
"""
p[0] = p[2] | 5,287,159 |
def inf(shape, dtype, allocator=drv.mem_alloc):
"""
Return an array of the given shape and dtype filled with infs.
Parameters
----------
shape : tuple
Array shape.
dtype : data-type
Data type for the array.
allocator : callable
Returns an object that represents the m... | 5,287,160 |
def belief_propagation(model: GraphModel,
max_iter: int = 1000,
converge_thr: float = 1e-5,
damp_ratio: float = 0.1) -> InferenceResult:
"""Inference with (loopy) Belief Propagation.
Estimates partition function using Loopy Belief Propagation... | 5,287,161 |
def model_loss(input_real, input_z, output_channel_dim, alpha):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss,... | 5,287,162 |
def remove_from_index(dataobj_id):
"""Removes object of given id"""
es = get_elastic_client()
if not es:
return
es.delete(index=current_app.config["SEARCH_CONF"]["index_name"], id=dataobj_id) | 5,287,163 |
def somar(a=0, b=0, c=0):
"""
-> Faz a soma de tres valores e mostra o resultado na tela
:param a: o primeiro valor
:param b: o segundo valor
:param c: o terceiro valor
"""
s = a + b + c
print("A soma vale {}".format(s)) | 5,287,164 |
def compile_timestamped_transcript_files(json_filenames):
"""
`json_filenames` is a list of filepaths with this filename format:
00900-01000.json
where the left-number represents the starting time offset and
the right-number represents the ending time, in seconds
Each file in this list ... | 5,287,165 |
def _solve_inequality(ie, s):
""" A hacky replacement for solve, since the latter only works for
univariate inequalities. """
from sympy import Poly
if not ie.rel_op in ('>', '>=', '<', '<='):
raise NotImplementedError
expr = ie.lhs - ie.rhs
p = Poly(expr, s)
if p.degree() != 1:
... | 5,287,166 |
def verify_bgp_route_is_received(
device,
vrf,
neighbor_address,
default_rd,
default_vrf,
address_family,
received_routes,
):
""" Verify if VRF and Router Distinguisher have at least one received route
Args:
device ('obj') : Device object
addr... | 5,287,167 |
def theils_u_matrix(df):
"""
Wrapper around dython's theils_u. Given a dataframe df
containing only categorical data, it calculates Theil's U
for each combination of columns, filling an output matrix, and
returns the output matrix.
Parameters
----------
df : pandas.DataFrame
The... | 5,287,168 |
def SHRN(cpu_context: ProcessorContext, instruction: Instruction):
"""Shift right narrow immediate (vector form)"""
logger.debug("%s instruction not currently implemented.", instruction.mnem) | 5,287,169 |
def support(shape1, shape2, direction):
"""Find support for the Minkowski difference in the given direction.
PARAMETERS
----------
shape1, shape2: Shape
The inputs for Minkowski difference. `shape1` is subtracted from `shape2`.
direction: Point
The direction for finding th... | 5,287,170 |
def plot_trajectory(plot_config, show_plot=True):
"""Plot particle trajectory
"""
species = plot_config["species"]
pic_run = plot_config["pic_run"]
tracer_dir = "/net/scratch3/xiaocanli/vpic-sorter/data/trans-relativistic/"
picinfo_fname = '../data/pic_info/pic_info_' + pic_run + '.json'
pic... | 5,287,171 |
def load_metadata(directory, filename='meta.json'):
"""Load the metadata of a training directory.
Parameters
----------
directory : string
Path to folder where model is saved. For example './experiments/mnist'.
"""
path_to_metadata = os.path.join(directory, filename)
with... | 5,287,172 |
def cli(debug):
"""Run pymysensors as an app for testing purposes."""
if debug:
logging.basicConfig(level=logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO) | 5,287,173 |
def build_cache_maps(context, configurations, region, installed_region):
"""Build a giant cache of instances, volumes, snapshots for region"""
LOG.info("Building cache of instance, volume, and snapshots in %s",
region)
LOG.info("This may take a while...")
cache_data = {
# calculated... | 5,287,174 |
async def test_custom_availability_payload(hass, mqtt_mock_entry_with_yaml_config):
"""Test availability by custom payload with defined topic."""
await help_test_custom_availability_payload(
hass, mqtt_mock_entry_with_yaml_config, light.DOMAIN, DEFAULT_CONFIG
) | 5,287,175 |
def export_aggregation(aggregation, sketch, zip_file):
"""Export an aggregation from a sketch and write it to a ZIP file.
Args:
aggregation (timesketch.models.sketch.Aggregation): an aggregation
object.
sketch (timesketch.models.sketch.Sketch): a sketch object.
zip_file (Zip... | 5,287,176 |
def precise(adata: AnnData,
x1key: str = 'Ms',
x2key: str = 'velocity',
n_pcs: int = 50,
n_pvs: int = 50,
random_state: int = 0,
k: int = 10,
X1 = None,
X2 = None,
logX1: bool = False,
logX2: bool = F... | 5,287,177 |
def lint(fix_imports, check):
"""Lint and check code style with black, flake8 and isort."""
root_files = glob("*.py")
root_directories = [
name for name in next(os.walk("."))[1] if not name.startswith(".")
]
files_and_directories = [arg for arg in root_files + root_directories]
def exec... | 5,287,178 |
def test_make_contact_sync_message(user):
"""Test make_contact_sync_message serializes a user and returns a properly formatted sync message"""
contact_sync_message = api.make_contact_sync_message(user.id)
serialized_user = UserSerializer(user).data
serialized_user.update(serialized_user.pop("legal_addr... | 5,287,179 |
def get_service(key_file_location, api_name='analytics', api_version='v3',
scopes = ['https://www.googleapis.com/auth/analytics.edit',
'https://www.googleapis.com/auth/analytics']):
"""Get a service that communicates to a Google API.
Args:
key_file_location: The path to a valid service ac... | 5,287,180 |
def render_html_with_traceback(error: HTTPError) -> str:
"""Bottle's default error handler."""
return tob(template(ERROR_PAGE_TEMPLATE, e=error)) | 5,287,181 |
def is_empty(path: Path) -> bool:
"""Checks if a directory has files
Args:
path: The path to the directory to check
Returns:
bool: True if the dir is empty, False if it contains any files
"""
return not any(path.iterdir()) | 5,287,182 |
def match_dist(W_mat, pathways_mat):
"""
Match latent factors to pathways
Parameters
----------
W_mat : np.array
pathways_mat : np.array
Returns
-------
rv : list of tpl
each tpl is of the form (<latent_factor_id>, <pathway_id>, <distance>)
where W_mat latent factors are identified with nam... | 5,287,183 |
def before_method_control(
context: Experiment,
configuration: Configuration = None,
secrets: Secrets = None,
**kwargs: Any,
) -> None:
"""
Control run *before* the execution of an Experiments Method.
For a given Experiment, the control creates an Experiment Event Entity Context in
the ... | 5,287,184 |
def bounded_1d_kde(
pts, method="Reflection", xlow=None, xhigh=None, *args, **kwargs
):
"""Return a bounded 1d KDE
Parameters
----------
pts: np.ndarray
The datapoints to estimate a bounded kde from
method: str, optional
Method you wish to use to handle the boundaries
xlow: ... | 5,287,185 |
def parse_manifest_file(filename):
"""
Parses artifacts from a manifest file into a mapping from region to AMI.
Args:
filename: the manifest file to parse
Returns:
A dict mapping region to AMI ID
"""
with open(filename, 'r') as manifest_file:
packer_manifest = json.load(... | 5,287,186 |
def find_best_group_or_software(obj_tour_list):
""" Find group with step 2 and 3 with 2 or more subtechniques """
# Ideal: find Step 2 and Step 3 with most subtechniques
obj_w_best_step_2_3 = {}
for obj_tour in obj_tour_list:
# First group
if not obj_w_best_step_2_3:
obj_w_... | 5,287,187 |
def test_parse_query_string():
""" """
params = (
("status:not", "completed"),
("status", "active"),
("code", "http://acme.org/conditions/codes|ha125"),
("probability", "gt0.8"),
("date", "ge2010-01-01"),
("date", "le2011-12-31"),
("alue-quantity", "5.4|ht... | 5,287,188 |
def set_password(request):
"""
User visits confirm link and sets password.
User set password if he/she forgot his/her password, if he/she is invited
by owner, if he/she signs up.
"""
params = params_from_request(request)
key = params.get('key', '')
invitoken = params.get('invitoken', '... | 5,287,189 |
def detectPupil(image, threshold=101, minimum=5, maximum=50):
"""
Given an image, return the coordinates of the pupil candidates.
"""
# Create the output variable.
bestPupilID = -1
ellipses = []
centers = []
area = []
kernel = np.ones((5, 5), np.uint8)
# Grayscale i... | 5,287,190 |
def screen_off__MAC(jarvis, s):
"""Turn of screen instantly"""
os.system('pmset displaysleepnow') | 5,287,191 |
def vad_on_unlabelled_data(audio_path: str, output_path: str, session_name: str, strictness_level: int = 3,
word_threshold: int = 1, number_of_thread: int = 0, time_type: str = "timestamp"):
"""
This function is doing the VAD on unlabelled audio data.
It will generate a new csv fi... | 5,287,192 |
def main() -> None:
""" Make a jazz noise here """
args = get_args()
# str_arg = args.string_arg
# int_arg = args.int_arg
# file_arg = args.file
# flag_arg = args.on
pos_arg = args.positional
# print(f'str_arg = "{str_arg}"')
# print(f'int_arg = "{int_arg}"')
# print('file_arg ... | 5,287,193 |
def save_wav(x, path):
"""Save wav."""
pass | 5,287,194 |
def _get_talairach_all_levels(data_dir=None, verbose=1):
"""Get the path to Talairach atlas and labels
The atlas is downloaded and the files are created if necessary.
The image contains all five levels of the atlas, each encoded on 8 bits
(least significant octet contains the hemisphere, the next one ... | 5,287,195 |
def simplify(g:Graph) -> tuple:
"""
Performs a single iteration of simplification
of Graph instance according to a set or rules.
Returns: tuple: list of Graph instances and
boolean: whether the graph was successfully simplified
"""
choices = {(1,1):4,(2,2):4,(0,0):6,(1,0):3,(2,1):2... | 5,287,196 |
def check_duplicates(message):
"""tweet message 를 최신 세 개의 사용자 tweet 과 대조하여 중복된 게시물이 없는지 확인합니다.
전달인자:
message: 게시할 메시지를 포함한 문자열
반환 값:
중복이 발견되었을 경우 True를 나타내는 boolean
"""
last_three = retrieve_own_tweets()
last_three_tweets = [tweet.full_text for tweet in last_three] # 확인할 트윗 메시지 문자열 li... | 5,287,197 |
def myKPCA(X, Y, kernel_type='gauss', c=3, deg=2, ncomp=2, dataset='wine', show=False):
""" Kernel PCA.
Params:
--------------
X: n x d samples matrix
Y: n x 1 vector of class labels
kernel_type: Kernel type (Polynomial, RBF, etc.)
c: Gaussian width (Ignored if kernel... | 5,287,198 |
def get_test_subdirs(test_parser, test_root, question_to_grade):
"""Get list of questions to grade."""
problem_dict = test_parser.TestParser(
os.path.join(test_root, 'CONFIG')).parse()
if question_to_grade is not None:
questions = get_depends(test_parser, test_root, question_to_grade)
... | 5,287,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.