content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def silent_nan_np(f):
"""Decorator that silences np errors and returns nan if undefined.
The np.nanmax and other numpy functions will log RuntimeErrors when the
input is only nan (e.g. All-NaN axis encountered). This decorator silences
these messages.
Args:
f: function to decorate.
Retu... | 5,296,500 |
def evaluate_non_measured_estimation_tasks(
estimation_tasks: List[EstimationTask],
) -> List[ExpectationValues]:
"""This function evaluates a list of EstimationTask that are not
measured, and either contain only a constant term or require 0 shot.
Non-constant EstimationTask with 0 shot return 0.0 as th... | 5,296,501 |
def knapsack(p, v, cmax):
"""Knapsack problem: select maximum value set of items if total size not
more than capacity
:param p: table with size of items
:param v: table with value of items
:param cmax: capacity of bag
:requires: number of items non-zero
:returns: value optimal solution, lis... | 5,296,502 |
def identity(n, dtype='d', format=None):
"""Identity matrix in sparse format
Returns an identity matrix with shape (n,n) using a given
sparse format and dtype.
Parameters
----------
n : integer
Shape of the identity matrix.
dtype :
Data type of the matrix
format : strin... | 5,296,503 |
def test_nested_child_events():
"""Test that nested lists bubbles nested child events.
If you add an object that implements the ``SupportsEvents`` Protocol
(i.e. has an attribute ``events`` that is an ``EmitterGroup``), to a
``NestableEventedList``, then the parent container will re-emit those
even... | 5,296,504 |
def d2s(d):
"""
Date to string in friendly format, without time.
"""
return datetime.datetime.strftime(d, '%B %d, %Y') | 5,296,505 |
def refresh_content(username, password):
"""
Refresh the annoucements and resources for a user
Args:
username (String) : a UQ username to sign into blackboard and scrape
password (String) : the password for the UQ username's blackboard
Returns:
courses
"""
scraper = UQ... | 5,296,506 |
def adresa_inceput(netmask, ip):
"""
Ia un netmask si un IP si determina adresa de inceput
a retelei
:param (str) netmask:
:param (str) ip:
:return adresa_inceput (str):
"""
netmask_nums = netmask.split(".")
ip_nums = ip.split(".")
adresa_inceput = ""
for i in ra... | 5,296,507 |
def get_all_features(after_time_added=None):
"""
Args:
after_time_added: get all features that were added to the db after this date.
Returns:
"""
features = []
if after_time_added:
for feature in Feature.objects.exclude(feature_added_time__lt=after_time_added):
... | 5,296,508 |
async def explode(pos : Tuple[int, int], power : int, sub_exclusions : List[str] = [], npc_exclusions : List[int] = []):
"""
Makes an explosion in pos, dealing power damage to the centre square,
power-1 to the surrounding ones, power-2 to those that surround and
so on.
"""
from ALTANTIS.subs.sta... | 5,296,509 |
def ASBII(ATcur_P, ATxyz_P, ATxyz_K):
"""
| X | Astr. Azimuth , Zenith , Slope
| Y | ---------------+-------> from P to K distance distance
| Z |AT_P | (Apk) (Bpk) (Spk)
... | 5,296,510 |
def auto_build_socket(address):
"""Auto build a socket.socket instance from address"""
address_type = get_address_type(address)
if address_type == 'tcp':
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
elif address_type == 'uds':
sock = socket.socket(socket.AF_UNIX, socket.... | 5,296,511 |
def get_usage_data_labels(usage_data):
"""Return dict with human readable labels for each of the groups in each of the given usage data timeframes."""
labels = {}
timeframe_formats = {"day": "%H", "week": "%b %d", "month": "%b %d", "year": "%b %Y"}
for timeframe, timeframe_data in usage_data.items():
... | 5,296,512 |
def truncate_entry_titles(apps, schema_editor):
"""This function will truncate the values of Entry.title so they are
255 characters or less.
"""
Entry = apps.get_model("andablog", "Entry")
for entry in Entry.objects.all():
# Truncate to 255 characters (or less) but keep whole words intact.
... | 5,296,513 |
def test_node_to_table_xml_els():
"""We should be able to find a GPOTABLE in multiple places. Tagged_text is
can be an unescaped XML _fragment_"""
escaped_str = '<GPOTABLE unique="id">Content & stuff</GPOTABLE>'
unescaped_str = '<GPOTABLE unique="id">Content & stuff</GPOTABLE>'
nested_str = '<P>... | 5,296,514 |
def has_same_disk_several_positions(board):
"""
Check if the same disk appears multiple times on the same board
Returns True is there is one or are multiple appearances, False if not
"""
used_disks = list(board.values())
for pos in range(len(used_disks) - 1, -1, -1):
if ... | 5,296,515 |
def test_list_subcommands_has_all_scripts():
"""Tests if the output from running `fontbakery --list-subcommands` matches
the fontbakery scripts within the bin folder and the promoted profiles."""
import fontbakery.commands
from fontbakery.cli import CLI_PROFILES
commands_dir = os.path.dirname(font... | 5,296,516 |
def add_metadata(file):
"""This function merges two .txt files into one."""
data = data2 = ""
# Reading data from file1
with open('multinode_metadata_20200313.txt') as fp:
data = fp.read()
# Reading data from file2
with open('{}'.format(file)) as fp:
data2 = fp.read()
# Mer... | 5,296,517 |
def handle_client(connection: socket.socket, address: tuple):
"""Main function which creates a new thread for each client to handle"""
try:
log("SERVER", "New connection coming!")
if address[0] in get_config()['bans']:
connection.send(pickle.dumps({'banned': True}))
conn... | 5,296,518 |
def _get_temporal_props(ds: xr.Dataset) -> dict:
"""
Get temporal boundaries, resolution and duration of the given dataset. If
the 'bounds' are explicitly defined, these will be used for calculation,
otherwise it will rest on information gathered from the 'time' dimension
itself.
:param ds: Dat... | 5,296,519 |
def iconify_window(window):
"""
Iconifies the specified window.
Wrapper for:
void glfwIconifyWindow(GLFWwindow* window);
"""
_glfw.glfwIconifyWindow(window) | 5,296,520 |
def draft_file_resource():
"""Draft file resource."""
return DraftFileResource(
config=DraftFileResourceConfig,
service=Service(config=ServiceConfig)
) | 5,296,521 |
def make_models():
"""build all the models based on the arguments provided via absl
Returns: encoder_model, decoder_model, discriminator_model
"""
if FLAGS.model == "default" and FLAGS.training_method == "adaptive_st" or FLAGS.model == "adaptive_st":
logging.info("define adaptive_st model")
... | 5,296,522 |
def test_no_chromemanifest():
"""
Chrome manifest tests should not be run if there is no chrome manifest.
"""
err = ErrorBundle()
assert tc_chromemanifest.test_categories(err) is None
assert not err.failed()
err = ErrorBundle()
assert tc_chromemanifest.test_resourcemodules(err) is None
... | 5,296,523 |
def get_expression_parser(_: Environment) -> ExpressionParser:
"""Return an expression parser for the given environment."""
# Future proofing.
return STANDARD_EXPRESSION_PARSER | 5,296,524 |
async def _setup(hass, hass_ws_client, properties_data):
"""Set up tests."""
ws_client = await hass_ws_client(hass)
devices = MockDevices()
await devices.async_load()
devices.fill_properties("33.33.33", properties_data)
async_load_api(hass)
return ws_client, devices | 5,296,525 |
def run():
"""Set dates, variable names, and parameters to plot sensitivity."""
# run_type = 'NCEP_NCAR_MONTHLY_STJPV'
# run_type = 'NCEP_NCAR_DAILY_STJPV'
run_type = "ERAI_MONTHLY_THETA_STJPV"
dates = ('1979-01-01', '2018-12-31')
param_vals = {'pv_lev': np.arange(1.0, 4.5, 0.5),
... | 5,296,526 |
def reset_profiler_config_parser():
"""
The function resets the profiler config parser object.
This is necessary for test framework.
:return:
"""
global _profiler_config_parser
_profiler_config_parser = None | 5,296,527 |
def filter(function, iterable) -> object:
"""filter."""
if function is None:
return (item for item in iterable if item)
return (item for item in iterable if function(item)) | 5,296,528 |
def playmusic2(soundfile):
"""Stream music with mixer.music module using the event module to wait
until the playback has finished.
This method doesn't use a busy/poll loop, but has the disadvantage that
you neet to initialize the video module to use the event module.
Also, interrupting the... | 5,296,529 |
def red_car(red,lat):
"""
Convert reduced coordinates to cartesian
"""
return np.array(map( lambda coord: coord[0]*lat[0]+coord[1]*lat[1]+coord[2]*lat[2], red)) | 5,296,530 |
def _define_collect(batch_env, ppo_hparams, scope, frame_stack_size, eval_phase,
sampling_temp, force_beginning_resets):
"""Collect trajectories.
Args:
batch_env: Batch environment.
ppo_hparams: PPO hparams, defined in tensor2tensor.models.research.rl.
scope: var scope.
frame_st... | 5,296,531 |
def byte_at_a_time_ecb_decryption_harder(encryption_oracle):
"""Performs the byte-at-a-time ECB decryption attack to discover the secret padding used by the oracle."""
# Find the block length
block_length = find_block_length(encryption_oracle)
# To detect if the oracle encrypts with ECB mode, we can e... | 5,296,532 |
def cmk_arn_value():
"""Retrieves the target CMK ARN from environment variable."""
arn = os.environ.get(AWS_KMS_KEY_ID, None)
if arn is None:
raise ValueError(
'Environment variable "{}" must be set to a valid KMS CMK ARN for integration tests to run'.format(
AWS_KMS_KEY_... | 5,296,533 |
def data_cleaning(
data: pd.DataFrame,
drop_threshold_cols: float = 0.9,
drop_threshold_rows: float = 0.9,
drop_duplicates: bool = True,
convert_dtypes: bool = True,
col_exclude: Optional[List[str]] = None,
category: bool = True,
cat_threshold: float = 0.03,
cat_exclude: Optional[Lis... | 5,296,534 |
def _pmf_doc_name(doc):
"""Helper to generate document name for a ProceedingsMaterialFactory LazyAttribute"""
return 'proceedings-{number}-{slug}'.format(
number=doc.factory_parent.meeting.number,
slug=xslugify(doc.factory_parent.type.slug).replace("_", "-")[:128]
) | 5,296,535 |
def test_works_with_no_violations(scene: Dict[str, Any]) -> None:
"""
Tests drivable area violation metric, by checking the detection and the depth of violation on a made up scenario.
:param scene: the json scene
"""
history = setup_history(scene)
history.data = history.data[:2]
metric = Dr... | 5,296,536 |
def isWanted(client, date):
"""Check if the page of a date contains free time slots."""
loadDate(client, date)
times = getAvailableTimes(client.html)
ret = len(times) > 0
print('\tinspecting date', date, ', result =', 'available!!' if ret else 'full')
return ret | 5,296,537 |
def _get_counter_one(store: typing.Callable, item_key: ItemKey) -> int:
"""Returns count under exactly matched key.
"""
count = store.get(item_key.key)
return 0 if count is None else int(count) | 5,296,538 |
def print_hr_pot(tors_pots):
""" Check hr pot to see if a new mimnimum is needed
"""
print('\nHR potentials...')
for name in tors_pots:
print('- Rotor {}'.format(name))
pot_str = ''
for pot in tors_pots[name].values():
pot_str += ' {0:.2f}'.format(pot)
prin... | 5,296,539 |
def cron():
"""
Periodically fetches oldest pcap file to extract messages from.
"""
while True:
time.sleep(0.1)
try:
oldest = min(glob.iglob("{}/*.pcap".format(CONF['pcap_dir'])))
except ValueError as err:
logging.warning(err)
continue
... | 5,296,540 |
def wait_loading():
"""
Wait for selenium page to be ready
"""
return driver.execute_script('return document.readyState;') != 'complete' | 5,296,541 |
def tril(m, k=0):
"""
Returns a lower triangle of an array.
Returns a copy of an array with elements above the k-th diagonal zeroed.
Args:
m(array_like): The shape and data-type of a define these same
attributes of the returned array.
k(int, optional): Diagonal above which ... | 5,296,542 |
def save_persistent_data():
"""Persist data about the metadata plugin to a file"""
if PERSISTENCE_PATH:
try:
with open(os.path.join(PERSISTENCE_PATH,
PERSISTENCE_FILE), 'w') as f:
persist = {
SAVED_HOST_KEY: HOST,
... | 5,296,543 |
def distance(request):
"""
Compute the Euclidean distance using our package. Check that multithreading has no
effect on the result.
"""
kwargs = request.param
kwargs.update(DATASET_1)
return g.distance_pairwise(**kwargs) | 5,296,544 |
def modify_primer_file( infile, outfile ):
"""! @brief add subfix number to all primers """
counter = 0
mapping_table = {}
with open( outfile, "w" ) as out:
with open( infile, "r" ) as f:
line = f.readline()
while line:
if line[0] == ">":
if counter % 2 == 0:
name = line.strip()
out.w... | 5,296,545 |
def show_interface(dut, interface_name = None, cli_type="klish"):
"""
API to show sflow interface configuration
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param dut:
:return:
"""
output = list()
if cli_type == "klish":
command = "show sflow interface"
i... | 5,296,546 |
def calculate_totals():
"""Run the average workflow"""
scheduler = luigi.scheduler.Scheduler()
worker = luigi.worker.Worker(scheduler=scheduler, worker_processes=5)
averages = RunTotals()
with worker:
worker.add(averages)
worker.run()
print luigi.execution_summary.summary(wor... | 5,296,547 |
def format_currency(amount):
"""Convert float to string currency with 2 decimal places."""
str_format = str(amount)
cents = str_format.split('.')[1]
if len(cents) == 1:
str_format += '0'
return '{0} USD'.format(str_format) | 5,296,548 |
async def async_setup(hass, config) -> bool:
"""Initialize the Sure Petcare component."""
if DOMAIN not in config:
return True
hass.async_create_task(
hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_IMPORT},
data=conf... | 5,296,549 |
def test_calc_pixel_neighbors_square_diagonal():
"""
check that neighbors for square-pixel cameras are what we expect,
namely that the diagonals are included if requested.
"""
x, y = np.meshgrid(np.arange(20), np.arange(20))
cam = CameraGeometry(
camera_name="test",
pix_id=np.ar... | 5,296,550 |
def _build_module_validity_mat(module_names):
"""
Build a module validity matrix, ensuring that only valid modules will have
non-zero probabilities. A module is only valid to run if there are enough
attentions to be popped from the stack, and have space to push into
(e.g. _Find), so that stack will not underf... | 5,296,551 |
def get_plist_text(cf_bundler_identifier, cf_bundle_name=None,
docset_platform_family=None):
"""TODO"""
cf_bundle_name = cf_bundle_name or cf_bundler_identifier.upper()
docset_platform_family = docset_platform_family or cf_bundle_name.upper()
return """
<?xml version="1.0" encoding="UTF-8"?>
... | 5,296,552 |
def make_predictions(df):
"""
Uses the pycaret best model to make predictions on data in the df dataframe.
"""
model = load_model('churn_ada')
predictions = predict_model(model, data=df)
predictions.rename({'Label': 'Churn_prediction'}, axis=1, inplace=True)
predictions['Churn_predict... | 5,296,553 |
def _audio_to_embeddings_fn(kv, teacher_fn, output_dimension):
"""Map audio to teacher labels."""
samples = kv[SAMPLES_]
teacher_embeddings = teacher_fn(samples)
teacher_embeddings.shape.assert_has_rank(2)
teacher_embeddings.set_shape([None, output_dimension])
return {SAMPLES_: samples, TARGETS_: teacher_em... | 5,296,554 |
def _get_delay_time(session):
"""
Helper function to extract the delay time from the session.
:param session: Pytest session object.
:return: Returns the delay time for each test loop.
"""
return session.config.option.delay | 5,296,555 |
def req_send_restore():
"""Отправка сообщения для активации"""
temp = User.find_link(request.get_json())
data = {
'title': 'Восстановление пароля',
'button': 'Изменить',
'login': temp[0],
'link': "http://127.0.0.1:5000/restore/" + get_link(temp[1]),
'color': col[temp[... | 5,296,556 |
def discretize(df, nbins=10, cut=pd.qcut,
verbose=2, drop_useless=True):
"""Discretize columns in {df} to have at most {nbins} categories.
* Categorical columns: take the Top n-1 plus "Other"
* Continuous columns: cut into {nbins} using {cut}.
Returns a new discretized dataframe with... | 5,296,557 |
def verify_data_present():
"""Check that the already-notified database is there."""
if not os.path.isfile(CONFIG.get("dyknotifier", "ALREADY_NOTIFIED_FILE")):
print("Couldn't locate %s" % CONFIG.get("dyknotifier", "ALREADY_NOTIFIED_FILE"))
sys.exit(1) | 5,296,558 |
def get_flavor_kind(penalty):
"""
Gets the flavor kind of a penalty.
Parameters
----------
penalty: PenaltyConfig, PenaltyTuner
The penalty whose flavor we want to know.
Output
------
flavor_kind: None, str
The flavor; one of [None, 'adaptive', 'non_convex']
"""
... | 5,296,559 |
def test_account_with_recvWindow():
"""Tests the API endpoint to account information with recvWindow"""
client = Client(key, secret)
response = client.account(recvWindow=10000)
response.should.equal(mock_item) | 5,296,560 |
def is_overlapping_lane_seq(lane_seq1: Sequence[int], lane_seq2: Sequence[int]) -> bool:
"""
Check if the 2 lane sequences are overlapping.
Overlapping is defined as::
s1------s2-----------------e1--------e2
Here lane2 starts somewhere on lane 1 and ends after it, OR::
s1------s2-----... | 5,296,561 |
def get_dataset_from_code(code, batch_size):
""" interface to get function object
Args:
code(str): specific data type
Returns:
(torch.utils.data.DataLoader): train loader
(torch.utils.data.DataLoader): test loader
"""
dataset_root = "./assets/data"
if code == 'mnist':
... | 5,296,562 |
def make_uniform_edge_dataset(args):
""" Uniform edge-sampled dataset. """
def dataset_fn(graph_data, seed):
neighbours, lengths, offsets = tensorboard_hack(graph_data)
def _fn(s):
return dataset_ops.UniformEdgeDataset(
args.num_edges, neighbours=neighbours, lengths=... | 5,296,563 |
def output_handler(data, context):
"""Post-process TensorFlow Serving output before it is returned to the client.
Args:
data (obj): the TensorFlow serving response
context (Context): an object containing request and configuration details
Returns:
(bytes, string): data to return to cl... | 5,296,564 |
def call_in_netns(chute, env, command, onerror="raise", pid=None):
"""
Call command within a chute's namespace.
command: should be a list of strings.
onerror: should be "raise" or "ignore"
"""
if pid is None:
# We need the chute's PID in order to work with Linux namespaces.
cont... | 5,296,565 |
def largest_rectangle(h):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/largest-rectangle/problem
Skyline Real Estate Developers is planning to demolish a number of old, unoccupied buildings and construct a
shopping mall in their place. Your task is to find the largest solid area in which th... | 5,296,566 |
def get_size(objct, seen=None):
"""Recursively finds size of objects"""
if seen is None:
seen = set()
# Important mark as seen *before* entering recursion to gracefully handle
# self-referential objects
all_objects = [objct]
total_size = 0
while len(all_objects) > 0:
cu... | 5,296,567 |
def _load_imsitu_file(mode):
"""
Helper fn that loads imsitu file
:param fn:
:return:
"""
if mode not in LISTS:
raise ValueError("Invalid mode {}, must be train val or test".format(mode))
imsitu_ind_to_label = {}
dps = []
with open(LISTS[mode], 'r') as f:
for row in ... | 5,296,568 |
def fahr2cel(t):
"""Converts an input temperature in fahrenheit to degrees celsius
Inputs:
t: temperature, in degrees Fahrenheit
Returns:
Temperature, in C
"""
return (t - 32) * 5 / 9 | 5,296,569 |
def column_union(rel: list, left_col: int, right_col: int):
"""
TODO
"""
return | 5,296,570 |
def str2tod(timeval=''):
"""Return tod for given string without fail."""
ret = None
if timeval is not None and timeval != '':
try:
ret = tod(timeval)
except:
pass
return ret | 5,296,571 |
def log_error(msg: str, line_number: typing.Optional[int] = None) -> None:
"""
Log Error.
Method for logging errors to ensure uniform summary.
:param msg: message to be logged
:param line_number: input file line number
:returns: None
"""
msg = msg if line_number is None else f"line : {... | 5,296,572 |
def readFDOUB1(stream):
"""
Read FDOUB1 from given stream
:type stream: FileIO or ByteIO
:param stream: stream to be read
:return: Result.
:rtype: FDOUB1
"""
return FDOUB1(stream) | 5,296,573 |
def _sub_sample(matrix_X, matrix_Y, test_statistic, num_samples, sub_samples, which_test):
"""
Sub samples the data and calculates the sub sampled test statistic
:param matrix_X: is interpreted as a ``[n*p]`` data matrix, a matrix with ``n`` samples in ``p`` dimensions
:type matrix_X: 2D numpy.array
... | 5,296,574 |
def require_partitions(f: Callable[['MultiDiskBundleStore', Any], Any]):
"""Decorator added to MultiDiskBundleStore methods that require a disk to
be added to the deployment for tasks to succeed. Prints a helpful error
message prompting the user to add a new disk.
"""
def wrapper(*args, **kwargs):
... | 5,296,575 |
def get_peleenet(model_name=None,
pretrained=False,
root=os.path.join("~", ".tensorflow", "models"),
**kwargs):
"""
Create PeleeNet model with specific parameters.
Parameters:
----------
model_name : str or None, default None
Model name for... | 5,296,576 |
def convert_file_dic(fn1, fn2):
"""
voca
"""
data = []
regex2 = re.compile(
r'^[aàảãáạăằẳẵắặâầẩẫấậbcdđeèẻẽéẹêềểễếệghiìỉĩíịklmnoòỏõóọôồổỗốộơờởỡớợpqrstuùủũúụưừửữứựvxyỳỷỹýỵ_]+$', re.UNICODE)
with open(fn1, 'r') as json_data:
for f in json_data:
data.append(json.loads... | 5,296,577 |
def read_csv(param_name, filepath):
"""read dataframe using pandas.read_csv, but with appropriate types
"""
specs = filemanager.get_specs(param_name)
columndata = specs['columns']
converters = {c: eval(data['type']) for c, data in columndata.items()}
try:
cols = find_cols(filepath, colum... | 5,296,578 |
def maxterms(name):
"""
Given a BF, returns the maxterms.
"""
if name in _workspace:
maxt = _workspace[name].maxterms()
for i in range(len(maxt)):
if i != len(maxt) - 1:
printc("%i, " %maxt[i], term = "")
else:
printc(maxt[i])
... | 5,296,579 |
def test_custom_action(FormAction):
""" """
def name(self) -> Text:
return "action_recipe_search"
@staticmethod
def required_slots(tracker:Tracker) -> List[Text]:
# returns names of all slots that must be provides
return ["purpose", "diet_type"]
# can define slot_mappi... | 5,296,580 |
def load_fonts():
"""
Load all fonts in the fonts directory
"""
return [os.path.join('fonts1', font) for font in os.listdir('fonts1')] | 5,296,581 |
def reshape_data(state_trajectory, control_inputs, numstates):
"""
Reshapes the data of get_sampled_traj_and_ctrls
"""
traj = np.array(state_trajectory)
len_traj = len(state_trajectory)
traj = traj.reshape(len_traj, numstates)
ctrl = np.array(control_inputs)
return [traj, ctrl] | 5,296,582 |
def handle_response(command, frame, args, quiet=False):
"""
Handle a response frame from the device.
Return a dictionary of interesting information.
"""
ret_dict = {}
resp_command = frame.get_frame()[0]
if resp_command & protocol.CMD_RESPONSE:
resp_command ^= protocol.CMD_RESPONSE
... | 5,296,583 |
def configure():
""" Setup logging """
for logger in _loggers:
setup_logger(_loggers[logger]) | 5,296,584 |
def trace(f):
"""
helps debug recursive calls
"""
indent = ' '
def _f(*args):
signature = '%s(%s)' % (f.__name__, ', '.join(map(repr, args)))
print '%s--> %s' % (trace.level * indent, signature)
trace.level += 1
try:
result = f(*args)
print ... | 5,296,585 |
def generate_table(rows: list[sqlite3.Row],
target: tuple[int, Any] = None) -> list[str]:
"""Generate a Markdown-like table out of the given rows.
The optional `target` parameter expects a tuple of the form
``(col#, value)``. If the given column number in any row has a value that
mat... | 5,296,586 |
def test_val_parser_tool_plugin_scan_find_errors():
"""Make sure the Parser tool correctly finds errors."""
vtp = setup_val_parser_tool_plugin("/opt/val/bin/Parser")
# Sanity check - make sure Parser exists
if not vtp.command_exists("/opt/val/bin/Parser"):
pytest.skip("Couldn't find 'Parser' com... | 5,296,587 |
def getPrivateKeyObject(filename = None, data = '', passphrase = ''):
"""
Return a C{Crypto.PublicKey.pubkey.pubkey} object corresponding to the
private key file/data. If the private key is encrypted, passphrase B{must}
be specified, other wise a L{BadKeyError} will be raised.
@type filename: ... | 5,296,588 |
def get_two_movies_average_rating(movie1_id, movie2_id, threshold=50):
"""return the average rating for two movies, based on the users who have watched both of the movies"""
users = get_user_watched_two_movies(movie1_id, movie2_id)
if users and len(users) > threshold:
ratings1 = Rating.select(Rating... | 5,296,589 |
def add_gpu_mark():
"""No-op fixture, use it to add the 'gpu' mark to a test or fixture."""
pass | 5,296,590 |
def test_extraction():
"""End-to-end test of a model extraction attack"""
# Create a query function for a target PyTorch Lightning model
model = train_four_layer_mnist_victim(gpus=torch.cuda.device_count())
def query_mnist(input_data):
# PrivacyRaven provides built-in query functions
r... | 5,296,591 |
def read_parquet(filename, column, **kwargs):
"""read_parquet"""
memory = kwargs.get("memory", "")
start = kwargs.get("start", 0)
stop = kwargs.get("stop", None)
if stop is None and column.shape[0] is not None:
stop = column.shape[0] - start
if stop is None:
stop = -1
return parquet_ops.io_read_pa... | 5,296,592 |
def decompress(full_bzip_filename: Path, temp_pth: Path) -> str:
"""
Decompresses .bz2 file and returns the non-compressed filename
Args:
full_bzip_filename: Full compressed filename
temp_pth: Temporary path to save the native file
Returns:
The full native filename to the decom... | 5,296,593 |
def tag_na_resources(file_name: str, tag_operation: str = 'read', region: str = 'us-east-2'):
"""
This method generate the NA tag file and update tags of each region
@param tag_operation:
@param region:
@param file_name:
@return:
"""
update_na_tags = UpdateNATags(region=region, file_name... | 5,296,594 |
def to_int(value):
"""Converts the given string value into an integer. Returns 0 if the
conversion fails."""
try:
return int(value)
except (TypeError, ValueError):
return 0 | 5,296,595 |
def create_two_transforms_curve(transform1, transform2, name = ''):
"""
Create a curve between two transforms.
"""
if not name:
name = '%s_to_%s_curve' % (transform1, transform2)
pos1 = cmds.xform(transform1, q = True, ws = True, t = True)
pos2 = cmds.xform(transform2, q = T... | 5,296,596 |
def vms_ajax_assign_disk(request, vm_id, template_name='vms/ajax/assign_disk.html', form_class=AssignDiskForm):
"""
Ajax view for assigning Disk to a virtual machine.
"""
rest_data = prep_data({'disks': 'user/storage_image/get_list/',
'disk_controllers': 'user/storage_image/ge... | 5,296,597 |
def open_url(event):
""" 打开网页 """
webbrowser.open("https://blog.csdn.net/coldrain_end", new=0) | 5,296,598 |
def set_memory_growth() -> None:
"""Set if memory growth should be enabled for ALL `PhysicalDevice`.
If memory growth is enabled for ALL `PhysicalDevice`, the runtime initialization
will not allocate all memory on the device. Memory growth cannot be configured
on a `PhysicalDevice` with virtual de... | 5,296,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.