content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def plot_profiled_all_images_table(method_list):
"""绘制多个图片的结果."""
high_dpi_dir_path, high_dpi_file_name = "result", "high_dpi.json"
rich_texture_dir_path, rich_texture_file_name = "result", "rich_texture.json"
text_dir_path, text_file_name = "result", "text.json"
image_list = ['high_dpi', 'rich_tex... | 31,400 |
def test_name(request):
"""Returns (module_name, function_name[args]) for a given test"""
return (
request.module.__name__,
request._parent_request._pyfuncitem.name, # pylint: disable=protected-access
) | 31,401 |
def inputwrap(x, ARG_indented: bool=False, ARG_end_with: str=" "):
"""Textwrapping for regular 'input' commands.
Parameters
----------
x
The text to be wrapped.
ARG_indented : bool (default is 'False')
Whether or not the textwrapped string should be indented.
ARG_end_with : str ... | 31,402 |
def test_reproject_geometry(landpoly):
"""Reproject geometry."""
with fiona.open(landpoly, "r") as src:
for feature in src:
# WGS84 to Spherical Mercator
out_geom = reproject_geometry(
shape(feature["geometry"]), CRS(src.crs), CRS().from_epsg(3857)
)
... | 31,403 |
async def save_token(token):
"""
Save the oauth token for re-use instead of logging in again. We
store it in the vault cubbyhole secrets engine.
"""
os.umask(0)
with open(
os.open(TESLA_API_TOKEN_FILE, os.O_CREAT | os.O_WRONLY, 0o600), "w"
) as fh:
fh.write(token) | 31,404 |
def SBP_single(ell_fix, redshift, pixel_scale, zeropoint, ax=None, offset=0.0,
x_min=1.0, x_max=4.0, alpha=1, physical_unit=False, show_dots=False, show_grid=False,
show_banner=True, vertical_line=None, linecolor='firebrick', linestyle='-',
linewidth=3, labelsize=25, ticksize=30, label='SBP', labelloc='l... | 31,405 |
def min_conflicts_value(csp, var, current):
"""Return the value that will give var the least number of conflicts.
If there is a tie, choose at random."""
return argmin_random_tie(csp.domains[var],
key=lambda val: csp.nconflicts(var, val, current)) | 31,406 |
def init(jwt):
"""Initialize the JWTManager.
Parameters:
jwt (JWTManager): an instance of the jwt manager.
"""
@jwt.token_in_blacklist_loader
def check_if_token_in_blacklist(decoded_token):
"""Callback to check if a token is in the blacklist.
Parameters: ... | 31,407 |
def get_component_rst_string(module: ModuleType, component: Callable, level: int) -> str:
"""Get a rst string, to autogenerate documentation for a component (class or function)
:param module: the module containing the component
:param component: the component (class or function)
:param level: the level... | 31,408 |
def log_mse_loss(source, separated, max_snr=1e6, bias_ref_signal=None):
"""Negative log MSE loss, the negated log of SNR denominator."""
err_pow = tf.math.reduce_sum(tf.math.square(source - separated), axis=-1)
snrfactor = 10.**(-max_snr / 10.)
if bias_ref_signal is None:
ref_pow = tf.math.reduc... | 31,409 |
def crack(password: str) -> Union[str, None]:
"""
Crack the given password
"""
# found 96% by caesar
return caesar(password) | 31,410 |
def insert_file(file_item):
"""Inserts a file into the autocode database
:param file_item: the file item to insert
:return:
"""
conn = create_connection()
with conn:
__insert_file(conn, file_item) | 31,411 |
def fetchOne(query):
"""
Returns a dict result from the fetch of one query row
"""
return sqliteRowToDict(query.fetchone()) | 31,412 |
def _get_class_rgb(num_classes, predicted_class):
"""Map from class to RGB value for a specific colormap.
Args:
num_classes: Integer, the total number of classes.
predicted_class: Integer, the predicted class, in [0, num_classes).
Returns:
Tuple of 3 floats in [0.0, 1.0] representing an RGB color.... | 31,413 |
def PUT(request):
"""Update a project's name."""
request.check_required_parameters(body={'project': {'name': 'name'}}, path={'projectId': 'string'})
project = Project.from_id(request.params_path['projectId'])
project.check_exists()
project.check_user_access(request.google_id, True)
project.s... | 31,414 |
def load_book_details(file_path):
""" Read book details from a csv file into a pandas DataFrame. """
books_df = pd.read_csv(file_path, index_col='book_id')
return books_df | 31,415 |
def random_string_fx() -> str:
"""
Creates a 16 digit alphanumeric string. For use
with logging tests.
Returns:
16 digit alphanumeric string.
"""
result = "".join(random.sample(string.ascii_letters, 16))
return result | 31,416 |
def parse_scheduler_nodes(
pbscmd: PBSCMD, resource_definitions: Dict[str, PBSProResourceDefinition]
) -> List[Node]:
"""
Gets the current state of the nodes as the scheduler sees them, including resources,
assigned resources, jobs currently running etc.
"""
ret: List[Node] = []
for ndict in... | 31,417 |
def GaugeSet(prefix, *, name, index, **kwargs):
"""
Factory function for Gauge Set.
Parameters
----------
prefix : str
Gauge base PV (up to 'GCC'/'GPI').
name : str
Name to refer to the gauge set.
index : str or int
Index for gauge (e.g. '02' or 3).
prefix_con... | 31,418 |
def user_rating(user, object, category=""):
"""
Usage:
{% user_rating user obj [category] as var %}
"""
return user_rating_value(user, object, category) | 31,419 |
def weighted_mean(
x: NumericOrIter,
w: NumericOrIter = None,
na_rm: bool = False,
) -> NumericType:
"""Calculate weighted mean"""
if is_scalar(x):
x = [x] # type: ignore
if w is not None and is_scalar(w):
w = [w] # type: ignore
x = Array(x)
if w is not None:
w ... | 31,420 |
def internet(host="8.8.8.8", port=53, timeout=10):
"""
Check Internet Connections.
:param host: the host that check connection to
:param port: port that check connection with
:param timeout: times that check the connnection
:type host:str
:type port:int
:type timeout:int
:return b... | 31,421 |
def parse_date(td):
"""helper function to parse time"""
resYear = float(td.days)/364.0 # get the number of years including the the numbers after the dot
resMonth = int((resYear - int(resYear))*364/30) # get the number of months, by multiply the number after the dot by 364 and divide by 30... | 31,422 |
def test_basis():
"""
Test basis change.
"""
well = Well.from_las(FNAME)
gr = well.data['GR']
x = gr.to_basis(start=100, stop=200, step=1)
assert x.size == 101
assert x[0] - 66.6059 < 0.001
y = gr.to_basis_like(x)
assert y.size == 101
assert y[0] - 66.6059 < 0.001 | 31,423 |
def describe_instance_patch_states(InstanceIds=None, NextToken=None, MaxResults=None):
"""
Retrieves the high-level patch state of one or more instances.
See also: AWS API Documentation
Exceptions
:example: response = client.describe_instance_patch_states(
InstanceIds=[
... | 31,424 |
def hue_angle(a, b):
"""
Returns the *hue* angle :math:`h` in degrees.
Parameters
----------
a : numeric
Opponent colour dimension :math:`a`.
b : numeric
Opponent colour dimension :math:`b`.
Returns
-------
numeric
*Hue* angle :math:`h` in degrees.
Exam... | 31,425 |
def perform_similarity_checks(post, name):
"""
Performs 4 tests to determine similarity between links in the post and the user name
:param post: Test of the post
:param name: Username to compare against
:return: Float ratio of similarity
"""
max_similarity, similar_links = 0.0, []
# Kee... | 31,426 |
def create_getters(tuples):
"""Create a series of itemgetters that return tuples
:param tuples: a list of tuples
:type tuples: collections.Iterable
:returns: a generator of item getters
:rtype: generator
::
>>> gs = list(create_getters([(0, 2), (), (1,)]))
>>> d = ['a', 'b', '... | 31,427 |
def report_cots_cv2x_bsm(bsm: dict) -> str:
"""A function to report the BSM information contained in an SPDU from a COTS C-V2X device
:param bsm: a dictionary containing BSM fields from a C-V2X SPDU
:type bsm: dict
:return: a string representation of the BSM fields
:rtype: str
"""
report =... | 31,428 |
def get_level_matrix(matrix, level):
"""Returns a binary matrix with positions exceeding a threshold.
matrix = numpy array object
level = floating number
The matrix it returns has 1 in the positions where matrix
has values above level and 0 elsewhere."""
logging.info("Selecting the amino acids... | 31,429 |
def bookmark(repo, subset, x):
"""``bookmark([name])``
The named bookmark or all bookmarks.
If `name` starts with `re:`, the remainder of the name is treated as
a regular expression. To match a bookmark that actually starts with `re:`,
use the prefix `literal:`.
"""
# i18n: "bookmark" is a ... | 31,430 |
def test_packages(host):
"""Test that the appropriate packages were installed."""
distribution = host.system_info.distribution
if distribution in ["amzn", "fedora"]:
pkgs = ["tigervnc-server"]
elif distribution in ["debian", "kali", "ubuntu"]:
pkgs = ["tigervnc-standalone-server", "tiger... | 31,431 |
def indel_protein_processor(df, refgene, proteincdd=None):
"""Calculate protein features
Features not used in the final model are commented out
Args:
df (pandas.DataFrame)
refgene (str): path to refCodingExon.bed.gz
proteincdd (str): optional, path to proteinConservedDomains.t... | 31,432 |
def setup_module():
"""Set up before all tests."""
# switch to examples/app.py
os.chdir(EXAMPLE_APP_DIR) | 31,433 |
def main() -> None:
"""Simple CLI for the module."""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-i", dest="iso_filename", required=True, help="ISO filename")
parser.add_argument("-u", dest="preseed_url", required=True, help="preseed URL")
parser.add_argument("-o", d... | 31,434 |
def test_metadata_source_value():
"""Alert Processor Input Validation - Source Entity Value"""
# Default valid alert to be modified
invalid_metadata_source = get_alert()
# metadata > source value validation
invalid_metadata_source['source_entity'] = 100
# Test with invalid metadata source valu... | 31,435 |
def perdict_raw(model, *args, **kwargs):
"""
Tries to call model.predict(*args, **kwargs, prediction_type="RawFormulaVal"). If that fail,
calls model.predict(*args, **kwargs)
"""
try:
return model.predict(*args, **kwargs, prediction_type="RawFormulaVal")
except TypeError:
return ... | 31,436 |
def login_required(arg):
""" Decorator to check if a user is logged in"""
@wraps(arg)
def wrap(*args, **kwargs):
"""Checking if token exists in the request header"""
if request.headers.get('Authorization'):
auth_token = request.headers.get('Authorization')
token = aut... | 31,437 |
def calc_manual_numbers(n):
"""
>>> calc_manual_numbers(1)
20151125
>>> calc_manual_numbers(2)
31916031
>>> calc_manual_numbers(3)
18749137
>>> calc_manual_numbers(21)
33511524
"""
return (BASE * pow(FACTOR, n - 1, MOD)) % MOD | 31,438 |
def accuracy(y0, y1):
"""
compute accuracy for y1 and y2 does not meter if either of them is in vector or integer form
:param y0: list of - labels or vector of probabilities
:param y1: list of - labels or vector of probabilities
:return: accuracy
"""
if not isinstance(y0[0], (int, float, np.... | 31,439 |
def random_function(*args):
"""Picks one of its arguments uniformly at random, calls it, and returns the result.
Example usage:
>>> random_function(lambda: numpy.uniform(-2, -1), lambda: numpy.uniform(1, 2))
"""
choice = random.randint(0, len(args) - 1)
return args[choice]() | 31,440 |
def get_transceiver_sensor_sub_id(ifindex, sensor):
"""
Returns sub OID for transceiver sensor. Sub OID is calculated as folows:
sub OID = transceiver_oid + XCVR_SENSOR_PART_ID_MAP[sensor]
:param ifindex: interface index
:param sensor: sensor key
:return: sub OID = {{index}} * 1000 + {{lane}} * ... | 31,441 |
def test_include_2():
"""
>>> text = '''
... {% include file=test.js %}
... {% endinclude %}
... '''
>>> blocks = {'include':include}
>>> print (parseHtml(text, '%(body)s', block_callback=blocks))
<BLANKLINE>
<pre><code>$(function(){
$('.div').on('click', function(e){
... | 31,442 |
def patch_twitter_get_following_users(value):
"""Return a function decorator which patches the TwitterClient.get_following_user_ids method."""
return patch_twitter_client_method("get_following_user_ids", value) | 31,443 |
def test_convert_html_to_newspaper():
"""Should convert the given HTML into a newspaper article object."""
result = utils.convert_html_to_newspaper(
"<html><head></head><body><article><p>Hello</p></article>"
)
assert isinstance(result, newspaper.Article) | 31,444 |
def conv1x1_1d(inplanes: int,
outplanes: int,
stride: int = 1) -> nn.Conv1d:
"""1x1一维卷积,用于短接时降采样"""
return nn.Conv1d(
inplanes,
outplanes,
kernel_size=(1,),
stride=(stride,),
padding=0,
bias=False
) | 31,445 |
def load_cifar10(channels_last=True, x_shape=None, x_dtype=np.float32,
y_dtype=np.int32, normalize_x=False):
"""
Load the CIFAR-10 dataset as NumPy arrays.
Args:
channels_last (bool): Whether or not to place the channels axis
at the last?
x_shape: Reshape each d... | 31,446 |
def test_tag_spot_instance_request():
"""
Test that moto correctly tags a spot instance request
"""
conn = boto.connect_ec2()
request = conn.request_spot_instances(price=0.5, image_id=EXAMPLE_AMI_ID)
request[0].add_tag("tag1", "value1")
request[0].add_tag("tag2", "value2")
requests = c... | 31,447 |
def unpack_mmap_block(mm, n):
"""Decode the nth 4-byte long byte string from mapped memory."""
return struct.unpack("<L", mm[n*DATA_BLOCK_SIZE:(n+1)*DATA_BLOCK_SIZE])[0] | 31,448 |
def tobs():
"""Return a list of temperatures for prior year"""
# * Query for the dates and temperature observations from the last year.
# * Convert the query results to a Dictionary using `date` as the key and `tobs` as the value.
# * Return the json representation of your dictionary.
las... | 31,449 |
def answer(comment):
"""Answers given comment."""
text = comment.body.replace("\n","")
low = text.lower()
print "//INCOMING COMMENT {}: {}".format(comment.id, text)
if keyword not in text.lower():
print "//KEYWORD NOT IN COMMENT"
return
if keyword + " say " in low:
... | 31,450 |
def test_unknown_offset_raises_error():
"""It should raise an exception when an invalid offset is used."""
with pytest.raises(ValueError):
assert parse_date('(2018-01-01) + 1century', '%Y-%m-%d') | 31,451 |
def reactToAMQPMessage(message, send_back):
"""
React to given (AMQP) message. `message` is expected to be
:py:func:`collections.namedtuple` structure from :mod:`.structures` filled
with all necessary data.
Args:
message (object): One of the request objects defined in
... | 31,452 |
def recE(siEnergy, layer):
""" Reconstructed energy from sim energy """
return ( (siEnergy/mipSiEnergy) * layerWeights[layer-1] + siEnergy)*\
secondOrderEnergyCorrection | 31,453 |
def get_account_id():
"""
Retrieve the AWS account ID
"""
client = boto3.client("sts")
account_id = client.get_caller_identity()["Account"]
return account_id | 31,454 |
def process_tag(item, profile, level=0):
"""
Processes element with <code>tag</code> type
@type item: ZenNode
@type profile: dict
@type level: int
"""
if not item.name:
# looks like it's root element
return item
attrs = make_attributes_string(item, profile)
cursor = profile['place_cursor'] and zen_codin... | 31,455 |
def read_secret(project_id: str, secret_name: str) -> Optional[str]:
"""Reads the latest version of a GCP Secret Manager secret.
Returns None if the secret doesn't exist."""
secret_manager = secretmanager.SecretManagerServiceClient()
secret_path = secret_manager.secret_path(project_id, secret_name)
... | 31,456 |
def find_in_xml(data, search_params):
"""Try to find an element in an xml
Take an xml from string or as xml.etree.ElementTree
and an iterable of strings (and/or tuples in case of findall) to search.
The tuple should contain the string to search for and a true value.
"""
if isinstance(dat... | 31,457 |
def conditional_expect(
X,
func,
reg,
method=None,
quantile_method=None,
n_integration_samples=10,
quad_dict=None,
random_state=None,
include_x=False,
include_idx=False,
vector_func=False,
):
"""Calculates the conditional expectation, i.e. E[func(Y)|X=x_eval], where
Y... | 31,458 |
def pump_volume(volume, direction):
"""
Moves volume of solution through pump
:param volume: amount of volume to move (float)
:param direction: 0 to pull solution in, 1 to pump out
"""
volume_to_add = volume
# pull in solution
if direction == 0:
# if volume_to_add is greater tha... | 31,459 |
def delete_temp_files():
"""
Deletes the 3 single component temporary files
"""
for component in COMPS:
filename = PREFIX + component
os.unlink(filename)
filename = PREFIX_PROC + component
os.unlink(filename) | 31,460 |
def getSumOfSquaresPixel16_Image16(Image):
"""getSumOfSquaresPixel16_Image16(Image) -> unsigned __int16"""
return _ImageFunctions.getSumOfSquaresPixel16_Image16(Image) | 31,461 |
def greeting_py():
"""A simple Python function"""
print("Hello World, from Python!") | 31,462 |
def parse_statement(parsed, output):
"""Parses a tokenized sql_parse token and returns an encoded table."""
# Get the name of the table being created
table_name = next(token.value for token in parsed.tokens if isinstance(token, Identifier))
# Add the table metadata to the cached tables to access later.
... | 31,463 |
def create_hue_success_response(entity_number, attr, value):
"""Create a success response for an attribute set on a light."""
success_key = f"/lights/{entity_number}/state/{attr}"
return {"success": {success_key: value}} | 31,464 |
def get_deaths():
"""***DEPRECATED - Use get_data_jhu instead.***
Get most recent fatality counts from JHU."""
# Deprecated warning
url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/"
warnings.warn("This function is deprecated. Use g... | 31,465 |
def init_enforcer(policy_file=None, rules=None,
default_rule=None, use_conf=True):
"""Synchronously initializes the policy enforcer
:param policy_file: Custom policy file to use, if none is specified,
`CONF.oslo_policy.policy_file` will be used.
:param rul... | 31,466 |
def transform_sentence(text, model):
"""
Mean embedding vector
"""
def preprocess_text(raw_text, model=model):
"""
Excluding unknown words and get corresponding token
"""
raw_text = raw_text.split()
return list(filter(lambda x: x in model.vocab, raw_text))
... | 31,467 |
def main():
"""As usual, the main line of the program is pretty compact. Here I have opted to read in the microrarray
data file in the main line of the program rather than cluttering up my Tree class.
"""
i = 0
# filename = 'ratiodata.txt'
filename = 'BacillusData2.txt'
infile = op... | 31,468 |
def model_primary_key_columns_and_names(Model: DeclarativeMeta) -> (Sequence[Column], List[str]):
""" Get the list of primary columns and their names as two separate tuples
Example:
pk_columns, pk_names = model_primary_key_columns_and_names(models.User)
pk_columns # -> (models.User.id, )
... | 31,469 |
def biweekly_test_data():
""" Provides test data for the full system test when using "biweekly" time_scale."""
time_scale = "biweekly"
time_per_task = {
"Free" : 480 * 9 * 2,
"Work" : 480 * 5 * 2,
"Sleep" : 480 * 7 * 2
}
min_task_time = 60
preferences = {
"Free" :... | 31,470 |
def test_apply_rename_through_arg(spark_session) -> None:
"""
"""
assert "name_renamed" in TestApplyRenameThroughArg.load(spark_session).columns | 31,471 |
def plot_bar_whiskers_jitter_significance(data, comparison_columns,
significant_comparison_columns,
heights, ylabel,
xlabels=None,
ax_handle=None,
... | 31,472 |
def test_configure(mock_va):
"""
Test configuration
"""
sample_config = {"ebr-trackerbot": {"api_url": "https:/test_url.com", "slack_token": "test-token"}}
mock_va.return_value.auth_from_file = Mock(return_value=True)
mock_va.return_value.load = Mock(return_value=sample_config)
bot.configu... | 31,473 |
def _is_trans_valid(seed, mutate_sample):
"""
Check a mutated sample is valid. If the number of changed pixels in
a seed is less than pixels_change_rate*size(seed), this mutate is valid.
Else check the infinite norm of seed changes, if the value of the
infinite norm less than pixel_value_change_rate... | 31,474 |
def split_axis(x, indices_or_sections, axis):
"""Splits given variables along an axis.
Args:
x (tuple of Variables): Variables to be split.
indices_or_sections (int or 1-D array): If this argument is an integer,
N, the array will be divided into N equal arrays along axis.
... | 31,475 |
def status(**kwargs):
"""Execute \"git status\" on the repository."""
status = check_output(["git", "status"]).decode("utf-8")
repo_clean = True
for keyword in ["ahead", "modified", "untracked"]:
if keyword in status:
repo_clean = False
return {"clean": repo_clean, "status": st... | 31,476 |
def preprocessing_raw_csv(PATH=".//tcdata//hy_round2_train_20200225//",
local_file_name="train.pkl"):
"""Loading and processing all train csv data."""
if PATH is None:
raise ValueError("Invalid PATH !")
file_names = sorted(os.listdir(PATH), key=lambda s: int(s.split(".")[0]... | 31,477 |
def update_points(points):
"""Atualiza os pontos maximos."""
file = open('max_points.txt', 'w')
file.write(str(points)) | 31,478 |
def random_rewire (G, n, allow_self_loops=False):
"""Randomly rewire edges.
This function performs a full rewire i.e., it will ensure the newly created
edge contains all the same properties as the original.
Parameters
----------
G : NetworkX graph
It is assumed that this is configu... | 31,479 |
def find_listener_frequent_words(df, num):
"""
Given a conversation dataframe from a certain subreddit, find the top frequent words spoken by listeners.
Args:
df: A specified dataframe from a subreddit.
num: A ranking number used for finding the top frequent words.
Return:
resul... | 31,480 |
def is_rescue_entry(boot_entry):
"""
Determines whether the given boot entry is rescue.
:param BootEntry boot_entry: Boot entry to assess
:return: True is the entry is rescue
:rtype: bool
"""
return 'rescue' in boot_entry.kernel_image.lower() | 31,481 |
def plotLineChart(df, wb, sheetname, **kwargs):
"""Line chart of columns in given DataFrame
Parameters
----------
df : pandas.DataFrame
DataFrame with data
wb : xlsxwriter.Workbook
sheetname: : string
Name of sheet to which data and plot should be written
Other parameters
... | 31,482 |
def estimate_cost(features, ssd):
"""Generate a TensorFlow subgraph to estimate the cost of an architecture.
Args:
features: A 1D float tensor containing features for a single network
architecture.
ssd: The name of the search space definition to use for the cost model.
Returns:
A scalar floa... | 31,483 |
def test_bind_gre_segment_vxlan_tunnel_advertised(
f5_mech_driver, context, agent_with_vxlan_vtep, gre_segment):
"""Test proper behaviour when agent advertises vxlan tunnels.
The network segment is gre and the only advertised tunnel type
is vxlan
Pass if no binding is performed
"""
ret... | 31,484 |
def load_bias_module(df, dataset):
"""
"""
print('Launch dataset module thread : load_bias_module')
thread = Thread(target=bias.compute_bias_metrics,
args=(df, dataset,))
thread.start() | 31,485 |
def installFromRequests(requestOrPackages = "requests", fromRequests = True):
"""Install PyPI packages from a requests file or a list"""
if fromRequests:
requestOrPackages = withoutFormat.getLines(requestOrPackages)
bar = ProgressBar()
l = len(requestOrPackages)
c = 0
for package in requ... | 31,486 |
def short_bubble(l, debug=True):
"""
what if the whole list is already in ascending order, the bubble would then still go through the entire outer loops
actually, if there is no swap happens in a certain iteration ( the inner loop), the next loop should stop
:param l:
:param debug:
:return:
... | 31,487 |
def initdb_command():
""" Initializes the database."""
init_db()
print('Initialized the database.') | 31,488 |
def IsResourceLike(item):
"""Return True if item is a dict like object or list of dict like objects."""
return yaml.dict_like(item) or (yaml.list_like(item) and
all(yaml.dict_like(x) for x in item)) | 31,489 |
def rad_to_gon(angle: float) -> float:
"""Converts from radiant to gon (grad).
Args:
angle: Angle in rad.
Returns:
Converted angle in gon.
"""
return angle * 200 / math.pi | 31,490 |
def check_interface_status(conn_obj, interface, state, device="dut"):
"""
API to check the interface state
Author: Chaitanya Vella (chaitanya-vella.kumar@broadcom.com)
:param conn_obj:
:param interface:
:param state:
:param device:
:return:
"""
interface_state = get_interface_sta... | 31,491 |
def test_efficiency():
"""Test solved per (2^n)-1 algorithm for lowest move count."""
assert not t(0)[3] # none
assert t(1)[3] == 2 ** 1 - 1 # 1
assert t(2)[3] == 2 ** 2 - 1 # 3
assert t(3)[3] == 2 ** 3 - 1 # 7
assert t(10)[3] == 2 ** 10 - 1 | 31,492 |
def hungarian_match(self, y_true, y_pred):
"""Matches predicted labels to original using hungarian algorithm."""
y_true = self.adjust_range(y_true)
y_pred = self.adjust_range(y_pred)
D = max(y_pred.max(), y_true.max()) + 1
w = np.zeros((D, D), dtype=np.int64)
# Confusion matrix.
fo... | 31,493 |
def orthantree(scaled, capacity=8):
"""Constructs a :ref:`tree <presolve>` for the given :func:`~pybbfmm.scale`'d problem.
This is a bit of a mess of a function, but long story short it starts with all the sources allocated to the root
and repeatedly subdivides overfull boxes, constructing the various tree... | 31,494 |
def make_sparse(
docs_to_fit, min_df=50, stop_words=None,
docs_to_transform=None, ngram_range=None,
):
"""
Take a pre-tokenized document and turn into a sparse matrix.
:param docs_to_fit: A list of lists of tokenized words to build the vocabulary from.
:param min_df: Number of records th... | 31,495 |
def weightedPriorityReliabilityScore(service_instances, last_records):
"""
Algorithm to find highest priority of the service based on
reliability score achieved in past discovery results
"""
priority_list = []
for i in range(0, len(service_instances)):
single_instance = {... | 31,496 |
def calculate_output(param_dict, select_device, input_example):
"""Calculate the output of the imported graph given the input.
Load the graph def from graph file on selected device, then get the tensors based on the input and output name from the graph,
then feed the input_example to the graph and retrieve... | 31,497 |
def is_instance_failed_alarm(alarms, instance, guest_hb=False):
"""
Check if an instance failed alarm has been raised
"""
expected_alarm = {'alarm_id': fm_constants.FM_ALARM_ID_VM_FAILED,
'severity': fm_constants.FM_ALARM_SEVERITY_CRITICAL}
return _instance_alarm_raised(alarms... | 31,498 |
def load_metad_fes(fes_dir_path):
"""Load all the PLUMED free energy profiles saved by sumhills."""
from modules.plumedwrapper import io as plumedio
# Read the FES in time.
fes_file_prefix_path = os.path.join(fes_dir_path, 'fes_')
fes_time = plumedio.read_table(fes_file_prefix_path + 'time.dat')
... | 31,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.