content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def upload_secrets(secrets: 'dict[str,str]', base_url: str, header: 'dict[str, str]') -> None:
"""Uploads encrypted secret to github repo
Args:
secrets (dict[str,str]): Secret to be uploaded
base_url (str): The url to the repo
header (dict[str,str]): Header with auth tok... | 66,700 |
def calculate_percentages(df: pd.DataFrame,
numer_columns: list,
denom_column: str = 'total',
column_name_add: str = 'percent_') -> pd.DataFrame:
"""Convenience function to calculate percentages based on counts data
By default the cor... | 66,701 |
def test_docs_by_author4(flask_client, user0):
"""docs_by_author() displays login/signup page if user not logged in."""
response = flask_client.get("/all/author/2", follow_redirects=True)
assert b"Welcome!" in response.data | 66,702 |
def image_to_array(img_path:str):
"""
Convert image to numpy array
Paramenter:
img_path: str - Path to the image
Returns:
array: numpy.ndarray - The array converted from the image
"""
image = Image.open(str(img_path))
return np.array(image) | 66,703 |
def test_list_time_min_length_4_nistxml_sv_iv_list_time_min_length_5_3(mode, save_output, output_format):
"""
Type list/time is restricted by facet minLength with value 10.
"""
assert_bindings(
schema="nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-minLength-5.xsd",
instan... | 66,704 |
def calc(keep_stock_threshold,buy_change_threshold):
"""
:param keep_stock_threshold: 持股天数
:param buy_change_threshold: 下跌买入阀值
:return: 盈亏情况,输入的持股天数,输入的下跌买入阀值
"""
#实例化TradeStrategy2
trade_strategy2 = trade_strategy.TradeStrategy2()
#通过类方法设置买入后的持股天数
trade_strategy.TradeStrategy2.set_... | 66,705 |
def liquidation():
"""清算"""
rps = {}
rps["status"] = True
if request.form.get("token"):
token = request.form["token"]
liq_date = request.form["check_date"]
price_dict = {}
if request.form.get("price_dict"):
price_dict = request.form["price_dict"]
... | 66,706 |
def _do_get_latest_featuregroup_version(featuregroup, featurestore_metadata):
"""
Utility method to get the latest version of a particular featuregroup
Args:
:featuregroup: the featuregroup to get the latest version of
:featurestore_metadata: metadata of the featurestore
Returns:
... | 66,707 |
async def get_user_info(
storage: StorageInterface = Depends(StorageInterface),
) -> models.UserInfo:
"""Get info about the current user"""
with storage.start_transaction() as st:
out: models.UserInfo = st.get_user()
return out | 66,708 |
def update_one_contribute_score(user_total_click_num):
"""
item cf update sim contribution score by user
"""
return 1/math.log10(1+user_total_click_num) | 66,709 |
def mel_spec(audio, sample_rate, window_stride=(160, 80), fft_size=512, num_filt=20):
"""Calculates mel spectrogram (condensed spectrogram)"""
spec = power_spec(audio, window_stride, fft_size)
return safe_log(np.dot(spec, filterbanks(sample_rate, num_filt, spec.shape[1]).T)) | 66,710 |
def test1_feasible_actions():
"""
Method for preparing the feasible actions for the movie booking data set
"""
# all of the request slots the agent can pick
sys_request_slots = ['moviename', 'theater', 'starttime', 'date', 'numberofpeople', 'genre', 'state', 'city', 'zip',
... | 66,711 |
def _init_env():
"""Initialize ODBC env handle
Maybe add some more settings here, connection pooling etc.
"""
if sys.platform == 'darwin':
api = ctypes.cdll.LoadLibrary('libodbc.2.dylib')
else:
api = ctypes.cdll.LoadLibrary('libodbc.so')
env_h = ctypes.c_void_p()
rc = api.SQL... | 66,712 |
def get_percent_alloc(values):
"""
Determines a portfolio's allocations.
Parameters
----------
values : pd.DataFrame
Contains position values or amounts.
Returns
-------
allocations : pd.DataFrame
Positions and their allocations.
"""
return values.divide(
... | 66,713 |
def Multi30k(root, split,
task='task1',
language_pair=('de', 'en'),
train_set="train",
valid_set="val",
test_set="test_2016_flickr"):
"""Multi30k Dataset
The available datasets include following:
**Language pairs (task1)**:
+-----+-----... | 66,714 |
def load_user_history(user):
"""Loads the user's weight history as an attribute of the user instance."""
sql_statement = (''' SELECT
ID, DATE, WEIGHT from WEIGHT_HISTORY
where PERSON_ID = ?''')
data = execute_sql_statement(create_connection(), sql_statemen... | 66,715 |
def initialize():
"""
Initialize mongodb and s3
:return:
"""
log.info("Initializing database")
collection = mongodb_client.get_database("resman").get_collection("spider_jav")
collection.create_index([("time", pymongo.DESCENDING)])
collection.create_index([("published", pymongo.ASCENDING)... | 66,716 |
def test_parkinson_volatility(
dollar_bar_dataframe: pd.DataFrame, index_to_check: int, window: int
):
"""
Checks if output of transformer is similar to manual calculation.
"""
parkison_volatility_transformer = ParkinsonVolatility(window)
parkinson_constant = 1 / (4 * np.log(2))
high = dolla... | 66,717 |
def server_static(filepath):
"""Defina a Root para os ficheiros estaticos"""
return static_file(filepath, root='/var/www/core/static') | 66,718 |
def create_rdl_data_config(db_name: str):
"""Create rdl-data config files. Target specified DB."""
r_conn.switch_db(db_name)
generate_config(r_conn.settings, db_name) | 66,719 |
def author():
"""
Welcome to author, an easy way to configure your git
""" | 66,720 |
def write_maps(fmap_info):
"""
Overwrite the fieldmap JSON files.
:param dict fmap_info: Fieldmap metadata, from :func:`match_maps`
"""
for fmap, info in fmap_info.items():
with open(fmap, 'w+') as fp:
info['IntendedFor'] = info.pop('NewIntendedFor')
json.dump(info, ... | 66,721 |
def check_send_files(logger):
"""
Sends all queued files to the Bouldair server for the website.
:param logger: logging logger to record to
:return: bool, True if ran correctly, False if exit on error
"""
logger.info('Running check_send_files()')
try:
engine, session = connect_to_d... | 66,722 |
def get_summary_level_config(dataset: str, q_variable: str, api_key: str = '', force_fetch: bool = False) -> dict:
"""Computes a list of summary levels available, their dependencies and list of required geo IDs for API calls.
Args:
dataset: Dataset of US census(e.g. acs/acs5/subject).
... | 66,723 |
def set_virtual_cpus_to_at_least(num_virtual_cpus):
"""Create virtual CPU devices if they haven't yet been created."""
if num_virtual_cpus < 1:
raise ValueError("`num_virtual_cpus` must be at least 1 not %r" %
(num_virtual_cpus,))
physical_devices = config.list_physical_devices("CPU"... | 66,724 |
def create_embeddings_mapping(X_train_tokenized, X_test_tokenized, debug=False):
"""create the mapping from each token to its index
Arguments:
X_train_tokenized {DataFrame} -- train set
X_test_tokenized {DataFrame} -- test set
Keyword Arguments:
debug {bool} -- print debug ... | 66,725 |
def get_used_namespace(project_id):
"""通过应用实例获取使用的命名空间"""
# 通过project_id查询模板集信息
all_tmpl = Template.objects.filter(project_id=project_id).values("id")
tmpl_id_list = [info["id"] for info in all_tmpl]
ns_id_info = VersionInstance.objects.filter(
is_deleted=False, is_bcs_success=True, template... | 66,726 |
def parse_args():
"""Argument parser."""
parser = argparse.ArgumentParser(description='Argument parser for AUPR-in/AUPR-out evaluations.')
parser.add_argument('--algo_name', type=str, default='e3outlier-0.1')
parser.add_argument('--positive', type=str, default='inliers', choices=['inliers', 'outliers'],... | 66,727 |
def random_transform(im, gt, target_shape, saturation_range=None, value_range=None,
brightness_range=None, contrast_range=None, blur_params=None, flip_lr=False,
rotation_range=None, shift_range=None, zoom_range=None, ignore_label=0):
"""
Applies a list of transforma... | 66,728 |
def is_excluded_path(args, filepath):
"""Returns true if the filepath is under the one of the exclude path."""
# Try regular expressions first.
for regexp_exclude_path in args.regexp:
if re.match(regexp_exclude_path, filepath):
return True
abspath = os.path.abspath(filepath)
if a... | 66,729 |
def process_universities_file(cur, filepath):
"""
- Read universities file.
- Process universities data.
- Insert data in sessions table using universities_table_insert query.
"""
# open courses file
df = pd.read_json(filepath, orient='records')
# open courses file
... | 66,730 |
def iterate_fields(fields, schema):
"""Recursively iterate over all DictField sub-fields.
:param fields: Field instance (e.g. input)
:type fields: dict
:param schema: Schema instance (e.g. input_schema)
:type schema: dict
"""
schema_dict = {val['name']: val for val in schema}
for field... | 66,731 |
def getSurvivedStatus(survivedStatus):
"""
---> Select survived passengers depending on status 0 or 1
<--- Return encoded list as a JSON payload with passengers data
"""
filterQuery = session.query(Titanic).filter(Titanic.Survived==survivedStatus).all()
survivedList = []
for i in filterQuer... | 66,732 |
def read_vertices(filename):
"""
Load VERTICES segment from a VTK file (actually indices to vertices).
Parameters
----------
filename : string
The path/filename of a VTK format file.
Returns
-------
indices : a list of integers
Each element is an integer defined in the ... | 66,733 |
def logout_auth():
"""
This function is used for logged in user to logout. Clear all session data
:return: if successful return status 1
"""
session.clear()
return jsonify({"status": 1}) | 66,734 |
def image_diff_threshold() -> float:
"""
Set default threshold differences of images. By default - 0.001
"""
return 0.1 | 66,735 |
def time_call(func, setup=None, maxtime=1, bestof=3):
"""
timeit() wrapper which tries to get as accurate a measurement as possible w/in maxtime seconds.
:returns:
``(avg_seconds_per_call, log10_number_of_repetitions)``
"""
from timeit import Timer
from math import log
timer = Timer... | 66,736 |
def ustr(string):
"""
Returns the Python version relevant string type
"""
try:
return unicode(string)
except NameError:
return str(string) | 66,737 |
def step_impl(context):
"""
:type context: behave.runner.Context
"""
raise NotImplementedError(u'STEP: Then I receive valid HTTP response code 201') | 66,738 |
def test_update_physical_resource_id_missing(create_lambda_event):
"""
GIVEN CloudFormation update request without physical resource id
WHEN lambda_handler is called with the request
THEN MalformedEventError is raised.
"""
event = {**create_lambda_event, "RequestType": "Update"}
with pytest... | 66,739 |
def get_blender_mesh_shape_key(me):
"""Return main shape deformer's key."""
return "|".join((get_blenderID_key(me), "Shape")) | 66,740 |
def _entry_morphophonemics_annotation_is_valid(entry: _LexiconEntry) -> None:
"""Checks if entry has a morphophonemics annotation if it is a compound."""
compound = _is_compound_of(entry)
morphophonemics = _morphophonemics_of(entry)
if compound == "true" and morphophonemics == "~":
raise InvalidLexiconEntr... | 66,741 |
def generate_STS_distance_matrix(slope_matrix, nthreads=4):
"""Takes in the slope matrix and returns the distance matrix. Uses parallel
processing.
Parameters
----------
slope_matrix: np.matrix
Matrix of the time-series slopes, produced by calculate_slopes()
nthreads: int
Number... | 66,742 |
def binary_peirce_score(target_tensor, forecast_probability_tensor):
"""Returns binary Peirce score.
:param target_tensor: See docstring for the 2 possible formats.
:param forecast_probability_tensor: Same.
:return: binary_peirce_score: Binary Peirce score.
"""
return (
binary_pod(targ... | 66,743 |
async def test_options(hass: HomeAssistant) -> None:
"""Test reconfiguring."""
input_sensor1_entity_id = "sensor.input1"
input_sensor2_entity_id = "sensor.input2"
# Setup the config entry
config_entry = MockConfigEntry(
data={},
domain=DOMAIN,
options={
"cycle": ... | 66,744 |
def add_until_10(node):
"""Sends num on the left port until it is greater than 10, then sends it
on the right port.
"""
num = 1
while num < 10:
node.send(num, None)
num = node.receive()["num"]
node.send(None, num) | 66,745 |
def addURL(g: rdflib.ConjunctiveGraph) -> rdflib.ConjunctiveGraph:
"""
Add a URL to the public permalink of the RKD website to each manuscript resource.
Args:
g: The graph object.
Returns:
The graph object with the URL added.
"""
manuscripts = g.subjects(RDF.type, SCHEMA.Manus... | 66,746 |
def erase_eb_cuda( Ex, Ey, Ez, Bx, By, Bz, Ntot ):
"""
Reset the arrays of fields (i.e. set them to 0)
Parameters
----------
Ex, Ey, Ez, Bx, By, Bz: 1d arrays of floats
(One element per macroparticle)
Represents the fields on the macroparticles
"""
i = cuda.grid(1)
if i ... | 66,747 |
def fit_and_check_correctness(pipeline: Pipeline,
data: Union[InputData, MultiModalData],
logger: Log, cache: Optional[OperationsCache] = None, n_jobs=1):
""" Test is initial pipeline can be fitted on presented data and give predictions """
try:
... | 66,748 |
def insertNodeAtPosition(head, data, position):
"""Function to insert a new node into a linked list at the specified index position
Args:
head (SinglyLinkedListNode): Head of the linked list
data (int): Data to store in the linked list
position (int): The position to store the new node
... | 66,749 |
def fase1():
"""
Render the fase1 template on the /fase1 route
"""
pagesClassIDs = {
"fase1": {
"bannertitle": [],
"subtitle": [],
"firstText": [],
"secondText": []
}
}
for key in pagesClassIDs["fase1"].keys():
pagesClassID... | 66,750 |
def dump_action(mid, action, log_dir):
"""
dump action
"""
filename = os.path.join(log_dir, "actions", "%d.pkl" % mid)
pickle.dump(action, open(filename, "wb")) | 66,751 |
def run_git_hook(cmd, param=[]):
"""Execute a hook if the hook exists."""
if verbose:
sys.stderr.write("Looking for hook: %s\n" % cmd)
sys.stderr.flush()
hooks_path = gitConfig("core.hooksPath")
if len(hooks_path) <= 0:
hooks_path = os.path.join(os.environ["GIT_DIR"], "hooks")
... | 66,752 |
def service(
valid: datetime = Query(None),
):
"""Replaced above."""
df = run(valid)
return deliver_df(df, "geojson") | 66,753 |
def get_corporations_corporation_id_assets(*,
corporation_id,
token,
if_none_match=None,
page='1'):
"""
:param corporation_id: An EVE corpor... | 66,754 |
def test_setup(jira):
"""Verify our fixture."""
assert jira | 66,755 |
def has_bytes_component(typ: Type, py2: bool = False) -> bool:
"""Is this one of builtin byte types, or a union that contains it?"""
typ = get_proper_type(typ)
if py2:
byte_types = {'builtins.str', 'builtins.bytearray'}
else:
byte_types = {'builtins.bytes', 'builtins.bytearray'}
if i... | 66,756 |
def parameters():
"""
Generate the platform-scenario test cases.
"""
exclude, include = read_skip_list()
number = 0
params = []
scenarios = [p.parent.name for p in Path().glob('molecule/*/molecule.yml')]
for p in PLATFORMS:
for s in scenarios:
name = '%s-%s' % (p, s)
... | 66,757 |
def dis(func):
"""
Disassemble a function into cpython_assembly format
"""
co = func.__code__
result = []
if func.__doc__:
for line in func.__doc__.splitlines():
result.append(line)
result.append(' :::asm')
result.append(' .stacksize {0}'.format(co.co_stacksiz... | 66,758 |
def test_example_app(example_app):
"""Test example app."""
cmd = 'FLASK_APP=app.py flask tokens create --name test_token' \
' --user info@inveniosoftware.org'
token = subprocess.check_output(cmd, shell=True).decode('utf-8').strip()
# search page
cmd = 'curl http://localhost:5000/search'
... | 66,759 |
def cluster(distance_matrix, threshold, linkage_method='weighted', show_result=False, file_id=None, den_label_size=9, mat_label_size=7, trim_indices=[]):
"""Computes the clustering solution for a distance matrix and threshold
Computes the linkages for a distance matrix using SciPy's hierarchical (agglomera... | 66,760 |
def get_length(token, negative=True, percentage=False):
"""Parse a <length> token."""
if percentage and token.type == 'percentage':
if negative or token.value >= 0:
return Dimension(token.value, '%')
if token.type == 'dimension' and token.unit in LENGTH_UNITS:
if negative or toke... | 66,761 |
def test_convergence_mpl():
"""
Test of the convergence_plot function with mpl backend
"""
from masci_tools.vis.common import convergence_plot
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(16, 6))
convergence_plot(CONVERGENCE_ITERATIONS,
CONVERGENCE_DISTANCES,
... | 66,762 |
def fixture_encode_vorbis():
"""fixture_encode_vorbis"""
wav_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"test_audio",
"ZASFX_ADSR_no_sustain.wav",
)
audio = tf.audio.decode_wav(tf.io.read_file(wav_path))
value = audio.audio * (1 << 15)
value = tf.cas... | 66,763 |
def delete_user(ctx, user_name: str):
"""Remove a user.
Parameter
---------
user_name : str
User name
.. note::
The following steps are performed.
#. Look up a user name in the user database
#. Ask whether a backup should be made (calls ``def backup_user``)
... | 66,764 |
def test_dashboard_changes(prepare_db):
"""Test that dashboard information changes."""
print(prepare_db['stderr'])
assert prepare_db['exit_code'] == 0
session = prepare_db['session']
dash = session.query(ReportDashboard).filter(ReportDashboard.id == 147).first()
assert dash.name == 'CRM - ... | 66,765 |
def test_outputs(head_track):
"""check that the renderer outputs are consistent"""
# ideally these would be separate tests, but we want to use the renderer
# outputs more than once (for individual reference tests, and multi-object
# tests), and this avoids re-calculating them
skips = []
ht = "... | 66,766 |
def structure_sampling2(graph, centrality, function, retain_factor):
""" Returns a graph view for the graph with close to retain_factor edges
centrality should have a function .get_values that returns the values for the centrality
function should be a function that takes two vectors where elements at the sa... | 66,767 |
def test_override_and_use_existing(tmpdir):
"""
Cannot have both the override and use_existing parameters set to True.
"""
kaldi = KaldiInterface(f'{tmpdir}/state')
with pytest.raises(ValueError):
kaldi.new_transcription('transcription_w', override=True, use_existing=True)
return | 66,768 |
def test_fast_noexceptions(nb_file, tmpdir, plt):
"""Ensure that no cells raise an exception."""
pytest.importorskip("IPython", minversion="1.0")
pytest.importorskip("jinja2")
assert_noexceptions(nb_file, tmpdir, plt) | 66,769 |
def atcab_aes_cbcmac_finish(ctx, mac, mac_size):
"""
Finish a CBC-MAC operation returning the CBC-MAC value. If the data
provided to the atcab_aes_cbcmac_update() function has incomplete
block this function will return an error code.
Args:
ctx AES-128 CBC-MAC context.
mac ... | 66,770 |
def make_wsgi_app(registry=REGISTRY):
"""Create a WSGI app which serves the metrics from a registry."""
def prometheus_app(environ, start_response):
# Prepare parameters
accept_header = environ.get('HTTP_ACCEPT')
params = parse_qs(environ.get('QUERY_STRING', ''))
if environ['PATH... | 66,771 |
def init():
"""Treadmill Websocket"""
@click.command()
@click.option('--fs-root',
help='Root file system directory to zk2fs',
required=True)
@click.option('-m', '--modules', help='API modules to load.',
required=True, type=cli.LIST)
@click.optio... | 66,772 |
def _tournament_selection(parents: Population, n: int, fitness_idx: int = 0, k: int = 2, w: int = 1,
replacement: bool = False):
"""
Tournament selection is an operator that doesn't require any global knowledge of the population, nor a quantifiable
measure of quality. In this case ... | 66,773 |
def setup(hass, config=None):
""" Sets up the HTTP API and debug interface. """
if config is None or DOMAIN not in config:
config = {DOMAIN: {}}
api_password = util.convert(config[DOMAIN].get(CONF_API_PASSWORD), str)
no_password_set = api_password is None
if no_password_set:
api_p... | 66,774 |
def format_latex(ss):
"""
Formats a string so that it is compatible with Latex.
:param ss: The string to format
:type ss: string
:return: The formatted string
:rtype: string
"""
tt = (str(ss).replace('_', ' ')
.replace('%', '\%')
)
r... | 66,775 |
def test_deepfool_attack_detection():
"""
Deepfool-Attack test
"""
net = Net2()
inputs1_np = np.random.random((2, 10, 10)).astype(np.float32)
inputs2_np = np.random.random((2, 10, 5)).astype(np.float32)
gt_boxes, gt_logits = net(Tensor(inputs1_np), Tensor(inputs2_np))
gt_boxes, gt_logits... | 66,776 |
def CheckForInstalledBinary(binary_name, custom_message=None):
"""Check if binary is installed and return path or raise error.
Prefer the installed component over any version found on path.
Args:
binary_name: str, name of binary to search for.
custom_message: str, custom message to used by
Missing... | 66,777 |
def get_by_ref(db_session: Session, *, ref: str) -> Optional[TriggerDB]:
"""Return trigger object based on trigger ref.
Arguments:
db_session {Session} -- SQLAlchemy Session object
ref {str} -- ref string
Returns:
Optional[TriggerDB] -- Returns a TriggerDB object or nothing if it d... | 66,778 |
def cross_entropy(output, labels, target=None):
"""
Compute the cross entropy between output and labels. Can do multiple examples at a time.
Dimensions of output and labels must match and the target collapses along the row axis
"""
if not target:
n = _cudanet.get_nonleading_dimension(outpu... | 66,779 |
def append_njson_first_lines(temp_data, file, max_bytes):
"""
Given a fine path 'file' and a maximum number of characters/bytes,
writes all lines in 'file' to temp file until the character/byte counts
surpasses 'max_bytes'.
"""
# Read first lines of file:
with open(file, 'r') as f:
... | 66,780 |
def list_tables(db, library, show_n_rows=False):
"""
List all tables in a given library with optional row count information
:param db: Database connection
:param library: Queries library
:param show_n_rows: Show number of rows
:return: None
"""
for table in db.list_tables(library):
... | 66,781 |
def CheckTreeIsOpen(input_api, output_api, url, closed, url_text):
"""Similar to the one in presubmit_canned_checks except it shows an helpful
status text instead.
"""
assert(input_api.is_committing)
try:
connection = input_api.urllib2.urlopen(url)
status = connection.read()
connection.close()
... | 66,782 |
def temporal_split(df,
start_year=2019,
start_month=6,
start_day=1,
end_year=2019,
end_month=8,
end_day=1):
"""
Starts with client_df,
returns DataFrame of clients labeled churn or not.
... | 66,783 |
def time_stats(df):
"""
Displays statistics on the most frequent times of travel, in the local timezone, when applicable
ARGS:
df - Pandas DataFrame containing city data filtered by month and day
Returns:
no data is returne dupon completion of the function
"""
# drop frist column of d... | 66,784 |
def sprint_timeline(bugs, sprint):
"""Print timeline block."""
timeline = []
history = get_history(bugs, sprint)
# Try to associate the change that added the sprint to the
# whiteboard with a comment.
for when, bug, who, removed, added in history:
reason = 'NO COMMENT'
for comm... | 66,785 |
def xa(db_url, metadata=None):
"""
Provide a transactional scope around a series of database operations,
that commits on success and rolls back on error.
"""
if db_url.startswith('sqlite:'):
engine = sqlalchemy.create_engine(db_url, isolation_level='SERIALIZABLE')
else:
engine = ... | 66,786 |
def test_syllabi(mock_osp):
"""
Segment#syllabi() should generate Syllabus instances.
"""
path = mock_osp.add_segment('000')
segment = Segment(path)
# Add 10 files.
for i in range(10):
mock_osp.add_file(segment='000', name=str(i))
syllabi = segment.syllabi()
for i in ran... | 66,787 |
def _node(visuals, args, kwargs, level=0):
"""Recursive part of recursive Panel constructions"""
B, K = _broadcast(visuals, args, kwargs)
mk = _leaf if len(B) == 1 and Visual.isvisualable(B[0][0]) else _node # recursion
N, L = zip(*(mk(p, a, k, level+1) for p, a, k in B))
if level+1 < max(L)-1:
... | 66,788 |
def postprocess_multiline_shebang(filename):
"""
Try to rewrite the shebang of scripts. This function deals with
detecting whether the script is a shebang, and if so, rewrite it.
"""
if not os.path.isfile(filename) or not is_executable(filename):
return
with open(filename) as f:
... | 66,789 |
def compile():
"""
Compile external tools by calling make
"""
import sys
if len(sys.argv) < 2:
return
needs_build = False
for i in sys.argv[1:]:
if i in ["build", "build_ext", "build_clib", "install", "install_lib", "bdist", "bdist_rpm", "bdist_dumb", "bdist_wininst", "bdist... | 66,790 |
def best_solution_program(bundle: SpendBundle) -> SerializedProgram:
"""
This could potentially do a lot of clever and complicated compression
optimizations in conjunction with choosing the set of SpendBundles to include.
For now, we just quote the solutions we know.
"""
r = []
for coin_sol... | 66,791 |
def cleanup(bot, client, servers, print_all, leak):
"""Kills bot, kills server, print logs if failed, delete tmpdir."""
try:
try:
try:
if bot:
bot.stop(leak)
finally:
if servers:
servers.stop(leak)
finally:
if print_all:
if bot:
bot.dum... | 66,792 |
def test_sentence_piece_tokenizer_callable():
"""
Feature: SentencePieceTokenizer
Description: test SentencePieceTokenizer with eager mode
Expectation: output is equal to the expected value
"""
vocab = text.SentencePieceVocab.from_file([VOCAB_FILE], 100, 0.9995, SentencePieceModel.UNIGRAM, {})
... | 66,793 |
def os_aware(data: dict) -> dict:
"""
Makes data OS aware by changing all separators in file paths to match the current operating system.
:param data: JSON data.
:return: OS aware JSON data.
"""
for key, val in data.items():
if isinstance(val, dict):
data[key] = os_aware(val... | 66,794 |
def mock_engine_port(sim_def, attr_ref, attr_val):
"""Mock Engine gRPC server fixture that handles test requests"""
# define servicer that handles requests
class TestEngine(EngineServiceServicer):
def GetVersion(self, request, context):
return GetVersionResp(commit_hash="HASH12")
... | 66,795 |
def parseX(sol, *args):
"""Parse a sol into plotable piece"""
tX = np.reshape(sol[:25*4], (25, 4))
tU = np.reshape(sol[100: 100 + 2*24], (24, 2))
tf = sol[-1]
return tX, tU, tf | 66,796 |
def main():
"""
The entrypoint to the Piccolo CLI.
"""
# In case it's run from an entrypoint:
sys.path.insert(0, os.getcwd())
###########################################################################
# Run in diagnose mode if requested.
diagnose = get_diagnose_flag()
if diagnose:... | 66,797 |
def MatchingFileType(file_name, extensions):
"""Returns true if the file name ends with one of the given extensions."""
return bool([ext for ext in extensions if file_name.lower().endswith(ext)]) | 66,798 |
def process_data(path_to_folder, class_index):
"""process_data processes all data in a file and resizes it to IMG_WIDTH and IMG_HEIGHT and returns a list of
all images in the given folder
Args:
path_to_folder (str) : absolute path to the folder that contains all the images with backslash at the end
cla... | 66,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.