content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def store_dns_info( matchobj):
"""
02:28:21.105740 IP 172.30.253.88.(53418) > (1.1.1.1.53: 18184)+ A? (blah.com). (26)
02:28:21.177084 IP 172.30.253.88.40745 > 1.1.1.1.53: 25446+ AAAA? blah.com. (26)
"""
key = matchobj.group(1) + matchobj.group(2)
domain = matchobj.group(3)
#print( f'store_dns() key... | 32,400 |
def edit_schedule(request):
"""Edit automatic updates schedule"""
if request.method == "POST":
schedule = models.UpdateSchedule.objects.get()
def fun(query):
return [int(x.strip()) for x in query.split(" ") if x.strip() != ""]
schedule.text = json.dumps({
models.... | 32,401 |
def infection_formula(name_model, infectious_number, classroom_volume, classroom_ach):
""" Calculate infection rate of with/without a mask by selected model. """
if name_model == "wells_riley":
# Use wells riley model.
effect_mask = 1.0 / ((1.0 - config.EXHALATION_FILTRATION_EFFICIENCY) * (1.0 ... | 32,402 |
def RetryWithBackoff(opts, fn, args=None, kwargs=None):
"""`fn` function must follow the interface suggested:
* it should return tuple <status, err> where
status - backoff status
err - error that happend in function to propogate it to caller."""
args = args or ()
kwargs = kwa... | 32,403 |
def export(args):
"""
This command export something
"""
if args['deb']:
print("run export deb packages")
elif args['docs']:
print("run export sources documents")
elif args['iso']:
print("run export iso images")
else:
print("You must specific that export") | 32,404 |
def fill_missing_ids(filename, id_map, highest_id):
"""
Open the workbook, fill in any None ids from the id_map with incremental values, and save it
:param filename: Name of the worksheet to be edited
:param id_map: The id_map generated by build_id_dict()
:param highest_id: The highest id used by a... | 32,405 |
def test_non_routable_igmp_pkts(do_test, ptfadapter, setup, fanouthost, tx_dut_ports, pkt_fields, igmp_version, msg_type, ports_info):
"""
@summary: Create an IGMP non-routable packets.
"""
# IGMP Types:
# 0x11 = Membership Query
# 0x12 = Version 1 Membership Report
# 0x16 = Version 2 Member... | 32,406 |
def noaa_api_formatter(raw, metrics=None, country_aggr=False):
"""Format the output of the NOAA API to the task-geo Data Model.
Arguments:
raw(pandas.DataFrame):Data to be formatted.
metrics(list[str]): Optional.List of metrics requested,valid metric values are:
TMIN: Minimum temper... | 32,407 |
def crop_wav(wav, center, radius):
"""
Crop wav on [center - radius, center + radius + 1], and pad 0 for out of range indices.
:param wav: wav
:param center: crop center
:param radius: crop radius
:return: a slice whose length is radius*2 +1.
"""
left_border = center - radius
right_b... | 32,408 |
def create_setup(filename_pyx, vobj_name, model_name, setup_filename, obj_directory):
"""
Create a setup.py file to compile the Cython Verilator wrapper.
"""
content = TEMPLATE_PYX.format(
model_name=model_name,
filename_pyx=filename_pyx,
verilator_include=VERILATOR_INCLUDE_DIR,
... | 32,409 |
def markdown(text: str) -> str:
"""Helper function to escape markdown symbols"""
return MD_RE.sub(r'\\\1', text) | 32,410 |
def import_sample(sample_name, db):
"""Import sample"""
cur = db.cursor()
cur.execute('select sample_id from sample where sample_name=?',
(sample_name, ))
res = cur.fetchone()
if res is None:
cur.execute('insert into sample (sample_name) values (?)',
(sam... | 32,411 |
def change_background_color_balck_digit(images, old_background, new_background, new_background2=None, p=1):
"""
:param images: BCHW
:return:
"""
if new_background2 is None:
assert old_background == [0]
if not torch.is_tensor(new_background):
new_background = torch.te... | 32,412 |
def main(args=None):
"""Console script for {{cookiecutter.repo_name}}."""
parser = get_parser()
args = parser.parse_args(args)
# Process args here
print(
"Replace this message by putting your code into "
"{{cookiecutter.project_slug}}.cli.main"
)
print(
"See argparse... | 32,413 |
def render_sprites(sprites, scales, offsets, backgrounds, name="render_sprites"):
""" Render a scene composed of sprites on top of a background.
An scene is composed by scaling the sprites by `scales` and offseting them by offsets
(using spatial transformers), and merging the sprites and background togethe... | 32,414 |
def load_shared_library(dll_path, lib_dir):
"""
Return the loaded shared library object from the dll_path and adding `lib_dir` to the path.
"""
# add lib path to the front of the PATH env var
update_path_environment(lib_dir)
if not exists(dll_path):
raise ImportError('Shared library doe... | 32,415 |
def test_yadis_user(client):
"""Check GET user-specific XRDS response"""
response = client.get(f'{_OPENID_URI_PATH_PREFIX}jbloggs')
assert response.status_code == 200
assert b"jbloggs</LocalID>" in response.data | 32,416 |
def smartAppend(table,name,value):
""" helper function for appending in a dictionary """
if name not in table.keys():
table[name] = []
table[name].append(value) | 32,417 |
def reply_garage_status(client, userdata, message):
"""
Callback method for when the latest status of the garage is requested.
"""
if sensor.is_active | sensor.value == 1:
lps("OPEN")
elif sensor.is_held | sensor.value == 0:
lps("CLOSED")
else:
lps("UNKNOWN") | 32,418 |
def apply_strategy_profile(player_configuration, strategy_profile):
"""
Applies a strategy profile to a list of players
:param player_configuration: List of players.
:param strategy_profile: Profile to apply
:return: None
"""
for reporter in player_configuration:
strategy_config = ... | 32,419 |
def preprocess_img(image):
"""Preprocess the image to adapt it to network requirements
Args:
Image we want to input the network (W,H,3) numpy array
Returns:
Image ready to input the network (1,W,H,3)
"""
# BGR to RGB
in_ = image[:, :, ::-1]
# image centralization
# They are the ... | 32,420 |
def tag_filter_matcher(
conjunction=None,
tag_key1_state=None,
tag_value1_state=None,
tag_key2_state=None,
tag_value2_state=None,
resource_inventory=None,
filter_tags=None,
tag_dict=None,
resource_name=None,
resource_arn=None,
):
"""Updates the passed resource_inventory dicti... | 32,421 |
def run(reload, once_time, debug):
"""
Запускает бота
"""
click.clear()
if reload:
args = sys.argv[1:]
if "-r" in args:
args.remove("-r")
if "--reload" in args:
args.remove("--reload")
args.append("--once-time")
# I tried to do smth fo... | 32,422 |
def test_client_exclude_fails_missing_session(server, client):
"""Should fail if a wrong access token is used."""
server.add(
responses.POST,
"https://example.com/api/panel/syncSendCommand",
status=401,
)
client._session_id = "test"
client._lock.acquire()
with pytest.rai... | 32,423 |
def main(key, root):
"""
Execution
key: str, Secret to encrypt the Thumbor URL
root: Path, Website root
"""
crypto = CryptoURL(key)
for i in root.glob('**/*.html'):
file = Path(i)
html = BeautifulSoup(file.read_text(), 'html.parser')
imgs = html.find_all('img')
... | 32,424 |
def _parse_ec_record(e_rec):
"""
This parses an ENSDF electron capture + b+ record
Parameters
----------
e_rec : re.MatchObject
regular expression MatchObject
Returns
-------
en : float
b+ endpoint energy in keV
en_err : float
error in b+ endpoint energy
... | 32,425 |
def setup(bot):
"""
Mandatory function to add the Cog to the bot.
"""
bot.add_cog(attribute_checker(AntistasiLogWatcherCog(bot))) | 32,426 |
def process_node_properties(node, node_type, intermine_model, rdf_prefixes, prefixes_used, pos):
"""
Process the properties of a graph node
:param node:
:param node_type:
:param intermine_model:
:param rdf_prefixes:
:param prefixes_used:
:param pos:
:return:
"""
for key, valu... | 32,427 |
def skpTime(time):
"""
Retorna un datetime con la hora en que la unidad genero la trama.
>>> time = '212753.00'
>>> datetime.time(int(time[0:2]), int(time[2:4]), int(time[4:6]), int(time[-2]))
datetime.time(21, 27, 53)
>>>
"""
import datetime
return datetime.tim... | 32,428 |
def calc_max_moisture_set_point(bpr, tsd, t):
"""
(76) in ISO 52016-1:2017
Gabriel Happle, Feb. 2018
:param bpr: Building Properties
:type bpr: BuildingPropertiesRow
:param tsd: Time series data of building
:type tsd: dict
:param t: time step / hour of the year
:type t: int
:re... | 32,429 |
def test_constructed_board_has_correct_open_cell(sol_board):
"""Test that the new Board has open cell in bottom corner."""
assert sol_board.open_cell_coords == (3, 3) | 32,430 |
def compress_pub_key(pub_key: bytes) -> bytes:
"""Convert uncompressed to compressed public key."""
if pub_key[-1] & 1:
return b"\x03" + pub_key[1:33]
return b"\x02" + pub_key[1:33] | 32,431 |
def is_tensor(blob):
"""Whether the given blob is a tensor object."""
return isinstance(blob, TensorBase) | 32,432 |
def transform_dlinput(
tlist=None, make_tensor=True, flip_prob=0.5,
augment_stain_sigma1=0.5, augment_stain_sigma2=0.5):
"""Transform input image data for a DL model.
Parameters
----------
tlist: None or list. If testing mode, pass as None.
flip_prob
augment_stain_sigma1
aug... | 32,433 |
def do_rollouts(env,
num_episodes: int,
max_episode_length: Optional[int] = None,
action_fn: Optional[Callable[[np.ndarray], np.ndarray]] = None,
render_mode: Optional[str] = None):
"""Performs rollouts with the given environment.
Args:
nu... | 32,434 |
def _(text):
"""Normalize white space."""
return ' '.join(text.strip().split()) | 32,435 |
def mean_IOU_primitive_segment(matching, predicted_labels, labels, pred_prim, gt_prim):
"""
Primitive type IOU, this is calculated over the segment level.
First the predicted segments are matched with ground truth segments,
then IOU is calculated over these segments.
:param matching
:param pred_... | 32,436 |
def get_tmp_directory_path():
"""Get the path to the tmp dir.
Creates the tmp dir if it doesn't already exists in this file's dir.
:return: str -- abs path to the tmp dir
"""
tmp_directory = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'tmp')
if no... | 32,437 |
def _infer_title(ntbk, strip_title_header=True):
"""Infer a title from notebook metadata.
First looks in metadata['title'] and if nothing is found,
looks for whether the first line of the first cell is an H1
header. Optionally it strips this header from the notebook content.
"""
# First try the... | 32,438 |
def stable_hash(value):
"""Return a stable hash."""
return int(hashlib.md5(str(value).encode('utf-8')).hexdigest(), 16) | 32,439 |
def test_api_page_delete_admin():
"""Can a user patch /api/v1/pages/<page_id> if admin"""
app = create_ctfd()
with app.app_context():
gen_page(app.db, title="title", route="/route", content="content")
with login_as_user(app, "admin") as client:
r = client.delete("/api/v1/pages/2"... | 32,440 |
def minimal_community(community_owner):
"""Minimal community data as dict coming from the external world."""
return {
"id": "comm_id",
"access": {
"visibility": "public",
},
"metadata": {
"title": "Title",
"type": "topic"
}
} | 32,441 |
def retrieve_descriptions(gene, descriptions, empties):
"""Given single gene name, grab possible descriptions from NCBI
and prompt user to select one"""
# Perform ESearch and grab list of IDs
query = gene + '[Gene Name]'
handle = Entrez.esearch(db='gene', term=query,
retmax=100,
... | 32,442 |
def readCmd():
""" Parses out a single character contained in '<>'
i.e. '<1>' returns int(1)
returns the single character as an int, or
returns -1 if it fails"""
recvInProgress = False
timeout = time.time() + 10
while time.time() < timeout:
try:
rc = ser.read().decode("u... | 32,443 |
def map_ground_truth(bounding_boxes, anchor_boxes, threshold=0.5):
"""
Assign a ground truth object to every anchor box as described in SSD paper
:param bounding_boxes:
:param anchor_boxes:
:param threshold:
:return:
"""
# overlaps shape: (bounding_boxes, anchor_boxes)
ove... | 32,444 |
def create_jumpbox(username, network, image_name='jumpBox-Ubuntu18.04.ova'):
"""Make a new jumpbox so a user can connect to their lab
:Returns: Dictionary
:param username: The user who wants to delete their jumpbox
:type username: String
:param network: The name of the network the jumpbox connect... | 32,445 |
def MakeFrame(ea, lvsize, frregs, argsize):
"""
Make function frame
@param ea: any address belonging to the function
@param lvsize: size of function local variables
@param frregs: size of saved registers
@param argsize: size of function arguments
@return: ID of function frame or -1
... | 32,446 |
def mip_solver(f, strides, arch, part_ratios, global_buf_idx, A, Z, compute_factor=10, util_factor=-1,
traffic_factor=1):
"""CoSA mixed integer programming(MIP) formulation."""
logging.info(f"LAYER {f}")
num_vars = len(A[0])
num_mems = len(Z[0])
m = Model("mip")
cost = []
c... | 32,447 |
def get_image_ids(idol_id):
"""Returns all image ids an idol has."""
c.execute("SELECT id FROM groupmembers.imagelinks WHERE memberid=%s", (idol_id,))
all_ids = {'ids': [current_id[0] for current_id in c.fetchall()]}
return all_ids | 32,448 |
def sortarai(datablock, s, Zdiff, **kwargs):
"""
sorts data block in to first_Z, first_I, etc.
Parameters
_________
datablock : Pandas DataFrame with Thellier-Tellier type data
s : specimen name
Zdiff : if True, take difference in Z values instead of vector difference
NB: this... | 32,449 |
def GetRemoteBuildPath(build_revision, target_platform='chromium',
target_arch='ia32', patch_sha=None):
"""Compute the url to download the build from."""
def GetGSRootFolderName(target_platform):
"""Gets Google Cloud Storage root folder names"""
if IsWindowsHost():
if Is64BitWin... | 32,450 |
def _extract_then_dump(hex_string: str) -> str:
"""Extract compressed content json serialized list of paragraphs."""
return json.dumps(
universal_extract_paragraphs(
unpack(bytes.fromhex(hex_string))
)
) | 32,451 |
def sso_redirect_url(nonce, secret, email, external_id, username, name, avatar_url, is_admin , **kwargs):
"""
nonce: returned by sso_validate()
secret: the secret key you entered into Discourse sso secret
user_email: email address of the user who logged in
user_id: the internal id of... | 32,452 |
def normalized_cluster_entropy(cluster_labels, n_clusters=None):
""" Cluster entropy normalized by the log of the number of clusters.
Args:
cluster_labels (list/np.ndarray): Cluster labels
Returns:
float: Shannon entropy / log(n_clusters)
"""
if n_clusters is None:
n_clusters... | 32,453 |
def step_impl(context):
"""
:type context: behave.runner.Context
"""
WebDriverWait(context.driver, 10).until(
EC.title_contains("Signup"))
current_page_title = context.driver.title
assert_that(current_page_title, contains_string("Signup")) | 32,454 |
def ingest_data(data, schema=None, date_format=None, field_aliases=None):
"""
data: Array of Dictionary objects
schema: PyArrow schema object or list of column names
date_format: Pandas datetime format string (with schema only)
field_aliases: dict mapping Json field names to desired schema names
... | 32,455 |
def build_messages(missing_scene_paths, update_stac):
""" """
message_list = []
error_list = []
for path in missing_scene_paths:
landsat_product_id = str(path.strip("/").split("/")[-1])
if not landsat_product_id:
error_list.append(
f"It was not possible to bui... | 32,456 |
def DecrementPatchNumber(version_num, num):
"""Helper function for `GetLatestVersionURI`.
DecrementPatchNumber('68.0.3440.70', 6) => '68.0.3440.64'
Args:
version_num(string): version number to be decremented
num(int): the amount that the patch number need to be reduced
Returns:
string: decremente... | 32,457 |
def hi_means(steps, edges):
"""This applies kmeans in a hierarchical fashion.
:param edges:
:param steps:
:returns: a tuple of two arrays, ´´kmeans_history´´ containing a number of
arrays of varying lengths and ´´labels_history´´, an array of length equal
to edges.shape[0]
"""
sub_... | 32,458 |
def tag_item(tag_name, link_flag=False):
"""
Returns Items tagged with tag_name
ie. tag-name: django will return items tagged django.
"""
print C3 % ("\n_TAGGED RESULTS_")
PAYLOAD["tag"] = tag_name
res = requests.post(
GET_URL, data=json.dumps(PAYLOAD), headers=HEADERS, verify=False)... | 32,459 |
def movie_info(tmdb_id):
"""Renders salient movie data from external API."""
# Get movie info TMDB database.
print("Fetching movie info based on tmdb id...")
result = TmdbMovie.get_movie_info_by_id(tmdb_id)
# TMDB request failed.
if not result['success']:
print("Error!")
# Can'... | 32,460 |
def diabetic(y, t, ui, dhat):
"""
Expanded Bergman Minimal model to include meals and insulin
Parameters for an insulin dependent type-I diabetic
States (6):
In non-diabetic patients, the body maintains the blood glucose
level at a range between about 3.6 and 5.8 mmol/L (64.8 and
104.4 mg/d... | 32,461 |
def get_spacy_sentences(doc_text):
"""
Split given document into its sentences
:param doc_text: Text to tokenize
:return: list of spacy sentences
"""
doc = _get_spacy_nlp()(doc_text)
return list(doc.sents) | 32,462 |
def get_recommendations(commands_fields, app_pending_changes):
"""
:param commands_fields:
:param app_pending_changes:
:return: List of object describing command to run
>>> cmd_fields = [
... ['cmd1', ['f1', 'f2']],
... ['cmd2', ['prop']],
... ]
>>> app_fields = {
... ... | 32,463 |
def file_based_convert_examples_to_features(examples,
label_list,
max_seq_length,
tokenizer,
output_file):
"""Convert a set of `InputExample... | 32,464 |
def main():
"""Digital bit output example."""
daq_device = None
dio_device = None
port_to_write = None
port_info = None
interface_type = InterfaceType.ANY
port_types_index = 0
try:
# Get descriptors for all of the available DAQ devices.
devices = get_daq_device_inventor... | 32,465 |
def hello():
"""Return a friendly HTTP greeting."""
return 'Hello World!!!' | 32,466 |
def test_land_initialisation():
"""
For all colors test that lands have given color and enter untapped.
"""
for color in ertai.colors:
card = ertai.BasicLand(color=color)
assert card.color == color
assert card.tapped is False | 32,467 |
def merge_day_month_year(data, day, month, year):
"""This method is not implemented yet."""
pass | 32,468 |
def _findStress(
syllables: Union[List[Syllable], List[List[str]]]
) -> Tuple[List[int], List[int]]:
"""Find the syllable and phone indicies for stress annotations"""
tmpSyllables = [_toSyllable(syllable) for syllable in syllables]
stressedSyllables: List[int] = []
stressedPhones: List[int] = []
... | 32,469 |
def test_discogs_ok_wantlist(mocker):
"""test_discogs_ok_default
Test if Discogs can obtain a wantlist.
Args:
mocker (pytest_mock.plugin.MockerFixture): Mocker.
"""
response_0 = {
'id': 1234567,
'username': 'dummy',
'resource_url': 'https://api.discogs.com/users/dummy... | 32,470 |
def add_flair_specific_reply(replyable, response_info):
"""Method to add a author's flair specific reply to the comment/submission.
:param replyable: The comment/submission on reddit
:param response_info: ResponseInfo containing hero_id and link for response
:return: None
"""
create_and_add_rep... | 32,471 |
def test_import_validation_fail(tmp_trestle_dir: pathlib.Path) -> None:
"""Validation failed."""
# catalog data
dup_cat = {
'uuid': '525f94af-8007-4376-8069-aa40179e0f6e',
'metadata': {
'title': 'Generic catalog created by trestle.',
'last-modified': '2020-12-11T02:04... | 32,472 |
def gen_dummy_object(class_title, doc):
"""
Create a dummy object based on the definitions in the API Doc.
:param class_title: Title of the class whose object is being created.
:param doc: ApiDoc.
:return: A dummy object of class `class_title`.
"""
object_ = {
"@type": class_title
... | 32,473 |
def gather_info(arguments) -> Info:
"""Gather info."""
if arguments.integration:
info = {"domain": arguments.integration}
elif arguments.develop:
print("Running in developer mode. Automatically filling in info.")
print()
info = {"domain": "develop"}
else:
info = _... | 32,474 |
def get_git_version():
"""
Get the version from git.
"""
return subprocess.check_output('git describe --tags'.split()).strip() | 32,475 |
def test_gamma_map_vol_sphere():
"""Gamma MAP with a sphere forward and volumic source space."""
evoked = read_evokeds(fname_evoked, condition=0, baseline=(None, 0),
proj=False)
evoked.resample(50, npad=100)
evoked.crop(tmin=0.1, tmax=0.16) # crop to window around peak
co... | 32,476 |
def get_mem_access_map(program, numpy_types=True, count_redundant_work=False,
subgroup_size=None):
"""Count the number of memory accesses in a loopy kernel.
:arg knl: A :class:`loopy.LoopKernel` whose memory accesses are to be
counted.
:arg numpy_types: A :class:`bool` speci... | 32,477 |
def __is_geotagging_input(question_input, _):
"""Validates the specified geotagging input configuration.
A geotagging input configuration contains the following optional fields:
- location: a string that specifies the input's initial location.
Args:
question_input (dict): An input configuratio... | 32,478 |
def _be_num_input(num_type, than, func=_ee_num_input, text='', error_text="Enter number great or equal than ",
error_text_format_bool=True,
error_text_format="Enter number great or equal than {}", pause=True, pause_text_bool=True,
pause_text='Press Enter...', cle... | 32,479 |
def createParetoFig(_pareto_df,_bestPick):
"""
Initalize figure and axes objects using pyplot for pareto curve
Parameters
----------
_pareto_df : Pandas DataFrame
DataFrame from Yahoo_fin that contains all the relevant options data
_bestPick : Pandas Series
Option data for the b... | 32,480 |
def _try_to_add_secondary_path(context: DependencyContext, dependency: Dependency, key: str, name: str,
path_set: DependencyPathSet, signatures: Optional[Dict[str, str]] = None):
"""
A function that attempts to load a secondary path (sources or javadoc) and, if
successful, add... | 32,481 |
def Plot_SNR(var_x,sample_x,var_y,sample_y,SNRMatrix,
fig=None,ax=None,
display=True,dl_axis=False,lb_axis=False,
smooth_contours=False, cfill=True,
display_cbar=True,x_axis_label=True,y_axis_label=True,
logLevels_min=-1.0,logLevels_max=0.0,
... | 32,482 |
def rem4(rings, si):
"""finds if the silicon atom is within a 4 membered ring"""
for i in range(len(rings)):
triangles = 0
distances = []
locations = []
for n in range(len(rings[i]) - 1):
for m in range(1, len(rings[i]) - n):
distances.append(distance(... | 32,483 |
def ilogit(x):
"""Return the inverse logit"""
return exp(x) / (1.0 + exp(x)) | 32,484 |
def get_out_of_bounds_func(limits, bounds_check_type="cube"):
"""returns func returning a boolean array, True for param rows that are out of bounds"""
if bounds_check_type == "cube":
def out_of_bounds(params):
""" "cube" bounds_check_type; checks each parameter independently"""
... | 32,485 |
def inspectors_for_each_mode(lead_type="lead_inspector") -> Dict[str, Set[str]]:
"""
We want to be able to group lead inspectors by submode.
"""
if lead_type not in ["lead_inspector", "deputy_lead_inspector"]:
raise ValueError("Can only query for lead_inspector and deputy_lead_inspector attribut... | 32,486 |
def add_shortcut_to_desktop_for_module(name):
"""
Adds a shortcut on a module which includes a script.
@param name name of the module
@return shortcut was added or not
"""
if name == "spyder":
from .link_shortcuts import add_shortcut_to_desktop, suffix
... | 32,487 |
def is_hdf_file(f):
"""Checks if the given file object is recognized as a HDF file.
:type f: str | tables.File
:param f: The file object. Either a str object holding the file name or
a HDF file instance.
"""
import tables
if((isinstance(f, str) and (f[-4:] == '.hdf' or f[-3:] == '.h5... | 32,488 |
def dummy_receivers(request, dummy_streamers):
"""Provides `acquire.Receiver` objects for dummy devices.
Either constructs by giving source ID, or by mocking user input.
"""
receivers = {}
for idx, (_, _, source_id, _) in enumerate(dummy_streamers):
with mock.patch('builtins.input', side_ef... | 32,489 |
def test_parse_one_histogram(p_check, mocked_prometheus_scraper_config):
"""
name: "etcd_disk_wal_fsync_duration_seconds"
help: "The latency distributions of fsync called by wal."
type: HISTOGRAM
metric {
histogram {
sample_count: 4
sample_sum: 0.026131671
bucket {
... | 32,490 |
def get_package_formats():
"""Get the list of available package formats and parameters."""
# pylint: disable=fixme
# HACK: This obviously isn't great, and it is subject to change as
# the API changes, but it'll do for now as a interim method of
# introspection to get the parameters we need.
def ... | 32,491 |
def construct_reverse_protocol(splitting="OVRVO"):
"""Run the steps in the reverse order, and for each step, use the time-reverse of that kernel."""
step_length = make_step_length_dict(splitting)
protocol = []
for step in splitting[::-1]:
transition_density = partial(reverse_kernel(step_mapping[... | 32,492 |
def tabinv(xarr, x):
"""
Find the effective index in xarr of each element in x.
The effective index for each element j in x is the value i such that
:math:`xarr[i] <= x[j] <= xarr[i+1]`, to which is added an interpolation fraction
based on the size of the intervals in xarr.
Parameter... | 32,493 |
def getldapconfig() :
""" Renvoie la configuration ldap actuelle"""
cfg = configparser.ConfigParser()
cfg.read(srv_path)
try :
return (cfg.get('Ldap', 'ldap_address'),
cfg.get('Ldap', 'ldap_username'),
cfg.get('Ldap', 'ldap_password').replace("$percent", "%"),
... | 32,494 |
def rename_dict_key(_old_key, _new_key, _dict):
"""
renames a key in a dict without losing the order
"""
return { key if key != _old_key else _new_key: value for key, value in _dict.items()} | 32,495 |
def api_browse_use_case() -> use_cases.APIBrowseUseCase:
"""Get use case instance."""
return use_cases.APIBrowseUseCase(items_repository) | 32,496 |
def treeIntersectIds(node, idLookup, sampleSet, lookupFunc=None):
"""For each leaf in node, attempt to look up its label in idLookup; replace if found.
Prune nodes with no matching leaves. Store new leaf labels in sampleSet.
If lookupFunc is given, it is passed two arguments (label, idLookup) and returns a... | 32,497 |
def get_descriptive_verbs(tree, gender):
"""
Returns a list of verbs describing pronouns of the given gender in the given dependency tree.
:param tree: dependency tree for a document, output of **generate_dependency_tree**
:param gender: `Gender` to search for usages of
:return: List of verbs as st... | 32,498 |
def client():
"""Return a client instance"""
return Client('192.168.1.1') | 32,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.