content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def binary_to_string(bin_string: str):
"""
>>> binary_to_string("01100001")
'a'
>>> binary_to_string("a")
Traceback (most recent call last):
...
ValueError: bukan bilangan biner
>>> binary_to_string("")
Traceback (most recent call last):
...
ValueError: tidak ada yang diinput... | 6,300 |
def put_lifecycle_configuration(FileSystemId=None, LifecyclePolicies=None):
"""
Enables lifecycle management by creating a new LifecycleConfiguration object. A LifecycleConfiguration object defines when files in an Amazon EFS file system are automatically transitioned to the lower-cost EFS Infrequent Access (IA... | 6,301 |
def plot_height(dset):
"""Plots ash top height from VOLCAT
Does not save figure - quick image creation"""
fig = plt.figure('Ash_Top_Height')
title = 'Ash Top Height (km)'
ax = fig.add_subplot(1,1,1)
plot_gen(dset, ax, val='height', time=None, plotmap=True,
title=title) | 6,302 |
def clean_axis(axis):
"""
Args:
axis:
Returns:
"""
axis.get_xaxis().set_ticks([])
axis.get_yaxis().set_ticks([])
for spine in axis.spines.values():
spine.set_visible(False) | 6,303 |
def create_fake_record():
"""Create records for demo purposes."""
fake = Faker()
data_to_use = {
"access": {
"record": "public",
"files": "public",
},
"files": {
"enabled": False,
},
"pids": {
},
"metadata": {
... | 6,304 |
def load_texture_pair(filename):
"""Function what loads two verions of the texture for left/right movement"""
return [
arcade.load_texture(filename),
arcade.load_texture(filename, flipped_horizontally=True)
] | 6,305 |
def aw_mover_set_state(id: int, state: int, model_num: int) -> None:
"""
Sets the state of a mover. Triggers the mover set state event.
Args:
id (int): The mover ID.
state (int): The state.
model_num (int): The model number.
Raises:
Exception: If the mover state cou... | 6,306 |
def bytes2bson(val: bytes) -> Tuple[bytes, bytes]:
"""Encode bytes as BSON Binary / Generic."""
assert isinstance(val, (bytes, bytearray))
return BSON_BINARY, pack_i32(len(val)) + BSON_BINARY_GENERIC + val | 6,307 |
def create_overlay(path: str, preprocessed: np.ndarray,
segmentation_result: Optional[SegmentationResult], cells_results: Optional[np.ndarray],
results: List[Tuple[float, int, str]]):
""" Creates and saves an overlaid image. """
# create path if needed
if not os.path.e... | 6,308 |
def tabindex(field, index):
"""Set the tab index on the filtered field."""
field.field.widget.attrs["tabindex"] = index
return field | 6,309 |
def compute_GridData(xvals, yvals, f, ufunc=0, **keyw):
"""Evaluate a function of 2 variables and store the results in a GridData.
Computes a function 'f' of two variables on a rectangular grid
using 'tabulate_function', then store the results into a
'GridData' so that it can be plotted. After calcula... | 6,310 |
def decorator_with_option(
decorator_fn,
):
"""Wraps a decorator to correctly forward decorator options.
`decorator_with_option` is applied on decorators. Usage:
```
@jax3d.utils.decorator_with_option
def my_decorator(fn, x=None, y=None):
...
```
The decorated decorator can then be used with or... | 6,311 |
def main():
"""Main program"""
disable_loggers(DISABLE_LOGGERS)
try:
docker_hub = DockerHub(http_get, DOCKER_HUB_USERNAME, DOCKER_HUB_PASSWORD, DOCKER_HUB_REPO)
except PermissionError:
log.error('Could not log into Docker hub')
sys.exit(1)
global fleet # pylint: disable=glo... | 6,312 |
def zones_logs(self):
""" API core commands for Cloudflare API"""
self.add('VOID', "zones", "logs")
self.add('AUTH_UNWRAPPED', "zones", "logs/received")
self.add('AUTH_UNWRAPPED', "zones", "logs/received/fields") | 6,313 |
def chebyshev_parameters(rxn_dstr, a_units='moles'):
""" Parses the data string for a reaction in the reactions block
for the lines containing the Chebyshevs fitting parameters,
then reads the parameters from these lines.
:param rxn_dstr: data string for species in reaction block
:t... | 6,314 |
def zip_varlen(*iterables):
"""Variable length zip() function."""
iters = [iter(it) for it in iterables]
while True: # broken when an empty tuple is given by _one_pass
val = tuple(_one_pass(iters))
if val:
yield val
else:
break | 6,315 |
def _gen_matrix(n, *args):
"""Supports more matrix construction routines.
1. Usual contruction (from a 2d list or a single scalar).
2. From a 1-D array of n*n elements (glsl style).
3. From a list of n-D vectors (glsl style).
"""
if len(args) == n * n: # initialize with n*n scalars
dat... | 6,316 |
def temperature(analog_pin, power_pin = None, ground_pin = None, R = 20000, n = 100):
"""Function for computing thermister temperature
Parameters
----------
adc_pin: :obj:'pyb.Pin'
Any pin connected to an analog to digital converter on a pyboard
power_pin: :o... | 6,317 |
def submit_form():
""" Submits survey data to SQL database. """
if request.method == "POST":
data = request.data
if data:
data = json.loads(data.decode("utf-8").replace("'",'"'))
student, enrollments, tracks = processSurveyData(data)
insert = 'INSERT INTO st... | 6,318 |
def get_target_external_resource_ids(relationship_type, ctx_instance):
"""Gets a list of target node ids connected via a relationship to a node.
:param relationship_type: A string representing the type of relationship.
:param ctx: The Cloudify ctx context.
:returns a list of security group ids.
""... | 6,319 |
def split_multibody(beam, tstep, mb_data_dict, ts):
"""
split_multibody
This functions splits a structure at a certain time step in its different bodies
Args:
beam (:class:`~sharpy.structure.models.beam.Beam`): structural information of the multibody system
tstep (:class:`~sharpy.utils.datas... | 6,320 |
def test_biomass_open_production(model, reaction_id):
"""
Expect biomass production in complete medium.
Using flux balance analysis this test optimizes the model for growth using
a complete medium i.e. unconstrained boundary reactions. Any non-zero
growth rate is accepted to pass this test.
Im... | 6,321 |
def qname_decode(ptr, message, raw=False):
"""Read a QNAME from pointer and respect labels."""
def _rec(name):
ret = []
while name and name[0] > 0:
length = int(name[0])
if (length & 0xC0) == 0xC0:
offset = (length & 0x03) << 8 | int(name[1])
... | 6,322 |
def coordinates_within_board(n: int, x: int, y: int) -> bool:
"""Are the given coordinates inside the board?"""
return x < n and y < n and x >= 0 and y >= 0 | 6,323 |
def check_for_header(header, include_dirs, define_macros):
"""Check for the existence of a header file by creating a small program which includes it and see if it compiles."""
program = "#include <%s>\n" % header
sys.stdout.write("Checking for <%s>... " % header)
success = see_if_compiles(program, include_dirs, def... | 6,324 |
def make_dvh_metric_diff_plots(df_dvh_metrics: pd.DataFrame, constants: ModelParameters):
"""
Generates box plots to visualize distribution of DVH point differences
Args:
df_dvh_metrics: Set of DVH metrics
constants: Model constants
"""
# Prep dvh metrics for analysis
df_to_plot ... | 6,325 |
def test_get_labeled_stats(client):
"""Test get all papers classified as prior documents"""
response = client.get("/api/projects/project-id/labeled_stats")
json_data = response.get_json()
assert isinstance(json_data, dict)
assert "n_prior" in json_data
assert json_data["n_prior"] == 2 | 6,326 |
def hook_name_to_env_name(name, prefix='HOOKS'):
"""
>>> hook_name_to_env_name('foo.bar_baz')
HOOKS_FOO_BAR_BAZ
>>> hook_name_to_env_name('foo.bar_baz', 'PREFIX')
PREFIX_FOO_BAR_BAZ
"""
return '_'.join([prefix, name.upper().replace('.', '_')]) | 6,327 |
def get_coefficients():
"""
Returns the global scaling dictionary.
"""
global COEFFICIENTS
if COEFFICIENTS is None:
COEFFICIENTS = TransformedDict()
COEFFICIENTS["[length]"] = 1.0 * u.meter
COEFFICIENTS["[mass]"] = 1.0 * u.kilogram
COEFFICIENTS["[time]"] = 1.0 * u.yea... | 6,328 |
def get_distance_from_guide_alignment(data, guide_data, reference_index_key="position", minus_strand=False):
"""Calculate the distance of input data alignment to the guide alignment.
:param data: input data with at least "raw_start", "raw_length", and reference_index_key fields
:param guide_data: guide alig... | 6,329 |
def get_info(font):
""" currently wraps the infoFont call, but I would like to add a JSON represenation of this data to
better display the individual details of the font."""
return pyfiglet.FigletFont.infoFont(font) | 6,330 |
def gevent_pywsgi_write(self, data):
"""
Monkey-patched version of the `gevent.pywsgi.WSGIHandler.write` method that ensures
that the passed `data` (which may be unicode string) are encoded to UTF8 bytes prior
to being written.
"""
if self.code in (304, 204) and data:
raise self.Applica... | 6,331 |
def readline_skip_comments(f):
"""
Read a new line while skipping comments.
"""
l = f.readline().strip()
while len(l) > 0 and l[0] == '#':
l = f.readline().strip()
return l | 6,332 |
def test_addDropShadowComplex_BGGreen():
"""
Manual Check
Desired Output: A square image 512x512 pixels with a black shadow to the
bottom right on a green background
"""
io.saveImage(
OUTPUT + "/test_addDropShadowComplex_BGGreen.png",
effects.addDropShadowComplex(IMAGE, 5, 50, [50, 50], "#00ff00", "#000000"),... | 6,333 |
def _verify_weight_parameters(weight_parameters):
"""Verifies that the format of the input `weight_parameters`.
Checks that the input parameters is a 2-tuple of tensors of equal shape.
Args:
weight_parameters: The parameters to check.
Raises:
RuntimeError: If the input is not a 2-tuple of tensors wit... | 6,334 |
def send_notification(lira_url, auth_dict, notification):
"""Send a notification to a given Lira.
Args:
lira_url (str): A typical Lira url, e.g. https://pipelines.dev.data.humancellatlas.org/
auth_dict (dict): Dictionary contains credentials for authenticating with Lira.
It should h... | 6,335 |
def beam():
"""
\b
_ ) __| \ \ | _ \ _ _| | _ \ __ __|
_ \ _| _ \ |\/ | __/ | | ( | |
___/ ___| _/ _\ _| _| _| ___| ____| \___/ _|
Beam Pilot - Cosmos Infrastructure Manager
""" | 6,336 |
def fill_missing_node_names(tree):
""" Names nodes in the tree without a name.
Parameters
----------
bp_tree : bp.Tree
Input tree with potentially unnamed nodes (i.e. nodes' .name attributes
can be None).
Returns
-------
skbio.TreeNode or empress.Tree
Tree with a... | 6,337 |
def calc_vfactor(atm="H2",LJPparam=None):
"""
Args:
atm: molecule consisting of atmosphere, "H2", "O2", and "N2"
LJPparam: Custom Lennard-Jones Potential Parameters (d (cm) and epsilon/kB)
Returns:
vfactor: dynamic viscosity factor for Rosner eta = viscosity*T**0.66
applic... | 6,338 |
def _crc16_checksum(bytes):
"""Returns the CRC-16 checksum of bytearray bytes
Ported from Java implementation at: http://introcs.cs.princeton.edu/java/61data/CRC16CCITT.java.html
Initial value changed to 0x0000 to match Stellar configuration.
"""
crc = 0x0000
polynomial = 0x1021
for byte ... | 6,339 |
def create_readme(target_path, context):
"""Create README.rst for test project
:param target_path: The path to the outer directory where the package
directory is contained
:param context: Jinja context used to render template
"""
target_path = os.path.abspath(target_path)
template_path ... | 6,340 |
def is_absolute_href(href):
"""Determines if an HREF is absolute or not.
Args:
href (str): The HREF to consider.
Returns:
bool: True if the given HREF is absolute, False if it is relative.
"""
parsed = urlparse(href)
return parsed.scheme != '' or os.path.isabs(parsed.path) | 6,341 |
def method_get_func(model, fields="__all__", need_user=False, **kwargs)->Callable:
"""生成一个model的get访问"""
async def list(page: Dict[str, int] = Depends(paging_query_depend),
user: User = Depends(create_current_active_user(need_user))):
"""
get
:return:
"""
... | 6,342 |
def get_mysqlops_connections():
""" Get a connection to mysqlops for reporting
Returns:
A mysql connection
"""
(reporting_host, port, _, _) = get_mysql_connection('mysqlopsdb001')
reporting = HostAddr(''.join((reporting_host, ':', str(port))))
return connect_mysql(reporting, 'scriptrw') | 6,343 |
def _get_params(conv_layer, bn_layer, relu_layer=None):
"""Retrieve conv_bn params within wrapped layers."""
if 'use_bias' in conv_layer['config']:
if conv_layer['config']['use_bias']:
raise ValueError(
'use_bias should not be set to True in a Conv layer when followed '
'by BatchNormal... | 6,344 |
def parse_amconll(fil, validate:bool = True) -> Iterable[AMSentence]:
"""
Reads a file and returns a generator over AM sentences.
:param fil:
:return:
"""
expect_header = True
new_sentence = True
entries = []
attributes = dict()
for line in fil:
line = line.rstrip("\n")
... | 6,345 |
def reverse(segment):
"""Reverses the track"""
return segment.reverse() | 6,346 |
def rmse(y, y_pred):
"""Returns the root mean squared error between
ground truths and predictions.
"""
return np.sqrt(mse(y, y_pred)) | 6,347 |
def _remove_comment_rel_rev(connection, rel_id):
"""Removes relationships revision for comment.
Args:
connection: An instance of SQLAlchemy connection.
rel_id: Id of comment relationship.
Returns:
-
"""
utils.add_to_objects_without_revisions(
connection,
rel_id,
"Relationship",
... | 6,348 |
def cdm_cluster_location_command(client: PolarisClient, args: Dict[str, Any]):
"""
Find the CDM GeoLocation of a CDM Cluster.
:type client: ``PolarisClient``
:param client: Rubrik Polaris client to use
:type args: ``dict``
:param args: arguments obtained from demisto.args()
:return: Comma... | 6,349 |
def prepare_cases(cases, cutoff=25):
""" clean cases per day for Rt estimation. """
new_cases = cases.diff()
smoothed = new_cases.rolling(7,
win_type='gaussian',
min_periods=1,
center=True).mean(std=2).round(... | 6,350 |
def load_data():
"""Load data into the database."""
if not args.populate:
log.info("Data is loaded in Memgraph.")
return
log.info("Loading data into Memgraph.")
try:
memgraph.drop_database()
load_twitch_data(memgraph)
except Exception as e:
log.info("Data loa... | 6,351 |
def wrap_profile_folders(mount_point: Path,
output_folder: Path) -> None:
"""
Load some tiffs with cuCIM and OpenSlide, save them, and run line_profile.
:return: None.
"""
def wrap_profile_folders() -> None:
profile_folders(mount_point, output_folder)
lp = Line... | 6,352 |
def utility(board):
"""
Returns 1 if X has won the game, -1 if O has won, 0 otherwise.
"""
if winner(board) == 'X':
return 1
elif winner(board) == 'O':
return -1
else:
return 0 | 6,353 |
def shard(group, num_shards):
"""Breaks the group apart into num_shards shards.
Args:
group: a breakdown, perhaps returned from categorize_files.
num_shards: The number of shards into which to break down the group.
Returns:
A list of shards.
"""
shards = []
for i in range(num_shards):
shar... | 6,354 |
def is_bond_member(yaml, ifname):
"""Returns True if this interface is a member of a BondEthernet."""
if not "bondethernets" in yaml:
return False
for _bond, iface in yaml["bondethernets"].items():
if not "interfaces" in iface:
continue
if ifname in iface["interfaces"]:
... | 6,355 |
def add_nexus_nodes(generator, vds_file_path):
"""Add in the additional information to make this into a standard nexus
format file:-
(a) create the standard structure under the 'entry' group with a
subgroup for each dataset. 'set_bases' lists the data sets we make here.
(b) save a dataset for each a... | 6,356 |
def create_table(dataset_id, table_id, project=None):
"""Creates a simple table in the given dataset.
If no project is specified, then the currently active project is used.
"""
bigquery_client = bigquery.Client(project=project)
dataset_ref = bigquery_client.dataset(dataset_id)
table_ref = data... | 6,357 |
def get_id(group):
"""
Get the GO identifier from a list of GO term properties.
Finds the first match to the id pattern.
Args:
group (List[str])
Returns:
str
"""
return first_match(group, go_id).split(':',1)[1].strip() | 6,358 |
def generateLogNormalVariate(mu, sigma):
"""
RV generated using rejection method
"""
variateGenerated = False
while not variateGenerated:
u1 = random.uniform(0, 1)
u2 = random.uniform(0, 1)
x = -1*math.log(u1)
if u2 > math.exp(-1*math.pow((x-1), 2)/2):
co... | 6,359 |
def test_a_list_of_sub_resource_generates_okay():
"""
Test that we generate subresources as expected when they are a list
"""
data = {
"author": [
{
"name": "This is the subresource"
},
{
"name": "This is another subresource"
... | 6,360 |
def replace_color_codes(text, replacement):
"""Replace ANSI color sequence from a given string.
Args:
text (str): Original string to replacement from.
replacement (str): String to replace color codes with.
Returns:
str: Mutated string after the replacement.
"""
return re.s... | 6,361 |
def get_uti_for_extension(extension):
"""get UTI for a given file extension"""
if not extension:
return None
# accepts extension with or without leading 0
if extension[0] == ".":
extension = extension[1:]
if (OS_VER, OS_MAJOR) <= (10, 16):
# https://developer.apple.com/doc... | 6,362 |
def test_compose_2() -> None:
"""Verify composition of Sim2 objects works for non-identity input."""
aSb = Sim2(R=rotmat2d(np.deg2rad(90)), t=np.array([1, 2]), s=4)
bSc = Sim2(R=rotmat2d(np.deg2rad(-45)), t=np.array([3, 4]), s=0.5)
aSc = aSb.compose(bSc)
# Via composition: 90 + -45 = 45 degrees
... | 6,363 |
def test_one_parameter_marked_only(param):
"""Case with parametrized argument and mark applied to the single one param""" | 6,364 |
def load_testingData(tempTrainingVectors, tempTestingVectors):
"""
TODO: Merge load_testingData() and load_trainingData() functions
This reads file DSL-StrongPasswordData.csv and returns the testing data in
an ndarray of shape tempTestingVectors*noOfFeatures and target ndarray
of shape (tempTestingVectors*noOfTota... | 6,365 |
async def anext(*args):
"""Retrieve the next item from the async generator by calling its __anext__() method.
If default is given, it is returned if the iterator is exhausted,
otherwise StopAsyncIteration is raised.
"""
if len(args) < 1:
raise TypeError(
f"anext expected at leas... | 6,366 |
def __prepare_arguments_for_d3_data(db_arguments, edge_type):
"""
:param db_arguments:
:param edge_type:
:return:
"""
all_ids = []
nodes = []
edges = []
extras = {}
LOG.debug("Enter private function to prepare arguments for d3")
# for each argument edges will be added as w... | 6,367 |
def delete_file(work_path, file_path):
"""We are only interested in maps, delete any other un-needed files."""
print(" * Deleting " + file_path)
(work_path / file_path).unlink() | 6,368 |
def get_service_gateway(client: VirtualNetworkClient = None,
compartment_id: str = None,
vcn_id: str = None) -> List[RouteTable]:
"""
Returns a complete, unfiltered list of Service Gateways of a vcn in the
compartment.
"""
service_gateway = []
serv... | 6,369 |
def get_road_network_data(city='Mumbai'):
"""
"""
data = pd.read_csv("./RoadNetwork/"+city+"/"+city+"_Edgelist.csv")
size = data.shape[0]
X = np.array(data[['XCoord','YCoord']])
u, v = np.array(data['START_NODE'], dtype=np.int32), np.array(data['END_NODE'], dtype=np.int32)
w = np.a... | 6,370 |
def main_json(config, in_metadata, out_metadata):
"""
Alternative main function
-------------
This function launches the app using configuration written in
two json files: config.json and input_metadata.json.
"""
# 1. Instantiate and launch the App
logger.info("1. Instantiate and launch... | 6,371 |
def test_datasource(request, dataset, dataset_fixture):
"""Test ZarrDataSource.
Data is saved to file and opened by the data source."""
odc_dataset_ = request.getfixturevalue(dataset_fixture)
group_name = list(dataset.keys())[0]
source = ZarrDataSource(BandInfo(odc_dataset_, group_name))
with ... | 6,372 |
def _infection_active(state_old, state_new):
"""
Parameters
----------
state_old : dict or pd.Series
Dictionary or pd.Series with the keys "s", "i", and "r".
state_new : dict or pd.Series
Same type requirements as for the `state_old` argument in this function
apply.
Retu... | 6,373 |
def isnum(txt):
"""Return True if @param txt, is float"""
try:
float(txt)
return True
except TypeError:
return False
except ValueError:
return False | 6,374 |
def xhr(func):
"""A decorator to check for CSRF on POST/PUT/DELETE using a <form>
element and JS to execute automatically (see #40 for a proof-of-concept).
When an attacker uses a <form> to downvote a comment, the browser *should*
add a `Content-Type: ...` header with three possible values:
* appl... | 6,375 |
def updateStyle(style, **kwargs):
"""Update a copy of a dict or the dict for the given style"""
if not isinstance(style, dict):
style = getStyle(style) # look up the style by name
style = style.copy()
style.update(**kwargs)
return style | 6,376 |
def lift2(f, a, b):
"""Apply f => (a -> b -> c) -> f a -> f b -> f c"""
return a.map(f).apply_to(b) | 6,377 |
def project_version(file_path=settings.PROJECT_VERSION_FILE):
"""Project version."""
try:
with open(file_path) as file_obj:
version = file_obj.read()
return parse_version(version)
except Exception:
pass
return None | 6,378 |
def readBinary(fileName):
"""Read a binary FIXSRC file."""
with FIXSRC(fileName, "rb", numpy.zeros((0, 0, 0, 0))) as fs:
fs.readWrite()
return fs.fixSrc | 6,379 |
def short_whitelist(whitelist):
"""A condensed version of the whitelist."""
for x in ["guid-4", "guid-5"]:
whitelist.remove(x)
return whitelist | 6,380 |
def extract_paths(actions):
"""
<Purpose>
Given a list of actions, it extracts all the absolute and relative paths
from all the actions.
<Arguments>
actions: A list of actions from a parsed trace
<Returns>
absolute_paths: a list with all absolute paths extracted from the actions
... | 6,381 |
def str2int(s):
"""converts a string to an integer with the same bit pattern (little endian!!!)"""
r = 0
for c in s:
r <<= 8
r += ord(c)
return r | 6,382 |
def load_operations_from_docstring(docstring):
"""Return a dictionary of OpenAPI operations parsed from a
a docstring.
"""
doc_data = load_yaml_from_docstring(docstring)
return {
key: val for key, val in iteritems(doc_data)
if key in PATH_KEYS or key.startswith('x-')
} | 6,383 |
def inference_model(model, img):
"""Inference image(s) with the classifier.
Args:
model (nn.Module): The loaded segmentor.
img (str/ndarray): The image filename or loaded image.
Returns:
result (list of dict): The segmentation results that contains: ...
"""
cfg = model.cfg
... | 6,384 |
def run_egad(go, nw, **kwargs):
"""EGAD running function
Wrapper to lower level functions for EGAD
EGAD measures modularity of gene lists in co-expression networks.
This was translated from the MATLAB version, which does tiled Cross Validation
The useful kwargs are:
int - nFold : Nu... | 6,385 |
def prepare_new():
"""
Handles a request to add a prepare project configuration. This is the first step in a two-step
process. This endpoint generates a form to request information about the new project from the
user. Once the form is submitted a request is sent to begin editing the new config.
"""
... | 6,386 |
def generic_plot(xy_curves, title, save_path, x_label=None, y_label=None, formatter=None, use_legend=True, use_grid=True, close=True, grid_spacing=20, yaxis_sci=False):
"""
:param xy_curves:
:param title:
:param x_label:
:param y_label:
:param formatter:
:param save_path:
:param use_leg... | 6,387 |
def dump(module, path, **kwargs):
"""Serialize *module* as PVL text to the provided *path*.
:param module: a ``PVLModule`` or ``dict``-like object to serialize.
:param path: an :class:`os.PathLike`
:param ``**kwargs``: the keyword arguments to pass to :func:`dumps()`.
If *path* is an :class:`os.Pa... | 6,388 |
def get_user_labels(client: Client, *_):
""" Returns all user Labels
Args:
client: Client
"""
labels = client.get_user_labels_request()
contents = []
for label in labels:
contents.append({
'Label': label
})
context = {
'Exabeam.UserLabel(val.Lab... | 6,389 |
def hdf5_sample(sample, request):
"""Fixture which provides the filename of a HDF5 tight-binding model."""
return sample(request.param) | 6,390 |
def get_graph_embedding_features(fn='taxi_all.txt'):
"""
Get graph embedding vector, which is generated from LINE
"""
ge = []
with open(fn, 'r') as fin:
fin.readline()
for line in fin:
ls = line.strip().split(" ")
ge.append([float(i) for i in ls])
ge = np.... | 6,391 |
def sub_0_tron(D, Obj, W0, eta=1e0, C=1.0, rtol=5e-2, atol=1e-4,
verbose=False):
"""Solve the Sub_0 problem with tron+cg is in lelm-imf."""
W, f_call = W0.copy(), (f_valp, f_grad, f_hess)
tron(f_call, W.reshape(-1), n_iterations=5, rtol=rtol, atol=atol,
args=(Obj, D, eta, C), verbose... | 6,392 |
def find_flavor_name(nova_connection: NovaConnection, flavor_id: str):
"""
Find all flavor name from nova_connection with the id flavor_id
:param nova_connection: NovaConnection
:param flavor_id: str flavor id to find
:return: list of flavors name
"""
flavor_list = []
for flavor in nov... | 6,393 |
def entity_decode(txt):
"""decode simple entities"""
# TODO: find out what ones twitter considers defined,
# or if sgmllib.entitydefs is enough...
return txt.replace(">", ">").replace("<", "<").replace("&", "&") | 6,394 |
def setup_configs():
""" Sets up the defualt log and config paths """
log_dir = '/var/log/cerberus'
athos_log = os.path.join(log_dir, 'cerberus.log')
conf_dir = '/etc/cerberus'
conf_file = os.path.join(conf_dir, 'topology.json')
rollback_dir = '/etc/cerberus/rollback'
failed_dir = '/etc/cerb... | 6,395 |
def __format_focal_length_tuple(_tuple):
"""format FocalLenght tuple to short printable string
we ignore the position after the decimal point
because it is usually not very essential for focal length
"""
if (isinstance(_tuple,tuple)):
numerator = _tuple[0]
divisor = _tuple[1]
els... | 6,396 |
def submit_resume_file(request):
""" Submit resume """
resume_file = request.FILES['json_file']
# print('resume file=%s' % resume_file)
file_content = resume_file.read()
data = json.loads(file_content.decode('utf-8'))
response = create_resume(data, request.user)
return response | 6,397 |
def read_from_env(export_format=None, export_file_path=None,deep_scan=False,sev=None):
"""
Collect requirments from env and scan and show reports
"""
print(stylize('Started Scanning .....', colored.fg("green")))
print('\n')
data_dict = {}
secure_data_dict = []
data_dict['pyraider'] =... | 6,398 |
def inner_E_vals(vec):
"""
Returns a list of the terms in the expectation times without dividing
by the length or one minus length.\nThis is meant to be used in
conjunction with an inner-product of two inner_E_vals() lists to
compute variance or covariance.
"""
out = [None] *... | 6,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.