content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_merged_contextvars(bound_logger: BindableLogger) -> Dict[str, Any]:
"""
Return a copy of the current context-local context merged with the context
from *bound_logger*.
.. versionadded:: 21.2.0
"""
ctx = get_contextvars()
ctx.update(structlog.get_context(bound_logger))
return ct... | 7,600 |
def policy_iteration(policy, env, value_function=None, threshold=0.00001, max_steps=1000, **kwargs):
"""
Policy iteration algorithm, which consists on iterative policy evaluation until convergence for the current policy
(estimate over many sweeps until you can't estimate no more). And then finally updates p... | 7,601 |
def main(pdb_complex_core, pdb_fragment, pdb_atom_core_name, pdb_atom_fragment_name, steps, core_chain="L",
fragment_chain="L", output_file_to_tmpl="growing_result.pdb", output_file_to_grow="initialization_grow.pdb",
h_core = None, h_frag = None, rename=False, threshold_clash=1.70):
"""
From a... | 7,602 |
def iterator_filtered( gff_iterator, feature = None, source = None, contig = None, interval = None, strand = None):
"""iterate over the contents of a gff file.
yield only entries for a given feature
"""
if interval: start, end = interval
if strand == ".": strand = None
for gff in gff_iterator:... | 7,603 |
def create_blueprint(app):
"""Register blueprint routes on app."""
blueprint = Blueprint(
"invenio_records_marc21",
__name__,
template_folder="../templates",
url_prefix="/marc21",
)
blueprint = init_theme_views(blueprint, app)
blueprint = init_records_views(blueprint... | 7,604 |
def mock_machine():
"""Fixture localapi Machine init with the data/response.json file."""
with requests_mock.Mocker() as mock_resp:
f = open(response_test_path,)
data = json.load(f)
machine_ipaddr = "0.0.0.0"
mock_addr = f"http://{machine_ipaddr}:3000/api/v1/hvac"
mock_re... | 7,605 |
def test_update_height():
"""
Test to make sure the height is being updated correctly:
Height = 3: 4
/ \
Height = 2: 2 5
/ \\ / \
Height = 1: 1 3 6 7
"""
tree = AVLTree()
tree.insert_array([1, 2, 3, 4, 5, 6, 7])
assert tre... | 7,606 |
def get_files_links(service, v):
"""Print links of uploaded files.
:param: service (object): Goolge Drive service object.
:param: v (string): Version of Tor Browser to look for.
"""
windows_re = 'torbrowser-install-%s_\w\w(-\w\w)?\.exe(\.asc)?' % v
linux_re = 'tor-browser-linux\d\d-%s_(\w... | 7,607 |
def list_(context, field, mpd_query=None):
"""
*musicpd.org, music database section:*
``list {TYPE} [ARTIST]``
Lists all tags of the specified type. ``TYPE`` should be ``album``,
``artist``, ``date``, or ``genre``.
``ARTIST`` is an optional parameter when type is ``album``,
... | 7,608 |
def test_sort_values_within_attribute_invalid_product_type(
staff_api_client, permission_manage_product_types_and_attributes
):
"""Try to reorder an invalid attribute (invalid ID)."""
attribute_id = graphene.Node.to_global_id("Attribute", -1)
value_id = graphene.Node.to_global_id("AttributeValue", -1)
... | 7,609 |
def palindrome(d: int)-> str:
"""
Function is getting the digits of the number, left shifting it by multiplying
it with 10 at each iteration and adding it the previous result.
Input: Integer
Output: String (Sentence telling if the number is palindrome or not)
"""
remainder = 0
revnum = 0... | 7,610 |
def main():
"""
Converting the JSON Data to Parquet
"""
inputs = "./raw_data/"
for file in os.listdir(inputs):
if file[-5:] == ".json":
df = spark.read.json(inputs + file)
df.write.parquet("./raw_data/parquet/{}".format(file[:-5]))
pass | 7,611 |
def import_from_file(request):
"""
Import a part of a source site's page tree via an import of a JSON file
exported to a user's filesystem from the source site's Wagtail Admin
The source site's base url and the source page id of the point in the
tree to import defined what to import and the destina... | 7,612 |
def teqc_version():
"""
return string with location of teqcexecutable
author: kristine larson
"""
exedir = os.environ['EXE']
gpse = exedir + '/teqc'
# heroku version should be in the main area
if not os.path.exists(gpse):
gpse = './teqc'
return gpse | 7,613 |
def graph_search(problem, verbose=False, debug=False):
"""graph_search(problem, verbose, debug) - Given a problem representation
attempt to solve the problem.
Returns a tuple (path, nodes_explored) where:
path - list of actions to solve the problem or None if no solution was found
nodes_explored - ... | 7,614 |
def _build_groupby_indices(df, table_name, join_columns):
"""
Pre-computes indexes based on the group-by columns.
Returns a dictionary of tuples to the list of indices.
"""
log.info("Grouping table '{}' by: {}.".format(table_name,
", ".join(join_colu... | 7,615 |
def test_print_warning_message_for_non_declared_skill_components():
"""Test the helper function '_print_warning_message_for_non_declared_skill_components'."""
with unittest.mock.patch.object(
aea.skills.base._default_logger, "warning"
) as mock_logger_warning:
_print_warning_message_for_non_... | 7,616 |
def add_multiple_package(package_list: List[str]) -> str:
"""
Generate latex code to add multiple package to preamble
:param package_list: List of package to add in preamble
"""
usepackage_command_list = []
for package in package_list:
usepackage_command_list.append(rf"""\usepackage{{{p... | 7,617 |
def emailAdmins(msgData):
"""
Emails all admins with given message. States which admin created/is sending the message to everyone.
Return: {bool}
"""
from metrics.models import Group
try:
if not msgData['msg']:
print('No message was provided to send.')
return False
admins = list(Group.objects.get(n... | 7,618 |
def add(isamAppliance, name, chainItems=[], description=None, check_mode=False, force=False):
"""
Create an STS chain template
"""
if force is False:
ret_obj = search(isamAppliance, name)
if force is True or ret_obj['data'] == {}:
if check_mode is True:
return isamApplia... | 7,619 |
def MinHamDistance(pattern, dna_list):
"""Calculate the minimum Hamming distance from a DNA list."""
return sum(HammingDistanceDiffLen(pattern, sequence) for sequence in
dna_list) | 7,620 |
def _add_note(text: str, user: KarmaUser) -> str:
"""Adds a new note to the database for the given user."""
_, note_msg = _parse_note_cmd(text)
if not note_msg:
return f"Sorry {user.username}, could not find a note in your message."
if _note_exists(note_msg, user):
return f"Sorry... | 7,621 |
def get_next_method(generator_instance):
"""
Cross-platform function that retrieves the 'next' method from a generator
instance.
:type generator_instance: Any
:rtype: () -> Any
"""
if sys.version_info > (3, 0):
return generator_instance.__next__
else:
return generator_ins... | 7,622 |
def process_line(this_line, do_stemming=False, remove_stopwords=False):
"""
Given a line from the CSV file, gets the stemmed tokens.
"""
speech = process_csv_line(this_line)
speech_tokens = process_raw_speech_text(speech.contents, perform_stemming=do_stemming,
... | 7,623 |
def kill_action(args):
"""Entry point for the 'kill' cli command."""
kill_app(args.app_name, args.sigkill_timeout) | 7,624 |
def metadef_tag_count(context, namespace_name):
"""Get metadef tag count in a namespace"""
namespace = metadef_namespace_get(context, namespace_name)
_check_namespace_visibility(context, namespace, namespace_name)
count = 0
for tag in DATA['metadef_tags']:
if tag['namespace_id'] == namespa... | 7,625 |
def act2graph(graph: Graph, xml_root: Xml, registry: dict,
namespaces: dict, tag: str) -> Graph:
""" Transform activityName tag into RDF graph.
The function transforms the Activity MasterData into identifier. The output
is a RDF graph that represents a part of the Ecoinvent nomenclature
s... | 7,626 |
def test_complex004_complex004_v2_xml(mode, save_output, output_format):
"""
xsi:type default Default value for xsi:type is allowed but ignored
"""
assert_bindings(
schema="saxonData/Complex/complex004.xsd",
instance="saxonData/Complex/complex004.n2.xml",
class_name="Root",
... | 7,627 |
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(norm_address)))
checksum_address = add_0x_prefix(
"".join(
... | 7,628 |
def is_volatile(type):
"""returns True, if type represents C++ volatile type, False otherwise"""
nake_type = remove_alias(type)
return isinstance(nake_type, cpptypes.volatile_t) | 7,629 |
def load_adult(as_frame: bool = False):
"""Load and return the higly imbalanced binary classification [adult income datatest](http://www.cs.toronto.edu/~delve/data/adult/desc.html).
you may find detailed description [here](http://www.cs.toronto.edu/~delve/data/adult/adultDetail.html)
"""
with resources... | 7,630 |
def sam(
body: Optional[Union[bool,Callable]] = json.loads,
pathParams: Optional[Union[bool,Callable]] = False,
queryString: Optional[Union[bool,Callable]] = False,
headers: Optional[Union[bool,Callable]] = False,
authenticate: Optional[Callable[[dict], types.AuthUser]] = None,
authorize: Option... | 7,631 |
def get_logger(name=None):
"""return a logger
"""
global logger
if logger is not None: return logger
print('Creating logger========================================>')
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
sh = logging.StreamHandler()
sh.setLevel(logging.INFO)... | 7,632 |
def LF_degen_spine(report):
"""
Checking for degenerative spine
"""
reg_01 = re.compile('degen',re.IGNORECASE)
reg_02 = re.compile('spine',re.IGNORECASE)
for s in report.report_text.text.split("."):
if reg_01.search(s) and reg_02.search(s):
return ABNORMAL_VAL
return ABST... | 7,633 |
def make_log_format(fields, sep=" - "):
"""
Build a custom log format, as accepted by the logging module, from a list of field names.
:param fields: list or tuple of str - names of fields to use in log messages
:param sep: str - separator to put between fields. Default is ' - '
:return: a log format... | 7,634 |
def tweets_for(type, args, per_user=None):
"""
Retrieve tweets for a user, list or search term. The optional
``per_user`` arg limits the number of tweets per user, for
example to allow a fair spread of tweets per user for a list.
"""
lookup = {}
lookup[type] = args[0].strip("\"'")
tweets... | 7,635 |
def sum_var(A):
"""summation over axis 1 (var) equivalent to np.sum(A, 1)"""
if issparse(A):
return A.sum(1).A1
else:
return np.sum(A, axis=1) if A.ndim > 1 else np.sum(A) | 7,636 |
def success_schema():
"""Pytest fixture for successful SchemaModel object"""
scm = SchemaVersion("1.0")
scm.success = True
return scm | 7,637 |
def _interfaces(config):
""" list system interfaces based on shape """
shape = lib.metadata.get_instance()['shape']
print
if config.getboolean('DEFAULT', 'auto') is True:
interfaces = lib.interfaces.get_interfaces_by_shape(shape)
else:
interfaces = config['DEFAULT']['interfaces']... | 7,638 |
def getColumninfo(columns):
"""
See ElementFaceToThickness.
"""
ColumnC, problematicColumns = ElementFaceToThickness(columns)
return ColumnC | 7,639 |
def main(tokens, directory, output_file, dry_run, offsets, is_regex, case_sensitive, export_clips, export_clips_dir, export_clips_template):
"""A tool for finding quotes in series/movies/animes and automatically creating compilations.
\b
Examples:
$ quoteclipper -match Hello .
$ quoteclipper -m "Mo... | 7,640 |
def script(
command: str, inputs: Any = [], outputs: Any = NULL, tempdir=False, **task_options
) -> Any:
"""
Execute a shell script as a redun task with file staging.
"""
if outputs == NULL:
outputs = File("-")
command_parts = []
# Prepare tempdir if requested.
temp_path: Optio... | 7,641 |
def get_forms(console: Console, sess: requests.Session, form_id: str = "General_Record_2020v2.0"):
"""
Method to get every form for a given FormID
"""
raw_resp = get_url(url=f"https://forms.agterra.com/api/{form_id}/GetAll/0", sess=sess)
if raw_resp.status_code != 200:
console.log(f"[red] S... | 7,642 |
def record_available_username(username):
"""
Notify the user of a valid username and write it to
./available-usernames.txt
"""
log.info("Name %s is available!", username)
available_usernames.append(username)
print(f"{available_usernames=}")
with open(
f"{script_dir}/available-us... | 7,643 |
def load_dataset(input_files,
input_vocab,
mode,
batch_size=32,
min_seq_len=5,
num_buckets=4):
"""Returns an iterator over the training data."""
def _make_dataset(text_files, vocab):
dataset = tf.data.TextLineDataset(te... | 7,644 |
def _get_results(**kwargs):
"""
Generate a command with the parameters, run it, and return the
normalized results
"""
output, error, rc = testoob.run_cmd.run_command(_generate_command(**kwargs))
return tt._normalize_newlines(output), tt._normalize_newlines(error), rc | 7,645 |
def main():
"""
This program simulates a bouncing ball at (START_X, START_Y)
that has VX as x velocity and 0 as y velocity. Each bounce reduces
y velocity to REDUCE of itself.
"""
ball.filled = True
window.add(ball)
onmouseclicked(star_ball) | 7,646 |
def infer_from_discretized_mix_logistic(params):
"""
Sample from discretized mixture of logistic distributions
Args:
params (Tensor): B x C x T, [C/3,C/3,C/3] = [logit probs, means, log scales]
Returns:
Tensor: sample in range of [-1, 1].
"""
log_scale_min = float(np.log(1e-14))
... | 7,647 |
def init_api_owners(init_owners):
"""Converts the ``DbOwns`` lists created by ``init_owners`` into lists
of dicts that can be used to test the responses of the API endpoints."""
api_owners = {}
for k, v in init_owners.items():
api_owners[k] = [
OwnsResp.from_dbowns(o).__dict__ for o ... | 7,648 |
def get_sorted_file_paths(file_path, file_extension=None, encoding=None):
"""
Sorts file paths with numbers "naturally" (i.e. 1, 2, 10, a, b), not
lexiographically (i.e. 1, 10, 2, a, b).
:param str file_path: File containing file_paths in a text file,
or as a list.
:param str file_extension: Opt... | 7,649 |
def _process_window(output_arrays: dict, entries_for_inter, trial_key: str,
crash_cutoff: Union[float, np.float], sampling_rate: int,
episode_id: int) -> None:
"""
helper function to interpolate entries in a window and record output
:param output_arrays:
:param en... | 7,650 |
def _load_reft_data(reft_file, index_name="btl_fire_num"):
"""
Loads reft_file to dataframe and reindexes to match bottle data dataframe
"""
reft_data = pd.read_csv(reft_file, usecols=["btl_fire_num", "T90", "REFTMP_FLAG_W"])
reft_data.set_index(index_name)
reft_data["SSSCC_TEMP"] = Path(reft_fi... | 7,651 |
def commit_veto(environ, status, headers):
"""Veto a commit.
This hook is called by repoze.tm in case we want to veto a commit
for some reason. Return True to force a rollback.
By default we veto if the response's status code is an error code.
Override this method, or monkey patch the instancemeth... | 7,652 |
def rate_limited_api(view_func):
"""
Checks users last post to rate limited endpoints
(adding comments or recipes) and rejects if within timeout period
for api requests (returns JSON response)
"""
@wraps(view_func)
def _wrapped_view(request, *args, **kwargs):
exceeded, msg = reques... | 7,653 |
def SecondOrderTVD(Uo, Courant, diffX, LimiterFunc, Limiter, Eps=0.01):
"""Return the numerical solution of dependent variable in the model eq.
This function uses the
explicit second-order TVD method and their various
Limiter functions and Limiters
to obtain the solution of the 1D non-linear ... | 7,654 |
def login_required(func):
""" Allow only auth users """
async def wrapped(self, *args, **kwargs):
if self.request.user is None:
add_message(self.request, "LogIn to continue.")
redirect(self.request, "sign_in")
return await func(self, *args, **kwargs)
return wrapped | 7,655 |
def splitter(iterable, sizes):
"""Split an iterable into successive slice by sizes.
>>> list(splitter(range(6), [1, 2, 3]))
[[0], [1, 2], [3, 4, 5]]
"""
iterator = iter(iterable)
for size in sizes:
yield list(it.islice(iterator, size)) | 7,656 |
def _hunnyb_search_func(name):
"""search function required by ``codecs.register``"""
if name in (HUNNYB_ENC_NAME,) + HB_ALIASES:
return (_encode, _decode, None, None) | 7,657 |
def fingerprint_file(file):
"""Open, read file and calculate MD5 on its contents"""
with open(file,'rb') as fd:
# read contents of the file
_file_data = fd.read()
# pipe contents of the file through
file_fingerprint = md5(_file_data).hexdigest()
return file_fingerprint | 7,658 |
def reset_color_info(*event):
"""Remove the values from the color info frame.
This function will be called when no items on the Treeview are selected.
"""
global previous_sd, current_sd
cell_spectrum_title["text"] = "Please select or add a spectrum to display its color coordinate"
cell_x_va... | 7,659 |
def toOTLookup(self, font, ff):
"""Converts a fontFeatures.Routine object to binary.
Args:
font: A ``TTFont`` object.
ff: The parent ``FontFeatures`` object containing this routine.
Returns a list of ``fontTools.otlLib.builder`` Builder objects allowing this
routine to be converted to ... | 7,660 |
def test_paragraph_series_m_hb_ol_t_nl_i3_ol_nl_i2_hb():
"""
Test case: Ordered list text newline indent of 3 ordered list newline indent of 2 html block
"""
# Arrange
source_markdown = """1. abc
1.
<script>
foo
</script>
"""
expected_tokens = [
"[olist(1,1):.:1:3:: ]",
... | 7,661 |
def test___init__username():
""" Will test __init__ function if username is provided.
:return:
"""
with pytest.raises(ValueError) as excinfo:
syn = syncope.Syncope(syncope_url="http://192.168.1.145:9080", password="admin")
assert excinfo.value.message == 'This interface needs an username to... | 7,662 |
def apply_to_all(func, results, datasets):
"""Apply the given function to all results
Args:
func: the function to apply
results: nested dictionary where the nested levels are: algorithm name, sensitive attribute
and split ID
datasets: nested dictionary where the nested ... | 7,663 |
def any_value_except(mapping, excluded_keys):
"""Return a random value from a dict that is not associated with
excluded_key. Raises StopIteration if there are no other keys than
excluded_key"""
return next(mapping[key] for key in mapping if key not in excluded_keys) | 7,664 |
def one_hot(y, num_dim=10):
"""
One Hot Encoding, similar to `torch.eye(num_dim).index_select(dim=0, index=y)`
:param y: N-dim tenser
:param num_dim: do one-hot labeling from `0` to `num_dim-1`
:return: shape = (batch_size, num_dim)
"""
one_hot_y = torch.zeros(y.size(0), num_dim)
if y.is... | 7,665 |
def relate(target_file, start_file):
"""
Returns relative path of target-file from start-file.
"""
# Default os.path.rel_path takes directories as argument, thus we need
# strip the filename if present in the paths else continue as is.
target_dir, target_base = os.path.split(target_file)
sta... | 7,666 |
def IdentityMatrix():
"""Creates an identity rotation matrix.
Returns a rotation matrix that has no effect on orientation.
This matrix can be the starting point for other operations,
such as using a series of calls to #Pivot to
create a custom rotation matrix.
Returns
-------
RotationM... | 7,667 |
def compute_K_from_vanishing_points(vanishing_points):
"""Compute intrinsic matrix given vanishing points.
Args:
vanishing_points: A list of vanishing points.
Returns:
K: The intrinsic camera matrix (3x3 matrix).
"""
# vanishing points used
v1 = vanishing_points[0]
v2 = vani... | 7,668 |
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
"""Set up the Insteon component."""
async_add_insteon_entities(
hass, DOMAIN, InsteonDimmerEntity, async_add_entities, discovery_info
) | 7,669 |
def getProgFromFile(f):
"""Get program name from __file__.
"""
if f.endswith(".py"):
f = f[:-3]
return os.path.basename(f) | 7,670 |
def _tpd2vec(seq, dtype=float):
"""
Convert a tpd file string to a vector, return a NumPy array.
EXAMPLES:
>>> _tpd2vec('1|13|4; 20; 25|28')
array([ 1., 5., 9., 13., 20., 25., 26., 27., 28.])
>>> _tpd2vec('5.5; 1.2@3; 3|7|2')
array([ 5.5, 1.2, 1.2, 1.2, 3. , ... | 7,671 |
def get_notification_html(*, notification_type: str, options: Dict, sender: str) -> str:
"""
Returns the formatted html for the notification based on the notification_type
:return: A string representing the html markup to send in the notification
"""
validate_options(options=options)
url_base =... | 7,672 |
def rank(config, path, metric, revision_index, limit, threshold, descending):
"""
Rank command ordering files, methods or functions using metrics.
:param config: The configuration
:type config: :class:'wily.config.WilyConfig'
:param path: The path to the file
:type path ''str''
:param met... | 7,673 |
def step(parents: be.Population, fitness: be.Fitness) -> tuple:
"""
The step function defines how an algorithm generation will be conducted. This function must receive a population and
a fitness object and return another population. In this case we will define the parameters of the algorithm within
the ... | 7,674 |
def asset_dividend_record(self, **kwargs):
"""Asset Dividend Record (USER_DATA)
Query asset dividend record.
GET /sapi/v1/asset/assetDividend
https://binance-docs.github.io/apidocs/spot/en/#asset-dividend-record-user_data
Keyword Args:
asset (str, optional)
startTime (int, optiona... | 7,675 |
def copy(engine, fromm, to, project: 'Project'):
"""
Copy files from the hosts file system using a Docker container running root.
See AbstractEngine.path_copy for general usage.
"""
if not path_in_project(to, project):
raise PermissionError(f"Tried to copy into a path that is not within the ... | 7,676 |
def heuristic(node_1, node_2):
""" Heuristic when only 4 directions are posible (Manhattan) """
(x_node_1, y_node_1) = node_1
(x_node_2, y_node_2) = node_2
return abs(x_node_1 - x_node_2) + abs(y_node_1 - y_node_2) | 7,677 |
def exercise_2(inputs): # DO NOT CHANGE THIS LINE
"""
Output should be the name of the class.
"""
output = Party
return output # DO NOT CHANGE THIS LINE | 7,678 |
def undistort(img, mtx, dist):
"""Undistort an image using camera matrix and distortion coefficients"""
h, w = img.shape[:2]
# return undistorted image with minimum unwanted pixels. It's okay to remove some pixesl at image corners.
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w,h), 0, ... | 7,679 |
def get_order(order_id, sandbox=False):
"""Get a single order using the Sell Fulfillment API."""
return single_api_call('sell_fulfillment_get_order', order_id=order_id,
field_groups='TAX_BREAKDOWN', sandbox=sandbox) | 7,680 |
def extend_dict(x, *y):
"""Similar to Object.assign() / _.extend() in Javascript, using
'dict.update()'
Args:
x (dict): the base dict to merge into with 'update()'
*y (dict, iter): any number of dictionary or iterable key/value
pairs to be sequentially merged into 'x'. Skipped i... | 7,681 |
def open_browser(page=None, browser=None, force=False):
"""Open web browser to page."""
if not sys.stdin.isatty() and not force:
raise RuntimeError(
"[-] use --force to open browser when stdin is not a TTY")
if page is None:
raise RuntimeError("[-] not page specified")
which ... | 7,682 |
def ErrorCriteria(errors):
"""Monitor the number of unexpected errors logged in the cluster. If more than five
errors have occurred on the cluster during this time period, post an alert. Posts a
warning if between one and four errors have occurred.
"""
ERROR_ALERT_THRESHOLD = 5
alerts = []
warnings = []
... | 7,683 |
def bdnyc_skyplot():
"""
Create a sky plot of the database objects
"""
# Load the database
db = astrodb.Database('./database.db')
t = db.query('SELECT id, ra, dec, shortname FROM sources', fmt='table')
# Convert to Pandas data frame
data = t.to_pandas()
data.index = data['id']
... | 7,684 |
def test_image_link_592():
"""
Test case 592: (part 1) Collapsed:
"""
# Arrange
source_markdown = """![foo][]
[foo]: /url "title"
"""
expected_tokens = [
"[para(1,1):]",
"[image(1,1):collapsed:/url:title:foo::::foo:::::]",
"[end-para:::True]",
"[BLANK(2,1):]",
... | 7,685 |
def get_model_config(model_name, dataset, params):
"""Map model name to model network configuration."""
model_map = _get_model_map(dataset.name)
if model_name not in model_map:
raise ValueError('Invalid model name \'%s\' for dataset \'%s\'' %
(model_name, dataset.name))
else:
return... | 7,686 |
def post_search(request):
"""Allow text matching search. """
form = SearchForm()
query = None
results = []
if 'query' in request.GET: # check if result is submitted by looking for query
form = SearchForm(request.GET)
if form.is_valid():
query = form.cleaned_data['query']... | 7,687 |
def PrimacyCodingNumeric_receptor_activity_monte_carlo_numba_generator(conc_gen):
""" generates a function that calculates the receptor activity for a given
concentration generator """
func_code = receptor_activity_monte_carlo_numba_template.format(
CONCENTRATION_GENERATOR=conc_gen)
# make sure ... | 7,688 |
def subtoken_counts(proposed, ground_truth):
"""
Compute the number of precise tokens, proposed tokens and ground truth tokens
from two strings representing tokens.
"""
gt_subtokens = set(compute_subtokens(ground_truth))
proposed_subtokens = set(compute_subtokens(proposed))
precise_subtokens... | 7,689 |
def welcome():
""" Define welcome reply """
hello = random.choice(_HELLO_)
nick = random.choice(_NICK_NAME_)
welcome = random.choice(_WELCOME_)
proposal = random.choice(_PROPOSAL_)
return hello + " " + nick + ", " + welcome + " ! " + proposal + " ?" | 7,690 |
def EDCN(linear_feature_columns,
dnn_feature_columns,
bridge_type='attention_pooling',
tau=0.1,
use_dense_features=True,
cross_num=2,
cross_parameterization='vector',
l2_reg_linear=1e-5,
l2_reg_embedding=1e-5,
l2_reg_cross=1e-5,
... | 7,691 |
def test_no_pass_confirm(db_session, nopassconfirm_app):
"""Register without password confirm option."""
assert db_session.query(User).count() == 0
res = nopassconfirm_app.get('/register')
res.form['email'] = DEFAULT_USER['email']
res.form['password'] = DEFAULT_USER['password']
res = res.form.s... | 7,692 |
def cart_to_polar(arr_c):
"""Return cartesian vectors in their polar representation.
Parameters
----------
arr_c: array, shape (a1, a2, ..., d)
Cartesian vectors, with last axis indexing the dimension.
Returns
-------
arr_p: array, shape of arr_c
Polar vectors, using (radiu... | 7,693 |
def createList(listSize):
"""
Creates list block that creates input instances for each element and an output instance for connecting to
the resulting list. List size is limited to 300 elements. Larger lists will be truncated.
:param listSize: The size of the list of point inputs that will be created
... | 7,694 |
def get_ground_weather_one_place(dir_path):
""" 1地点の地上気象データを取得する
Args:
dir_path(string) : ディレクトリパス
Returns:
DataFrame : ファイルの読込結果
"""
# 地上気象データのファイル一覧取得
file_paths = read_csv.get_file_paths(dir_path)
# 気象データを読み込み、DataFrameに格納する
ground_df = None
for file_pa... | 7,695 |
def trash_description(spl, garbage, keyword, description="description_1"):
"""description_1 OR description_2"""
relocate = spl[spl[description].str.contains(keyword, na=False, regex=True)]
spl = spl[~spl[description].str.contains(keyword, na=False, regex=True)]
garbage = pd.concat([garbage, relocate], i... | 7,696 |
def to_gray_example():
"""Show an example of the to_gray function."""
print('\n' + '=' * 42)
print("""print(to_gray('#FFFFFF'))
print(to_gray('#000000'))
print(to_gray('#435612'))
print(to_gray('#130303'))
print(to_gray('#777787'))
print(to_gray('#808080'))
print(to_gray('#A9A9A9'))""")
print('-' * 42)
... | 7,697 |
def run_analysis(
model,
target,
metric='integral',
style='barplot',
excluded_params=[]
):
"""
Perform sensitivity analysis to identify critical parameters, species or
reactions in the complex biological network.
The sensitivity S(y,x) was calculated according to... | 7,698 |
def update_job(**kwargs):
"""Update job.
Keyword arguments:
id -- Job ID
summary -- Job summary
location -- Location job was advertised
programs -- Programs the job is specified for
levels -- Levels job is intended for [Junior, Intermediate, Senior]
openings -- Number of job openings
... | 7,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.