content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def elgamal_keypair_from_secret(a: ElementModQ) -> Optional[ElGamalKeyPair]:
"""
Given an ElGamal secret key (typically, a random number in [2,Q)), returns
an ElGamal keypair, consisting of the given secret key a and public key g^a.
"""
secret_key_int = a
if secret_key_int < 2:
log_error... | 5,352,100 |
def make_plots(plot_data, plot_params_dict):
""" Draw and save plot from preprocessed data.
:param plot_data: Data structure processed by __name__.prep_data
:param plot_params_dict: dict holding some plotting paramaters, see e.g. plot_configs/single_day/pov_single_day_config.example.json["PLOT_PARAMS_DICT"... | 5,352,101 |
def current_default_thread_limiter():
"""Get the default `~trio.CapacityLimiter` used by
`trio.to_thread.run_sync`.
The most common reason to call this would be if you want to modify its
:attr:`~trio.CapacityLimiter.total_tokens` attribute.
"""
try:
limiter = _limiter_local.get()
e... | 5,352,102 |
def _mask_board(board):
"""
A function that copies the inputted board replaces all ships with empty coordinates to mask them.
:param board: a 2D numpy array containing a string representation of the board. All ships should be visible.
:return: a 2D numpy array containing a string representation of the b... | 5,352,103 |
def test_proxy_handling():
"""Proxy variable no impact."""
with InstalledApp(wsgi_app.simple_app, host=HOST, port=80,
proxy='some.host:1234') as app:
http_client = http_lib.HTTPConnection(HOST)
http_client.request('GET', '/')
content = http_client.getresponse().read... | 5,352,104 |
def query_yes_no(question, default="no", color=_constants.COLORS.RESET):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or No... | 5,352,105 |
def remove_head_id(ref, hyp):
"""Assumes that the ID is the begin token of the string which is common
in Kaldi but not in Sphinx."""
ref_id = ref[0]
hyp_id = hyp[0]
if ref_id != hyp_id:
print('Reference and hypothesis IDs do not match! '
'ref="{}" hyp="{}"\n'
'Fil... | 5,352,106 |
def convert_image_np(inp):
"""Convert a Tensor to numpy image."""
inp = inp.numpy().transpose((1, 2, 0))
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
inp = std * inp + mean
inp = np.clip(inp, 0, 1)
return inp | 5,352,107 |
def get_miner_day_list():
"""
存储提供者每天的miner数据
:return:
"""
miner_no = request.form.get("miner_no")
date = request.form.get("date")
data = MinerService.get_miner_day_list(miner_no, date)
return response_json(data) | 5,352,108 |
def get_notebook_logs(experiment_id, operator_id):
"""
Get logs from a Experiment notebook.
Parameters
----------
experiment_id : str
operator_id : str
Returns
-------
dict or None
Operator's notebook logs. Or None when the notebook file is not found.
"""
notebook =... | 5,352,109 |
def type_secret(locator, input_text, anchor="1", timeout=0, index=1, **kwargs):
"""Type secret information such as password.
Logging in start_keyword and end_keyword is filtered,
otherwise functionality is the same as TypeText.
Generally all secret credentials in Robot FW scripts should
be provide... | 5,352,110 |
def modify_env2(
function: Callable[[_UpdatedType], _SecondType],
) -> Kinded[Callable[
[Kind2[_Reader2Kind, _FirstType, _SecondType]],
Kind2[_Reader2Kind, _FirstType, _UpdatedType],
]]:
"""
Modifies the second type argument of a ``ReaderBased2``.
In other words, it modifies the function's
... | 5,352,111 |
def test_article_admin_translate_button_expected(db, admin_client):
"""
Translate button should be in detail page with the right URL and lead to the
"Translate" form with the right available languages.
"""
ping = CategoryFactory(slug="ping")
# Create meat articles with unpublished DE translatio... | 5,352,112 |
def model_trees(z, quantiles, normed=False,
dbhfile='c:\\projects\\MLM_Hyde\\Data\\hyde_runkolukusarjat.txt',
plot=False,
biomass_function='marklund'):
"""
reads runkolukusarjat from Hyde and creates lad-profiles for pine, spruce and decid.
Args:
z - g... | 5,352,113 |
def inject_general_timeline():
"""This function injects the function object 'Tweet.get_general_timeline'
into the application context so that 'get_general_timeline' can be accessed
in Jinja2 templates.
"""
return dict(get_general_timeline=Tweet.get_general_timeline) | 5,352,114 |
def is_a(file_name):
"""
Tests whether a given file_name corresponds to a Cosmo Skymed file. Returns a reader instance, if so.
Parameters
----------
file_name : str
the file_name to check
Returns
-------
CSKReader|None
`CSKReader` instance if Cosmo Skymed file, `None` o... | 5,352,115 |
def get_vaccinated_model(model, area=None):
"""Get all states that can be vaccinated or recovered (by area).
Parameters
----------
model : amici.model
Amici model which should be evaluated.
areas : list
List of area names as strings.
Returns
-------
states : list
... | 5,352,116 |
def MicrosecondsToDatetime(microseconds):
"""Returns a datetime given the number of microseconds, or None."""
if microseconds:
return datetime.utcfromtimestamp(float(microseconds) / 1000000)
return None | 5,352,117 |
def update() -> bool:
"""
Pull down the latest Docker image build and prune old image versions.
"""
current_image = DEFAULT_IMAGE
latest_image = latest_build_image(current_image)
if latest_image == current_image:
print(colored("bold", "Updating Docker image %s…" % current_image))
e... | 5,352,118 |
def get_default_accept_image_formats():
"""With default bentoML config, this returns:
['.jpg', '.png', '.jpeg', '.tiff', '.webp', '.bmp']
"""
return [
extension.strip()
for extension in config("apiserver")
.get("default_image_handler_accept_file_extensions")
.split(",... | 5,352,119 |
def findports():
"""Returns an array of the serial ports that have a command interpreter."""
if sys.platform.startswith('win'):
ports = ['COM%s' % (i + 1) for i in range(255)]
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
# this excludes your current terminal "/... | 5,352,120 |
def import_download_cache(filename_or_obj, urls=None, update_cache=False, pkgname='astropy'):
"""Imports the contents of a ZIP file into the cache.
Each member of the ZIP file should be named by a quoted version of the
URL whose contents it stores. These names are decoded with
:func:`~urllib.parse.unqu... | 5,352,121 |
def cells_handler(results, cl):
"""
Changes result cell attributes based on object instance and field name
"""
suit_cell_attributes = getattr(cl.model_admin, 'suit_cell_attributes', None)
if not suit_cell_attributes:
return results
class_pattern = 'class="'
td_pattern = '<td'
th... | 5,352,122 |
def dynamic_import(import_string):
"""
Dynamically import a module or object.
"""
# Use rfind rather than rsplit for Python 2.3 compatibility.
lastdot = import_string.rfind('.')
if lastdot == -1:
return __import__(import_string, {}, {}, [])
module_name, attr = import_string[:lastdot]... | 5,352,123 |
def main():
"""
We are going to draw a fractal called 'Sierpinski Triangle'.
"""
sierpinski_triangle(ORDER, LENGTH, UPPER_LEFT_X, UPPER_LEFT_Y) | 5,352,124 |
def _split_on_parenthesis(text_in: Union[str, list[str]]) -> List[str]:
"""Splits text up into a list of strings based on parenthesis locations."""
if isinstance(text_in, list):
if None in text_in:
return text_in
text_list = text_in
elif isinstance(text_in, str):
text_lis... | 5,352,125 |
def reply():
"""
Reply
"""
t = Twitter(auth=authen())
try:
id = int(g['stuff'].split()[0])
except:
printNicely(red('Sorry I can\'t understand.'))
return
tid = c['tweet_dict'][id]
user = t.statuses.show(id=tid)['user']['screen_name']
status = ' '.join(g['stuff'... | 5,352,126 |
def shell_command_error2exit_decorator(func: Callable):
"""Decorator to convert given ShellCommandException to an exit message
This avoids displaying nasty stack traces to end-users
"""
@functools.wraps(func)
def func_wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
... | 5,352,127 |
def test_almost_equal():
"""Tests almost_equal"""
assert almost_equal(10.0, 10.0005)
assert not almost_equal(10.0, 10.1)
assert almost_equal(10.0, 10.01, precision=0.1)
# Test "a 10% discount on $10"
assert almost_equal(10.0 - 10.0 * (10.0 / 100), 9.0) | 5,352,128 |
def getExternalIP():
""" Returns external ip of system """
ip = requests.get("http://ipv4.myexternalip.com/raw").text.strip()
if ip == None or ip == "":
ip = requests.get("http://ipv4.icanhazip.com").text.strip()
return ip | 5,352,129 |
def intersection_indices(a, b):
"""
:param list a, b: two lists of variables from different factors.
returns a tuple of
(indices in a of the variables that are in both a and b,
indices of those same variables within the list b)
For example, intersection_indices([1,2,5,4,6],[3,5,1,2... | 5,352,130 |
def test_extract_requested_slot_from_entity_with_intent():
"""Test extraction of a slot value from entity with the different name
and certain intent
"""
# noinspection PyAbstractClass
class CustomFormAction(FormAction):
def slot_mappings(self):
return {"some_slot": self.from_... | 5,352,131 |
def graph_cases(selenium, host):
"""
Factory method that allows to draw preconfigured graphs and manipulate them
with a series of helpful methods.
:type selenium: selenium.webdriver.remote.webdriver.WebDriver
:type host: qmxgraph.server.Host
:rtype: GraphCaseFactory
:return: Factory able to... | 5,352,132 |
def test_pipeline(info,
pipeline_id,
datasource,
orchestration_backend,
orchestration_args,
processing_backend,
processing_args,
training_backend,
training_args,
... | 5,352,133 |
def motion_controller_start_images(image_numbers):
"""Configure motion controller
image_numbers: list of 1-based integers
e.g. image_numbers = collection_pass(1)"""
if "after image" in translate.mode:
XYZ = array([translation_after_image_xyz(i) for i in image_numbers])
triggered_motion.x... | 5,352,134 |
def figure_8():
"""
Notes
-----
Colors from Bang Wong's color-blind friendly colormap. Available at:
https://www.nature.com/articles/nmeth.1618
Wong's map acquired from David Nichols page. Available at:
https://davidmathlogic.com/colorblind/.
"""
# choosing test sample and network... | 5,352,135 |
def check_threats(message):
"""Return list of threats found in message"""
threats = []
for threat_check in get_threat_checks():
for expression in threat_check["expressions"]:
if re.search(expression, message, re.I | re.U):
del threat_check["expressions"]
t... | 5,352,136 |
def data_processing_max(data, column):
"""Compute the max of a column."""
return costly_compute_cached(data, column).max() | 5,352,137 |
def type_of_target(y):
"""Determine the type of data indicated by the target.
Note that this type is the most specific type that can be inferred.
For example:
* ``binary`` is more specific but compatible with ``multiclass``.
* ``multiclass`` of integers is more specific but compatib... | 5,352,138 |
def extract_data_from_csv_stream(client: Client, alert_id: str,
attachment_id: str, delimiter: bytes = b'\r\n') -> List[dict]:
"""
Call the attachment download API and parse required fields.
Args:
client (Client): Cyberint API client.
alert_id (str): ... | 5,352,139 |
def validate_password(password, password_repeat=None):
"""
Validate user password.
:param password: password as string
:param password_repeat: repeat password
:return: False - valid password
"""
if password_repeat:
if password != password_repeat:
return "Passwords did not... | 5,352,140 |
def get_large_circuit(backend: IBMBackend) -> QuantumCircuit:
"""Return a slightly larger circuit that would run a bit longer.
Args:
backend: Backend on which the circuit will run.
Returns:
A larger circuit.
"""
n_qubits = min(backend.configuration().n_qubits, 20)
circuit = Qua... | 5,352,141 |
def loadUserProject():
""" Loads a project that contains only the contents of user.dev.
This project will not be cached, so every call will reload it."""
userFilePath = os.path.join(os.path.expanduser(devon.userPath), userFileName)
project = DevonProject("", time.time())
__mergeProject(projec... | 5,352,142 |
def top_k(loc_pred, loc_true, topk):
"""
count the hit numbers of loc_true in topK of loc_pred, used to calculate Precision, Recall and F1-score,
calculate the reciprocal rank, used to calcualte MRR,
calculate the sum of DCG@K of the batch, used to calculate NDCG
Args:
loc_pred: (batch_size... | 5,352,143 |
def enviar_contacto(request):
"""
Enviar email con el formulario de contacto
a soporte tecnico
"""
formulario = ContactoForm()
if request.method == 'POST':
formulario = ContactoForm(request.POST)
if formulario.is_valid():
mail = EmailMessage(subject='HPC Contacto',
... | 5,352,144 |
def dict_depth(d):
"""
递归地获取一个dict的深度
d = {'a':1, 'b': {'c':{}}} --> depth(d) == 3
"""
if isinstance(d, dict):
return 1 + (max(map(dict_depth, d.values())) if d else 0)
return 0 | 5,352,145 |
def test_split_exist_new(utils_patch):
"""
Tests split on exising new pool
"""
ret = {}
ret["stdout"] = ""
ret["stderr"] = "Unable to split datapool: pool already exists"
ret["retcode"] = 1
mock_cmd = MagicMock(return_value=ret)
with patch.dict(zpool.__salt__, {"cmd.run_all": mock_c... | 5,352,146 |
def apercorr(psf,image,objects,psfobj,verbose=False):
"""
Calculate aperture correction.
Parameters
----------
psf : PSF object
The best-fitting PSF model.
image : string or CCDData object
The input image to fit. This can be the filename or CCDData object.
objects : table
... | 5,352,147 |
def product_loading_factor_single_discount(skus: str, product_list: Dict[str, object], product: Dict[str, int], product_name: str, rules: list) -> Tuple[int, str]:
"""
Single product loading factor for calculating discounts with one rule
Parameters
----------
skus: str
String containing ind... | 5,352,148 |
def clean_text(page):
"""Return the clean-ish running text parts of a page."""
return re.sub(_UNWANTED, "", _unescape_entities(page)) | 5,352,149 |
async def test_when_a_stream_iterator_fails_midway():
"""
Sometimes bad things happen. What happens if we're iterating a stream and
some anarchist decides to delete it from under our feet? Well, I guess we
should return an error to the caller and stop the iterator.
"""
dispatcher = MessageDispat... | 5,352,150 |
def error(msg: str, exc_type: Exception=Exception) -> Exception:
"""
Wrapper to get around Python's distinction between statements and expressions
Can be used in lambdas and expressions such as: a if b else error(c)
:param msg: error message
:param exc_type: type of exception to raise
"""
r... | 5,352,151 |
def test_aks(directory: str, aks_service: AksWebservice):
"""
Test AKS with sample call.
:param directory: directory of data_folder with test data
:param aks_service: AKS Web Service to Test
"""
num_dupes_to_score = 4
dupes_test = get_dupes_test(directory)
text_to_score = dupes_test.il... | 5,352,152 |
def calculate_recall(tp, n):
"""
:param tp: int
Number of True Positives
:param n: int
Number of total instances
:return: float
Recall
"""
if n == 0:
return 0
return tp / n | 5,352,153 |
def authenticate_user_password(password : 'bytes', encryption_dict : 'dict', id_array : 'list'):
"""
Authenticate the user password.
Parameters
----------
password : bytes
The password to be authenticated as user password.
encryption_dict : dict
The dictionary containing all... | 5,352,154 |
def date_to_num(date):
"""Convert datetime to days since 1901"""
num = (date.year - 1901) * 365.25
num += [
0, 31, 59.25, 90.25, 120.25,
151.25, 181.25, 212.25, 243.25,
273.25, 304.25, 334.25
][date.month - 1]
num += date.day
return int(num) | 5,352,155 |
def load_world(filename: str, size: Tuple[int, int], resolution: int) -> np.array:
"""Load a preconstructred track to initialize world.
Args:
filename: Full path to the track file (png).
size: Width and height of the map
resolution: Resolution of the grid map (i.... | 5,352,156 |
def generate_image(model, img_size, n_flow, n_block, n_sample, temp=0.7, ctx=None, label=None):
"""Generate a single image from a Glow model."""
# Determine sizes of each layer
z_sample = []
z_shapes = calc_z_shapes(3, img_size, n_flow, n_block)
for z in z_shapes:
z_new = torch.randn(n_samp... | 5,352,157 |
def quote_spaces(arg):
"""Generic function for putting double quotes around any string that
has white space in it."""
if ' ' in arg or '\t' in arg:
return '"%s"' % arg
else:
return str(arg) | 5,352,158 |
def slice_map(center, radius, m):
""" :func:`slice_map` for slicing Map object based on center and radius.
:param center: x, y tuple of center of sliced map
:param radius: - :class:`int` center of sliced map
:param m: - :class:`Map` Map object that want to be sliced
return :class:`Map`
"""
... | 5,352,159 |
def configure(repl):
"""
Configuration method. This is called during the start-up of ptpython.
:param repl: `PythonRepl` instance.
"""
# Vi mode.
repl.vi_mode = True
# Enable 24bit True color. (Not all terminals support this. -- maybe check
# $TERM before changing.)
repl.true_color ... | 5,352,160 |
def download_file(url) -> Path:
"""Better download"""
name = Path(urlparse(unquote(url)).path).name
with mktempdir() as tmpdir:
@backoff.on_exception(backoff.expo, requests.exceptions.RequestException, max_time=30)
def get():
with requests.get(url, stream=True) as r:
... | 5,352,161 |
def creategui(handlerfunctions):
"""Initializes and returns the gui."""
gui = GUI(handlerfunctions)
# root.title('DBF Utility')
return gui | 5,352,162 |
def rank_src_trgs(enc_dec_gen, src_list, trg_list):
"""
"""
batch_size = len(trg_list)
x, y = enc_dec_gen.encode_inputs(src_list,
trg_list,
add_bos=True,
add_eos=True)
y_len = torch... | 5,352,163 |
def plugin_poll(handle):
""" Extracts data from the sensor and returns it in a JSON document as a Python dict.
Available for poll mode only.
Args:
handle: handle returned by the plugin initialisation call
Returns:
returns a sensor reading in a JSON document, as a Python dict, if it is av... | 5,352,164 |
def _set_new_event_entity_for_export_method():
"""Register the new for_export method on EventEntity."""
global _orig_event_entity_for_export
_orig_event_entity_for_export = m_models.EventEntity.for_export
m_models.EventEntity.for_export = _event_entity_for_export | 5,352,165 |
def top_average_pathways(document, file, max_sets, get_all=False):
""" Read the pathways file and get the top average pathways """
# read in the samples and get the data with out the stratification by bug
samples, pathways, data = document.read_table(file)
pathway_names = utilities.pathway_names(pa... | 5,352,166 |
def ltria2skew(L):
"""
assume L has already passed the assertion check
:param L: lower triangle matrix, shape [N, 3]
:return: skew sym A [N, 3, 3]
"""
if len(L.shape) == 2:
N = L.shape[0]
# construct the skew-sym matrix
A = torch.zeros(N, 3, 3).cuda() # [N, 3, 3]
... | 5,352,167 |
def gamma_contrast(data_sample, num_patches=324, num_channel=2, shape_data=None,
gamma_range=(0.5, 1.7), invert_image=False, per_channel=False,
retain_stats=False):
"""Performs gamma contrast transformation"""
epsilon = 1e-7
data_sample_patch = []
gamma_range_tenso... | 5,352,168 |
def _converge(helper, rcs, group):
"""
Function to be passed to :func:`_oob_disable_then` as the ``then``
parameter that triggers convergence.
"""
return group.trigger_convergence(rcs) | 5,352,169 |
def HybridClientFactory(jid, password):
"""
Client factory for XMPP 1.0.
This is similar to L{client.XMPPClientFactory} but also tries non-SASL
autentication.
"""
a = HybridAuthenticator(jid, password)
return xmlstream.XmlStreamFactory(a) | 5,352,170 |
def home():
"""Home page."""
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash('You are logged in.', 'success')
redirect_url = request.args.get('next') or url_for('user.mem... | 5,352,171 |
def countingsort(A):
"""
Sort the list A. A has to be a list of integers.
Every element of the list A has to be non-negative.
@param A: the list that should get sorted
@return the sorted list
"""
if len(A) == 0:
return []
C = [0] * (max(A)+1)
B = [""] * le... | 5,352,172 |
def calc_obstacle_map(ox, oy, resolution, vr):
"""
Build obstacle map according to the distance of a
certain grid to obstacles. Treat the area near the
obstacle within the turning radius of the vehicle
as the obstacle blocking area and mark it as TRUE.
"""
min_x = round(min(ox))
min_y = round(min(oy))
... | 5,352,173 |
def dilate(poly,eps):
"""
The function dilates a polytope.
For a given polytope a polytopic over apoproximation of the $eps$-dilated set is computed.
An e-dilated Pe set of P is defined as:
Pe = {x+n|x in P ^ n in Ball(e)}
where Ball(e) is the epsilon neighborhood with norm |n|<e
The c... | 5,352,174 |
def downgrade():
"""Reverse MSSQL backend compatibility improvements"""
conn = op.get_bind()
if conn.dialect.name != 'mssql':
return
alter_mssql_datetime2_column(conn, op, 'serialized_dag', 'last_updated', False)
op.alter_column(table_name="xcom", column_name="timestamp", type_=_get_timestam... | 5,352,175 |
def read_files_to_vardf(map_df, df_dict, gridclimname, dataset, metadata,
file_start_date, file_end_date, file_delimiter,
file_time_step, file_colnames,
subset_start_date, subset_end_date, min_elev, max_elev, variable_list=None):
"""
# r... | 5,352,176 |
def read_file(pickle_file_name):
"""Reads composite or non-composite class-activation maps from Pickle file.
:param pickle_file_name: Path to input file (created by
`write_standard_file` or `write_pmm_file`).
:return: gradcam_dict: Has the following keys if not a composite...
gradcam_dict['deno... | 5,352,177 |
def tacodev(val=None):
"""a valid taco device"""
if val in ('', None):
return ''
val = string(val)
if not tacodev_re.match(val):
raise ValueError('%r is not a valid Taco device name' % val)
return val | 5,352,178 |
def VioNet_densenet(config, home_path):
"""
Load DENSENET model
config.device
config.pretrained_model
config.sample_size
config.sample_duration
"""
device = config.device
ft_begin_idx = config.ft_begin_idx
sample_size = config.sample_size[0]
sample_duration = ... | 5,352,179 |
def afficheStats(statsKm, listeJoueurs):
"""
Affiche le graphique des kms parcourus par
chaque joueur en fonction du temps.
"""
i = 0
for liste in statsKm:
plt.plot(liste, label=listeJoueurs[i].nom)
i += 1
plt.title("Evolution de la partie")
plt.xlabel("Tour")
plt.yla... | 5,352,180 |
def explore_sub() -> None:
"""Explore some data sets."""
stats_df = data_frame_stats(sub)
print(stats_df) # .head().style.format({"notnulls%": "{:.2%}",
# "unique%": "{:.2%}"})
sub_stats = sub["form"].value_counts().reset_index()
sub_stats["label"] = \
np.where(sub_stats["form"].rank... | 5,352,181 |
def train_and_eval(train_epochs, train_data, test_data, train_embeddings_file_name, test_embeddings_file_name, eval_filename,
unformed_filename, positive_labels, combination_method, method, c_lst, lbd_type, experiment_name, a, c, gold_b):
"""Train and evaluate the model."""
index_map, weights = wvd.load(te... | 5,352,182 |
def decode_layout_example(example, input_range=None):
"""Given an instance and raw labels, creates <inputs, label> pair.
Decoding includes.
1. Converting images from uint8 [0, 255] to [0, 1.] float32.
2. Mean subtraction and standardization using hard-coded mean and std.
3. Convert boxes from yxyx [0-1] to x... | 5,352,183 |
def bact_plot(samples, bacteroidetes, healthiest_sample):
"""
Returns a graph of the distribution of the data in a graph
==========
samples : pandas.DataFrame
The sample data frame. Must contain column `Bacteroidetes` and
`Firmicutes` that contain the percentage of those phyla.
... | 5,352,184 |
def dynamic_upload_to(instance, filename):
"""
根据链接类型,决定存储的目录
"""
file_dir = (LogoImgRelatedDirEnum.APP.value
if instance.link_type == LinkTypeEnum.LIGHT_APP.value else LogoImgRelatedDirEnum.ICON.value)
return os.path.join(file_dir, filename) | 5,352,185 |
def xdraw_lines(lines, **kwargs):
"""Draw lines and optionally set individual name, color, arrow, layer, and
width properties.
"""
guids = []
for l in iter(lines):
sp = l['start']
ep = l['end']
name = l.get('name', '')
color = l.get('color')
arrow = l.g... | 5,352,186 |
def test_fragment_three_aa_peptide_c_series():
"""Test c1/2 fragmentation"""
fragments = PeptideFragment0r('MKK', charges=[1],ions=['c']).df
# fragments = fragger.fragment_peptide(ion_series=['c'])
assert isinstance(fragments, DataFrame)
# assert len(fragments) == 3
row = fragments.iloc[0]
... | 5,352,187 |
def _emit_params_file_action(ctx, path, mnemonic, cmds):
"""Helper function that writes a potentially long command list to a file.
Args:
ctx (struct): The ctx object.
path (string): the file path where the params file should be written.
mnemonic (string): the action mnemomic.
cmds (list<string>): th... | 5,352,188 |
def annotate_validation_results(results, parsed_data):
"""Annotate validation results with potential add-on restrictions like
denied origins."""
if waffle.switch_is_active('record-install-origins'):
denied_origins = sorted(
DeniedInstallOrigin.find_denied_origins(parsed_data['install_ori... | 5,352,189 |
def test_player_1_wins_diagonally_at_beginning_of_the_main_diagonal(game):
"""
Board final state is
0 0 0 0 0 0 0
0 0 0 0 0 0 0
0 0 0 1 0 0 0
0 0 1 1 0 0 0
2 1 2 2 0 0 0
1 2 2 1 0 0 0
"""
[game.drop_checker_on_column(c) for c in [3, 3, 3, 4, 3, 4, 0, 5, 1, 6, 2]]
assert game.... | 5,352,190 |
def RunCommand(command,
input=None,
pollFn=None,
outStream=None,
errStream=None,
killOnEarlyReturn=True,
verbose=False,
debug=False,
printErrorInfo=False):
"""
Run a command, with optional input... | 5,352,191 |
def ignore_firstline_dedent(text: str) -> str:
"""Like textwrap.dedent(), but ignore first empty lines
Args:
text: The text the be dedented
Returns:
The dedented text
"""
out = []
started = False
for line in text.splitlines():
if not started and not line.strip():
... | 5,352,192 |
def test_provide_fail(providers: list[Provider]) -> None:
"""It raises an exception."""
with pytest.raises(Exception):
provide(providers, URL()) | 5,352,193 |
def clear_output(wait_time=0):
""" Clear terminal output"""
time.sleep(wait_time)
if 'linux' in sys.platform or 'darwin' == sys.platform:
os.system('clear')
else:
os.system('cls') | 5,352,194 |
def discrete_micro(micro, es):
""" Performs discrete policy for autoscaling engine.
Algorithm:
if microservice crosses high threshold:
scale-up microservice
else:
scale-down microservice
"""
micro_config = util.read_config_file(eng.MICRO_CONFIG)
if up_scale(... | 5,352,195 |
def read_file(filename):
"""
Read a file and return its binary content. \n
@param filename : filename as string. \n
@return data as bytes
"""
with open(filename, mode='rb') as file:
file_content = file.read()
return file_content | 5,352,196 |
def getdictkeys(value):
"""
Returns the ordered keys of a dict
"""
if type(value) == dict:
keys = list(value.keys())
keys.sort(key=toint)
return keys
return [] | 5,352,197 |
def exp_lr_scheduler(optimizer, epoch, init_lr=5e-3, lr_decay_epoch=40):
"""Decay learning rate by a factor of 0.1 every lr_decay_epoch epochs."""
lr = init_lr * (0.1**(epoch // lr_decay_epoch))
if epoch % lr_decay_epoch == 0:
print('LR is set to {}'.format(lr))
for param_group in optimizer.... | 5,352,198 |
def leff_obs(n_zbin, pos_pos_dir, she_she_dir, pos_she_dir, ell_filename, pos_nl_path, she_nl_path, noise_ell_path,
leff_path, save_dir):
"""
Obtain a pseudo- cut-sky 'observation' by sampling from the Wishart distribution with effective l.
Args:
n_zbin (int): Number of redshift bins.
... | 5,352,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.