content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def add_integral_control(
plant, regulator=None, integrator_ugf=None,
integrator_time_constant=None, **kwargs):
"""Match and returns an integral gain.
This function finds an integral gain such that
the UGF of the integral control matches that of the specified
regulator.
If ``integra... | 37,800 |
def script():
"""Render the required Javascript"""
return Response(response=render_template("settings/settings.js"),
status=200,
mimetype="application/javascript") | 37,801 |
def repr_helper(tuple_gen_exp, ind=2):
""" given a sequence of 2-tuples, return a nice string like:
.. code_block:: python
(1, 'hi'), (2, 'there'), (40, 'you') ->
.. code_block:: python
[ 1] : hi
[ 2] : there
[40] : you
"""
lines = []
k_v = list(tuple_gen_exp)... | 37,802 |
def in_ipython() -> bool:
"""Return true if we're running in an IPython interactive shell."""
try:
from IPython import get_ipython
return get_ipython().__class__.__name__ == 'TerminalInteractiveShell'
except Exception:
pass
return False | 37,803 |
def simple_coordination_accept():
"""simple coordination
>>> test(r"John|NNP|NP and|CC|conj Mary|NNP|NP")
and_1 conj 1 Mary_2
and_1 conj 1 John_0
>>>
""" | 37,804 |
def test_get_own_km_user(api_rf, km_user_factory, user_factory):
"""
A user should be able to get the details of their own Know Me user
account.
"""
user = user_factory()
api_rf.user = user
km_user = km_user_factory(user=user)
request = api_rf.get(km_user.get_absolute_url())
respon... | 37,805 |
def demo_loss_accuracy_curve():
"""Make a demo loss-accuracy curve figure."""
steps = np.arange(101)
loss = np.exp(-steps * 0.1) * 20. + np.random.normal(size=101) * 2.
loss = loss - np.min(loss) + .2
valid_steps = np.arange(0, 101, 10)
valid_loss = (np.exp(-valid_steps * 0.1) * 25. +
... | 37,806 |
def guess_platform(ctx, arch=None):
"""L{guess_platform} returns a platform set that describes the various
features of the specified I{platform}. If I{platform} is I{None}, try to
determine which platform the system is and return that value. If the
platform cannot be determined, return I{None}."""
... | 37,807 |
def text_filter(sentence:str)-> str:
"""
过滤掉非汉字和标点符号和非数字
:param sentence:
:return:
"""
line = sentence.replace('\n', '。')
# 过滤掉非汉字和标点符号和非数字
linelist = [word for word in line if
word >= u'\u4e00' and word <= u'\u9fa5' or word in [',', '。', '?', '!',
... | 37,808 |
def get_lr_schedule(base_lr, global_batch_size, base_batch_size=None,
scaling=None, n_warmup_epochs=0, warmup_factor=-1, decay_schedule={}, is_root=True):
"""Get the learning rate schedule function"""
if scaling == 'linear':
scale_factor = global_batch_size / base_batch_size
elif... | 37,809 |
def test_show_info_retrieve_bluff_info_all(show_id: int):
"""Testing for :py:meth:`wwdtm.show.ShowInfoMultiple.retrieve_bluff_info_all`
:param show_id: Show ID to test retrieving show Bluff the Listener
information from all shows retrieved
"""
info = ShowInfoMultiple(connect_dict=get_connect_di... | 37,810 |
def stdp_values(values, period=None):
"""Returns list of running population standard deviations.
:param values: list of values to iterate and compute stat.
:param period: (optional) # of values included in computation.
* None - includes all values in computation.
:rtype: list of windowed popula... | 37,811 |
def main():
"""Provide the background logic and link the components together."""
while True:
score = [None, None, None] # set the list of scores to None
introduction()
location = navigate()
while True:
if quiz_check(location, score):
# check if a user... | 37,812 |
def json_serialize(item):
"""
A function similar to L{dumps}.
"""
def helper(unknown):
if isinstance(unknown, PlatedElement):
return unknown._asJSON()
else:
raise TypeError("{input} not JSON serializable"
.format(input=unknown))
ret... | 37,813 |
def get_sop_instance_uid(dicom):
"""
Return the SOP Instance UID.
Args:
dicom: pydicom Dataset
"""
return dicom.SOPInstanceUID | 37,814 |
def save_spotify_info_as_json(spotify_info_dict: dict,
path: str = os.getcwd(),
indent: int = None,
mongodb: bool = False) -> None:
"""Saves a dataset of weekly Billboard charts as a JSON file.
Args:
spotify_info_... | 37,815 |
def remove_filter():
"""
Removes a filter from the process
Returns
-------------
dictio
Success, or not
"""
# reads the session
session = request.args.get('session', type=str)
# reads the requested process name
process = request.args.get('process', default='receipt', typ... | 37,816 |
def test_ap_wps_reg_config_tkip(dev, apdev):
"""WPS registrar configuring AP to use TKIP and AP upgrading to TKIP+CCMP"""
skip_with_fips(dev[0])
ssid = "test-wps-init-ap"
appin = "12345670"
hostapd.add_ap(apdev[0],
{ "ssid": ssid, "eap_server": "1", "wps_state": "1",
... | 37,817 |
def flag_data(vis_windows, flag_windows):
""" Returns flag_windows untouched """
def _flag_data(vis_windows, flag_windows):
return flag_windows
return da.blockwise(_flag_data, _WINDOW_SCHEMA,
vis_windows, _WINDOW_SCHEMA,
flag_windows, _WINDOW_SCHEMA,... | 37,818 |
async def redirect_user(request):
"""fetch oauth token, redirecting user"""
async with Client() as client:
async for resp in client.post(
"/oauth/request_token",
headers={
"x_auth_access_type": getenv(
"TWITTER_X_AUTH_ACCESS... | 37,819 |
def create_micro_lib_base(
out_obj_path,
in_src_path,
toolchain_prefix,
device_id,
lib_type,
options=None,
lib_src_paths=None,
):
"""Compiles code into a binary for the target micro device.
Parameters
----------
out_obj_path : str
... | 37,820 |
def preprocess_static_feature(
static_feature_dict,
imputation_strategy="median",
standardize=False
):
"""Preprocessing for a dictionary of static features.
Args:
static_feature_dict: Dictionary of float values.
imputation_strategy: "median" or "mean" or "most_frequent" imputation.
standard... | 37,821 |
def auto_sampler(dataset, encoding, ui):
"""
Automatically find an appropriate number of rows to send per batch based
on the average row size.
:return:
"""
t0 = time()
sample_size = AUTO_SAMPLE_SIZE
is_gz = dataset.endswith('.gz')
opener, mode = (gzip.open, 'rb') if is_gz else (ope... | 37,822 |
def initialize():
"""
Initialize necessary the Multi Writing Style Detection algorithm.
**Warning** The module may work without calling this method under certain circumstances,
but it is recommended to call initialize() before calling the execute() function.
"""
download_nltk_depend... | 37,823 |
def sync_directories(src_dir, dest_dir, ignore=None):
"""
Syncs two directories so that the both contain the same content, with the exception of ignored files.
"""
if ignore is None:
ignore = []
ignore.extend(CMP_IGNORE_FILES)
dcmp = filecmp.dircmp(src_dir, dest_dir, ignore)
_sync_d... | 37,824 |
def test_is_binary():
"""Test the is_binary method on the Map object."""
mymap = mapping.Map(data="so")
assert mymap.is_binary
data = np.arange(10)
mymap = mapping.Map(data=data)
assert not mymap.is_binary
return | 37,825 |
def from_emso(platform_code: str, parameters: List[str]=[], start_time: str='',
end_time: str='', depth_min: float=None, depth_max: float=None,
user: str='', password: str='', size: int=10, token: str=''
) -> WaterFrame:
"""
Get a WaterFrame with the data of the EMSO AP... | 37,826 |
def _get_all_pivots(Ao, number_of_subsamples):
"""
A dummy case where we return all the subsamples.
"""
return np.arange(1, len(number_of_subsamples)) | 37,827 |
def trainer(xdata, gt_data, conf):
"""Training loop.
Handles model, optimizer, loss, and sampler generation.
Handles data loading. Handles i/o and checkpoint loading.
Parameters
----------
xdata : numpy.array (N, img_height, img_width, 2)
Dataset of under-sampled measurements... | 37,828 |
def clang_find_var(tu, name, ts, namespace=None, filename=None, onlyin=None):
"""Find the node for a given var."""
assert isinstance(name, basestring)
kinds = CursorKind.ENUM_DECL,
decls = clang_find_decls(tu, name, kinds=kinds, onlyin=onlyin, namespace=namespace)
decls = list(set(c.get_definition()... | 37,829 |
def main():
""" Step 0: Compiling Model """
# torch.manual_seed(123)
# print bayescnn
batch_size = 150
num_epochs = 5
bayescnn = BayesCNN(alpha = 0.5, k_mc = 3)
optimizer = torch.optim.SGD(bayescnn.parameters(), lr=0.001)
if torch.cuda.is_available():
print "Run on GPU"
... | 37,830 |
def ShouldRunOnInternalIpAddress(sending_vm, receiving_vm):
"""Returns whether a test should be run on an instance's internal IP.
Based on the command line flag --ip_addresses. Internal IP addresses are used
when:
* --ip_addresses=BOTH or --ip-addresses=INTERNAL
* --ip_addresses=REACHABLE and 'sending_vm' c... | 37,831 |
def create_main_window():
""" Used to create the Game Settings window.
Program initialized by calling this function.
"""
root = tk.Tk()
root.wm_title("Game Settings")
main = MainWindow(root)
root.geometry('{}x{}'.format(200, 300))
main.pack(side="top", fill="both", expand=True)
roo... | 37,832 |
def shn_get_crud_string(tablename, name):
""" Get the CRUD strings for a table """
crud_strings = s3.crud_strings.get(tablename, s3.crud_strings)
not_found = s3.crud_strings.get(name, None)
return crud_strings.get(name, not_found) | 37,833 |
def default_invalid_token_callback(error_string):
"""
By default, if an invalid token attempts to access a protected endpoint, we
return the error string for why it is not valid with a 422 status code
:param error_string: String indicating why the token is invalid
"""
return jsonify({config.err... | 37,834 |
def bf_generate_dataplane(snapshot=None, extra_args=None):
# type: (Optional[str], Optional[Dict[str, Any]]) -> str
"""Generates the data plane for the supplied snapshot. If no snapshot argument is given, uses the last snapshot initialized."""
return bf_session.generate_dataplane(snapshot=snapshot, extra_ar... | 37,835 |
def plot_histogram(hist_data: List[List[float]],
out: Optional[Text] = None
) -> None: # pragma: no cover
"""Plot a histogram of the confidence distribution of the predictions in
two columns.
Wine-ish colour for the confidences of hits.
Blue-ish colour for the conf... | 37,836 |
def k_correction_pl(redshift, a_nu):
"""Calculate the k-correction for a power law spectrum with spectral
index (per frequency) a_nu.
:param redshift: Cosmological redshift of the source
:type redshift: float
:param a_nu: Power law index (per frequency)
:type a_nu: float
:return: K-correcti... | 37,837 |
def make_points_image(pts, mask, radius=5):
"""
Create label image from physical space points
Creates spherical points in the coordinate space of the target image based
on the n-dimensional matrix of points that the user supplies. The image
defines the dimensionality of the data so if the input ima... | 37,838 |
def navigate(driver, move=1):
"""Use the arrow key to navigate the gallary"""
# For testing
# next_photo_xpath = '//*[@id="ow81"]/c-wiz[3]/div[2]/div[2]'
moves = [Keys.LEFT, Keys.RIGHT]
driver.find_element_by_css_selector('body').send_keys(moves[move]) | 37,839 |
def map_replacements():
""" create a map of what resources are replaced by others. This is a tree. """
isreplacedby = {} # isreplacedby[x] is the number of things that are replaced by x
replaces = {} # replaces[x] are the number of things that x replaces.
for r in BaseResource.objects.all():
i... | 37,840 |
def order_basemaps(key, out):
"""check the apy key and then order the basemap to update the select list"""
# checking the key validity
validate_key(key, out)
out.add_msg(cm.planet.mosaic.load)
# autheticate to planet
planet.client = api.ClientV1(api_key=planet.key)
# get the basemap name... | 37,841 |
def explanare_optionem(thing: Any) -> str:
"""Output debug information from data structures used on HDP containers
Args:
thing (Any): Anything that can be converted to str
Returns:
str: String
"""
return str(thing) | 37,842 |
def configure_logging(level, script_log_cmd=None, clock=time, dry_run=False):
"""Configure logging system by setting root handlers, level and clock.
Parameters
----------
level : integer or string
Log level for root logger (will typically apply to all loggers)
script_log_cmd : function, sig... | 37,843 |
def compute_iou(box1, box2, yxyx=False):
"""Calculates the intersection of union between box1 and box2.
Args:
box1: a `Tensor` whose shape is [..., 4] and represents the coordinates of
boxes in x_center, y_center, width, height.
box2: a `Tensor` whose shape is [..., 4] and represents the coordinates ... | 37,844 |
def show_consts():
"""Print out all constants"""
print("-"*40)
print("DHT11_PIN = %s" % DHT11_PIN)
print("CONVERT_TEMP_TO_F = %s" % CONVERT_TEMP_TO_F)
print("SAMPLE_SIZE = %s" % SAMPLE_SIZE)
print("LOG_IF_CHANGED_BY = %s" % LOG_IF_CHANGED_BY)
print("LOG_IF_HUMIDITY_CHANGED = %s" % LOG_IF_HUM... | 37,845 |
def download_file():
""" Calls the Download class to download a file """
Download(OUI_URL + OUI_FILE, OUI_FILE) | 37,846 |
def glLightiv(light, pname, parms):
"""light - GLenum
parms - sequence"""
if len(parms) != glGetXXDim[pname]:
raise TypeError(len(parms), glGetXXDim[pname], "wrong size of parms")
_gllib.glLightiv(light, pname, parms) | 37,847 |
def ensure_pyspark_df(spark_session: SparkSession, df: Union[pandasDF, sparkDF]):
"""Method for checking dataframe type for each onData() call from a RunBuilder."""
if not isinstance(df, sparkDF):
warnings.warn(
"WARNING: You passed in a Pandas DF, so we will be using our experimental utilit... | 37,848 |
def roundTime(dt=None, roundTo=60):
"""
Round a datetime object to any time lapse in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
Example:
roundTo=30*60 - 30 minutes
... | 37,849 |
def sample_recipe(user, **params):
"""Create and return a sample recipe"""
recipe_defaults = {
'title': 'simple ricepi shot',
'time_minutes': 10,
'price': 5.0
}
recipe_defaults.update(params)
return Recipe.objects.create(user=user, **recipe_defaults) | 37,850 |
def read_nitf_offsets(filename):
"""Read NITF fields relevant to parsing SICD
SICD (versions 0.3 and above) is stored in a NITF container. NITF is a
complicated format that involves lots of fields and configurations
possibilities. Fortunately, SICD only really uses a small, specific
portion of the... | 37,851 |
def clean_post_request(incomplete_items: dict, postrequest_path: Path):
"""Remove POST request files for completed items"""
keepjson_ts = []
for item in incomplete_items.values():
requests, timestamps = item.find_post_requests(postrequest_path)
if requests:
for request in request... | 37,852 |
def dttime(ts):
"""
将DataTime对象转换为unix时间
:param ts: unix时间
:type ts: float
:returns: datetime.datetime 对象
:rtype: datetime.datetime
"""
return datetime.datetime.fromtimestamp(ts) | 37,853 |
def split_import(sc, node, alias_to_remove):
"""Split an import node by moving the given imported alias into a new import.
Arguments:
sc: (scope.Scope) Scope computed on whole tree of the code being modified.
node: (ast.Import|ast.ImportFrom) An import node to split.
alias_to_remove: (ast.alias) The im... | 37,854 |
def load_trace(path):
"""Load the trace located in path.
Args:
path (string): Path to the LTTng trace folder.
Returns:
babeltrace.TraceCollection: a collection of one trace.
"""
trace_collection = bt.TraceCollection()
trace_collection.add_trace(path, 'ctf')
return trace_col... | 37,855 |
def get_repo_paths(config_file_path):
"""
Get a list of repository paths.
Arguments:
config_file_path (str): Path the to config file.
Raises:
(ConfigFileError): Raised if there was an error opening, reading or parsding through the config file.
Returns:
(list<str>): A list ... | 37,856 |
async def get_bosswins_rank(conn : asyncpg.Connection, user_id : int) -> int:
"""Returns the rank in bosswins for the player given"""
psql = """
WITH ranks AS (
SELECT ROW_NUMBER() OVER (ORDER BY bosswins DESC) AS rank,
user_id, user_name, bosswins
... | 37,857 |
def upgrade_v11_to_v12(db: 'DBHandler') -> None:
"""Upgrades the DB from v11 to v12
- Deletes all bittrex related DB data
"""
_delete_bittrex_data(db) | 37,858 |
def detect_objects_yolo(imgs, tensors):
"""This function makes use of multiprocessing to make predictions on batch.
Parameters
----------
imgs : list-like of images
tensors : dict
Contains tensors needed for making predictions.
Returns
-------
boxes: tuple
Tuple of leng... | 37,859 |
def test_defaults(caplog):
"""
If parameters aren't specified, they should be read from the parameter file.
"""
caplog.set_level(logging.INFO)
parameter_fnames = [f"{test_path}/test_data/mini-millennium.par"]
sage_output_formats = ["sage_hdf5"]
random_seeds = [666]
galaxy_analysis = G... | 37,860 |
def main():
"""Entry point."""
parser = argparse.ArgumentParser(
description='create spatial samples of data on a global scale')
parser.add_argument(
'raster_path_list', type=str, nargs='+',
help='path/pattern to list of rasters to sample')
parser.add_argument(
'--kernel_... | 37,861 |
def append_id(endpoint, _id):
"""
append '_id' to endpoint if provided
"""
if _id is not None:
return '/'.join([endpoint.rstrip('/'), _id])
return endpoint | 37,862 |
def records() -> dict:
""" Displays TJ's all time bests. """
records = cube.load_file("records")
times, people = records["records"], records["people"]
refresh = False
if "wca_token" in flask.session and "ion_token" in flask.session:
me = cube.api_call("wca", "me")["me"]
year = cube.a... | 37,863 |
def s3_import( # pylint: disable=too-many-arguments
s3_uri,
project_id,
metadata_json,
host,
email,
password,
api_key,
): # pylint: disable=line-too-long
"""Import all samples from a S3 URI to a project. Optionally add
metadata to the samples.
Examples:
Import samples... | 37,864 |
def write_env_vars(env_vars=None): # type: (dict) -> None
"""Write the dictionary env_vars in the system, as environment variables.
Args:
env_vars ():
Returns:
"""
env_vars = env_vars or {}
for name, value in env_vars.items():
os.environ[name] = value | 37,865 |
def cuffdiff(inputs, outputs, extras):
"""
Identify differentially expressed genes in each group using Cuffdiff.
"""
merged_gtk = inputs[0]
output_de, flagFile = outputs
c1_files, c2_files, c1_label, c2_label = extras
labels = c1_label + "," + c2_label
outputDir = os.path.dirname(output_... | 37,866 |
def main(url: str = "http://localhost:8000/openapi.json", output: str = "openapi.yaml"):
"""Generate openapi yaml from FastAPI server"""
response = requests.get(url)
json_data = response.json()
with open(output, "w") as json_file:
yaml.dump(json_data, json_file) | 37,867 |
def get_info_media(title: str, ydl_opts=None, search_engine=None, result_count=1):
"""
:param title:
:param ydl_opts:
:param search_engine:
:param result_count:
:return:
"""
if ydl_opts is None:
ydl_opts = {
# 'format': 'best[ext!=wav]/best',
'quiet': Fal... | 37,868 |
def datasetmaker(offset, matfilename):
"""offset is multiple of 256 matfile name is output name"""
#Computes FFT of dataset
Fs = 50000
T = 1/Fs
L = 50000
t = np.arange(0, L) * T
a = 0 + 50000 * offset
b = 49999 + 50000 * offset
matfilenamedat = "{}{}.csv" .format(matfilename,offset)... | 37,869 |
def export_post(request, style, format=-1):
"""
:param request:
:param style:
:param format:
:return:
"""
try:
payload = request.get_json(force=True) # post data in json
except:
payload = dict(request.form) # post data in form encoding
if not payload:
retu... | 37,870 |
def add_to_last_summary(chat, message):
"""
Args:
chat (telegram.Chat)
message (telegram.Message)
"""
atusername = get_at_username(chat.username)
bot_member = get_bot_chat_member(atusername)
if not bot_member.can_post_messages:
bot.send_message(chat_id=admin_chat_id,
... | 37,871 |
def unpack_literal_map_to_sdk_object(literal_map, type_map=None):
"""
:param lytekit.models.literals.LiteralMap literal_map:
:param dict[Text, flytekit.common.types.base_sdk_types.FlyteSdkType] type_map: Type map directing unpacking.
:rtype: dict[Text, T]
"""
type_map = type_map or {}
return... | 37,872 |
def object_name_readable(obj):
"""
Tests if object name is easily readable, so not equal to id.
:param obj: odml.Section or odml.Property.
"""
validation_id = IssueID.object_name_readable
if obj.name == obj.id:
yield ValidationError(obj, "Name not assigned", LABEL_WARNING, validation_i... | 37,873 |
def get_data(user:str,num_last:int)->int:
"""获取关注者数数据,输出数据增量并返回数据;重试3次,全部失败则返回False"""
# error=None
global proxies
for i in range(3):
try:
num_this=requests.get('https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names='+user,proxies=proxies,timeout=(10,30)).json()[0]['followers_count']
... | 37,874 |
def genClassifyScripts(ignorePolyA, barcodePath, roiFastaList, nameStemList,
scriptsDir, logDir, grpOutDirList):
"""Generate the classify submit scripts for colonial one, there is an option
to ignore the polyA signature at this point. Also if samples are pooled,
the barcode option should be used."""
... | 37,875 |
def parse_cli() -> dict:
"""
Parse CLI arguments.
:return: CLI Arguments dict.
"""
parser = argparse.ArgumentParser()
parser.add_argument(
"-s",
"--settings_path",
type=str,
help="Path to settings YAML-file for RailLabel.",
default="settings.yml",
)
... | 37,876 |
def _init_basemap(border_colour):
"""Initializes basemap.
:param border_colour: Colour (in any format accepted by matplotlib) of
political borders.
:return: narr_row_limits: length-2 numpy array of (min, max) NARR rows to
plot.
:return: narr_column_limits: length-2 numpy array of (min, ... | 37,877 |
def catalog() -> None:
"""Browse and search the query catalog."""
pass | 37,878 |
def unlock_device():
"""
Powers on device and unlocks it.
"""
# read device screen state
p = ADB.exec_cmd("shell 'if [ -z $(dumpsys power | grep mScreenOn=true) ]; then echo off; else echo on;fi'",
stdout=subprocess.PIPE)
device_screen = p.stdout.readline().strip('\r\n')
... | 37,879 |
def makeFigure():
"""Get a list of the axis objects and create a figure"""
ax, f = getSetup((9, 12), (5, 2))
cellTarget = "Treg"
epitopesDF = pd.DataFrame(columns={"Classifier", "Epitope"})
posCorrs1, negCorrs = CITE_RIDGE(ax[4], cellTarget)
for x in posCorrs1:
epitopesDF = epitopesDF.a... | 37,880 |
def get_data_frame(binary_tables, all_inputs):
"""
Gets a data frame that needs QM reduction and further logic.
Also removes the all_inputs from the DataFrame.
:param binary_tables: contains a tables with True and False outputs.
:param all_inputs: columns
:return: Pandas DataFrame.
"""
... | 37,881 |
def compute_shift_delay_samples(params_delays,vector_seconds_ref,freq_sample,seconds_frame,pair_st_so,data_type=0,\
front_time=None,cache_rates=[],cache_delays=[]):
"""
Compute number of samples to shift signal (always positive since reference station is closest to source).
... | 37,882 |
def classification_metrics_function(
logits: jnp.ndarray,
batch: base_model.Batch,
target_is_onehot: bool = False,
metrics: base_model.MetricNormalizerFnDict = _CLASSIFICATION_METRICS,
) -> Dict[str, Tuple[float, int]]:
"""Calculates metrics for the classification task.
Currently we assume each me... | 37,883 |
def create_validator_delegation_withdrawal(
params: DeployParameters,
amount: int,
public_key_of_delegator: PublicKey,
public_key_of_validator: PublicKey,
path_to_wasm: str
) -> Deploy:
"""Returns a standard withdraw delegation deploy.
:param params: Standard parameters used when creating a ... | 37,884 |
def get_host_finding_vulnerabilities_hr(vulnerabilities):
"""
Prepare human readable json for "risksense-get-host-finding-detail" command.
Including vulnerabilities details.
:param vulnerabilities: vulnerabilities details from response.
:return: list of dict
"""
vulnerabilities_list = [{
... | 37,885 |
def taskDone(job, taskId, result=ResultCode.OK):
"""Marks a task as done, including all required locators."""
locators = {}
if result is not ResultCode.ERROR:
for out in job.getTask(taskId).getOutputs():
locators[out] = locatorForTask(taskId)
job.taskDone(taskId, result, 'summary te... | 37,886 |
def train_on_file_dataset(
train_dataset_path: str,
valid_dataset_path: Optional[str],
feature_ids: List[str],
label_id: str,
weight_id: Optional[str],
model_id: str,
learner: str,
task: Optional[TaskType] = Task.CLASSIFICATION,
generic_hparms: Optional[hyperparameter_pb2.GenericHype... | 37,887 |
def db_fixture():
"""Get app context for tests
:return:
"""
return db | 37,888 |
def login_required(route_function):
"""
这个函数看起来非常绕
是实现装饰器的一般套路
"""
def f(request):
u = current_user(request)
if u is None:
log('非登录用户')
return redirect('/login')
else:
return route_function(request)
return f | 37,889 |
def SwitchWorkspace(workspace_name, create_if_missing=True):
"""Switch to the specific workspace.
Parameters
----------
workspace_name : str
The name of the specific workspace.
create_if_missing : boolean
Whether to create the specific workspace if it does not exist.
Returns
... | 37,890 |
def test_pyimport_empty():
"""Empty source string imports nothing."""
context = Context({'pyImport': ''})
pyimport.run_step(context)
assert context._pystring_globals == {}
# only builtins
assert list(dict.items(context._pystring_namespace)) == [
('__builtins__', builtins.__dict__)] | 37,891 |
def cuTypeConverter(cuType):
""" Converts calendar user types to OD type names """
return "recordType", CalendarDirectoryRecordMixin.fromCUType(cuType) | 37,892 |
def add_viz_sphere(
sim: habitat_sim.Simulator, radius: float, pos: mn.Vector3
) -> habitat_sim.physics.ManagedRigidObject:
"""
Add a visualization-only sphere to the world at a global position.
Returns the new object.
"""
obj_attr_mgr = sim.get_object_template_manager()
sphere_template = ob... | 37,893 |
def get_normalize_layer(dataset: str) -> torch.nn.Module:
"""Return the dataset's normalization layer"""
if dataset == "imagenet":
return NormalizeLayer(_IMAGENET_MEAN, _IMAGENET_STDDEV)
elif dataset == "cifar10":
return NormalizeLayer(_CIFAR10_MEAN, _CIFAR10_STDDEV) | 37,894 |
def token_apply_prefix(token, blockquote=None, codeblock=None):
"""
prefixes the lines
old method
token['data'] = token['data'].replace('\n', '\n%s' % prefix)
"""
if (not blockquote) and (not codeblock):
return
try:
if "\n" not in token["data"]:
return
_p... | 37,895 |
def summer_69(arr):
"""
Return the sum of the numbers in the array,
except ignore sections of numbers starting
with a 6 and extending to the next 9 (every 6 will be followed by at least one 9).
Return 0 for no numbers.
:param arr: list of integers
:return: int
"""
get_result = 0
... | 37,896 |
def test_notation_enumeration002_1384_notation_enumeration002_1384_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : facet=enumeration and value=foo and
document value=foo
"""
assert_bindings(
schema="msData/datatypes/Facets/NOTATION/NOTATION_enumeration002.xsd",
... | 37,897 |
def save_hparams(out_dir, hparams):
"""Save hparams."""
hparams_file = os.path.join(out_dir, "hparams")
print_out(" saving hparams to %s" % hparams_file)
with codecs.getwriter("utf-8")(tf.gfile.GFile(hparams_file, "wb")) as f:
f.write(hparams.to_json()) | 37,898 |
def get_notebook_title(nb_json, default=None):
"""Determine a suitable title for the notebook.
This will return the text of the first header cell.
If that does not exist, it will return the default.
"""
cells = nb_json['cells']
for cell in cells:
if cell['cell_type'] == 'heading':
... | 37,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.