content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def register_memory():
"""Register an approximation of memory used by FTP server process
and all of its children.
"""
# XXX How to get a reliable representation of memory being used is
# not clear. (rss - shared) seems kind of ok but we might also use
# the private working set via get_memory_map... | 5,291,300 |
def newgpg(ui, **opts):
"""create a new gpg instance"""
gpgpath = ui.config(b"gpg", b"cmd")
gpgkey = opts.get('key')
if not gpgkey:
gpgkey = ui.config(b"gpg", b"key")
return gpg(gpgpath, gpgkey) | 5,291,301 |
def test_sort_heroes_by_winrate(heroes, testconf_dict):
"""Tests `HeroGrid.sort_heroes_by_winrate()`"""
config = testconf_dict
for bracket in [b for b in Bracket if b != Bracket.ALL]:
h = HeroGrid(heroes, bracket, config)
h.sort_heroes_by_winrate()
for idx, hero in enumerate(h.heroes... | 5,291,302 |
def list_attached_volumes():
"""List attached volumes"""
parser = _get_parser()
argcomplete.autocomplete(parser)
_ = parser.parse_args()
if is_ec2():
for volume_id in info().volume_ids():
print(volume_id)
else:
parser.error("Only makes sense on an EC2 instance") | 5,291,303 |
def main(args=None):
"""Console script for cli_password_manager."""
pass_mgr = PasswordManager()
pass_mgr.screen()
return 0 | 5,291,304 |
def ensure_dir(directory, mode=0o777):
"""
Ensure that the provided directory and all of its parent directories exist.
This function is safe to execute on existing directories (no op).
:param directory: The directory to create (if it does not exist).
:param mode: The permission flags to use (if it ... | 5,291,305 |
def test(general: _general.Params, command: Params, stdout: TextIO) -> List[str]:
"""
Test the specified functions.
Return errors if any.
"""
if not command.path.exists():
return ["The file to be tested does not exist: {}".format(command.path)]
try:
source_code = command.path.r... | 5,291,306 |
def test_graph_depth_first_large():
"""Test_graph_depth_first_large."""
ng = Graph()
ng.add_edge(1, 2)
ng.add_edge(1, 7)
ng.add_edge(1, 8)
ng.add_edge(8, 9)
ng.add_edge(8, 12)
ng.add_edge(9, 10)
ng.add_edge(9, 11)
ng.add_edge(2, 6)
ng.add_edge(2, 3)
ng.add_edge(3, 4)
... | 5,291,307 |
def test_mindpage_lack_some_partition():
"""test page reader when some partition does not exist."""
create_cv_mindrecord(4)
paths = ["{}{}".format(CV_FILE_NAME, str(x).rjust(1, '0'))
for x in range(FILES_NUM)]
os.remove("{}".format(paths[0]))
with pytest.raises(MRMOpenError) as err:
... | 5,291,308 |
def vpg(env_fn, actor_critic=tabular_actor_critic.TabularVPGActorCritic,
n_episodes=100, env_kwargs={}, logger_kwargs={}, ac_kwargs={},
n_test_episodes=100, gamma=0.99, lam=0.95, bootstrap_n=3):
"""
Environment has discrete observation and action spaces, both
low dimensional so policy and va... | 5,291,309 |
def make_routing_table(obj, keys, prefix='on_'):
"""
:return:
a dictionary roughly equivalent to ``{'key1': obj.on_key1, 'key2': obj.on_key2, ...}``,
but ``obj`` does not have to define all methods. It may define the needed ones only.
:param obj: the object
:param keys: a list ... | 5,291,310 |
def series_greater_than_zero(series: pd.Series):
"""Return a bool series indicating whether the elements of s are > 0"""
return series > 0 | 5,291,311 |
def Seq_of_t(tau,Te,R):
"""
Python implementation of Seq(tau)
Time domain auto-correlation of a tunnel junction at thermal equilibrium
Latex :
S_{eq} = - \frac{\pi (k T)^2}{R \hbar} \sinh^{-2} \bigg( \frac{\pi k T}{\hbar} \tau \bigg)
See Also
--------
Th... | 5,291,312 |
def get_html_page(page_url):
""" Get the whole page source code"""
http = urllib3.PoolManager()
response = http.request('GET', page_url)
soup = BeautifulSoup(response.data, 'html.parser')
response.release_conn()
return soup | 5,291,313 |
def get_aname(value: str) -> str:
"""Pass."""
return strip_right(obj=str(value or ""), fix="_adapter") | 5,291,314 |
def air_cargo():
"""
[Figure 10.1] AIR-CARGO-PROBLEM
An air-cargo shipment problem for delivering cargo to different locations,
given the starting location and airplanes.
Example:
>>> from planning import *
>>> ac = air_cargo()
>>> ac.goal_test()
False
>>> ac.act(ex... | 5,291,315 |
def shutdown():
"""
Something is wrong and it does not worth it to keep running. This method
cancels all pending coroutines so the script can wrap up data collection
and move on (that is to say, compress the output we've got so far as an
.xz file).
"""
for task in asyncio.Task.all_tasks():
... | 5,291,316 |
def compare(r1, r2, label, outdir):
"""Compares results
* r1, r2 :: TesseraeResults
The score returned is the sum of the differences of scores between the same
match pair.
"""
with open(os.path.join(outdir, label+'.results'), 'w') as ofh:
r1_stop = {s for s in r1.stopwords}
... | 5,291,317 |
def test_warning_notification(node_factory):
""" test 'warning' notifications
"""
l1 = node_factory.get_node(options={'plugin': os.path.join(os.getcwd(), 'tests/plugins/pretend_badlog.py')}, allow_broken_log=True)
# 1. test 'warn' level
event = "Test warning notification(for unusual event)"
l1.... | 5,291,318 |
def create_spooled_temporary_file(filepath=None, fileobj=None):
"""
Create a spooled temporary file. if ``filepath`` or ``fileobj`` is
defined its content will be copied into temporary file.
:param filepath: Path of input file
:type filepath: str
:param fileobj: Input file object
:type fil... | 5,291,319 |
def save_frame(source_path, target_path, index=0, is_segm=False):
"""Saves a single frame of .mha cine-MRI slice as .npy and .png
Parameters
----------
source_path : Path
A path to the original file
target_path : Path
A path to save .npy and .png files
index : int
An index... | 5,291,320 |
def _split_comma_separated(string):
"""Return a set of strings."""
return set(filter(None, string.split(','))) | 5,291,321 |
def process_line(history, line):
""" Process one line from the history file, i.e. one quality report. """
report = eval(line)
date = fix_date(report.pop("date"))
history['dates'].append(date)
history['statuses'].append(dict())
for metric, old_value in report.items():
metric = fix_metric_... | 5,291,322 |
def make_ur_axialregion(asm_input, reg, mat_dict, flow_rate):
"""Process DASSH Assembly AxialRegion input to obtain un-rodded
region input parameters; to be used when instantiating un-rodded
region objects as axial regions in DASSH Assembly object"""
model = asm_input['AxialRegion'][reg]['model']
ar... | 5,291,323 |
def deprecate(
remove_by_version: str, replacement: Optional[str] = None
) -> Callable[[T], T]:
"""Return a function that can be used to deprecate functions. Currently
this is only used for deprecation of hook functions, but it may be expanded
to deprecated other things in the future.
Args:
... | 5,291,324 |
def triangular(n):
"""Compute the n-th triangular number."""
return np.floor_divide(n * (n + 1), 2) | 5,291,325 |
def delete_attachments_folder(sender, instance, *args, **kwargs):
"""
Delete recursively a folder
"""
delete_directory(instance.get_folder()) | 5,291,326 |
def list_captures():
"""Get a list of the videos and photo files on the GoPro
Use BeautifulSoup to parse the GoPro's list of captures
This list of captures is provided by the Cherokee webserver on the GoPro
To get this capture the GoPro Hero 3 Black
"""
page = urllib2.urlopen(CAPTURE_LIST)
... | 5,291,327 |
def get_nbest(lat, n, aw=1.0, lw=1.0, ip=0.0):
"""Obtain nbest hypotheses with scores from the lattice."""
hyps, scores = [], []
nbest_paths = lat.nbest(n, aw=aw, lw=lw, ip=0.0)
for path in nbest_paths:
hyp = [arc.dest.sym for arc in path]
# sos, eos, and other tokens are stripped
... | 5,291,328 |
def converge_clockwork(molobj, tordb, max_cost=2):
"""
molobj
torsions_idx
resolution
"""
atoms, xyz = cheminfo.molobj_to_xyz(molobj)
total_torsions = len(tordb)
print("total torsions", total_torsions)
# TODO Cache this
cost_input, cost_cost = clockwork.generate_costlist(tota... | 5,291,329 |
def test_nested_KeyValueList_CLI(spec_fixture,
workspace_manager_fixture,
test_workspace, tmpdir,
input_value, expected_output_dict):
"""Tests that CLI input of Complex type KeyValueList is nested in vars dict.
U... | 5,291,330 |
def static_filename(config, path, logger):
"""
Check if there is a static file matching 'path'.
:param config: IdP config
:param path: URL part to check
:param logger: Logging logger
:return: False, None or filename as string
:type config: IdPConfig
:type path: string
:rtype: False... | 5,291,331 |
def parse_args_and_maybe_launch(main: Callable) -> None:
"""Main entrypoint to HeyHi.
It does eveything HeyHi is for:
* Finds a config.
* Applies local and global includes and overridefs to the config.
* Determindes a folder to put the experiment.
* Detects the status of the exp... | 5,291,332 |
def get_tests():
"""Parse the TESTS file.
Parse the TESTS file and return a list of Entry objects
"""
if not check_test_index():
add_ids_test_index()
in_file = open(TESTS, 'rb')
entries = []
entry = Entry()
cur = entry.buffer
counter = 1
is_pre = False
p... | 5,291,333 |
def interpolate(xs: list, ys: list, zs: list, ratio: float) -> list:
""" This interpolates between two points """
x = xs[1] - xs[0]
y = ys[1] - ys[0]
z = zs[1] - zs[0]
return [xs[0] + x * ratio, ys[0] + y * ratio, zs[0] + z * ratio] | 5,291,334 |
def print_transactions(account):
"""
The print_transaction function is responsible for presenting
transaction details to end user.
:param account: The JSON decoded account and transaction data
:return: Nothing
"""
logging.info(
'Printing account and transaction data to console.')
... | 5,291,335 |
def str_to_sha256(s: str):
"""Generate a 256 bit integer hash of an arbitrary string."""
return int.from_bytes(hashlib.sha256(s.encode("utf-8")).digest(), "big") | 5,291,336 |
def comment(pitch_id):
"""This will add a comment
"""
pitches = Pitch.query.all()
comment_form = CommentForm()
comments = Comment.query.all()
if comment_form.validate_on_submit():
comment = Comment(comment = comment_form.comment.data, upvote = comment_form.vote.data,pitch_id = pitch_id,u... | 5,291,337 |
def get_template_redirects(site, template_name):
"""Gets the names of all of the template-space redirects to the
provided template. The names come without namespaces.
Example, if `site` is a enwiki site object:
>>> get_template_redicts(site, "Hexadecimal")
[u'hexdigit']
"""
print(template_n... | 5,291,338 |
def GetActiveWindow(*args):
"""
GetActiveWindow() -> Window
Get the currently active window of this application, or None
"""
return _misc_.GetActiveWindow(*args) | 5,291,339 |
def get_pysyd_parameters(args, parallel, CLI):
"""
Basic function to call the individual functions that load and
save parameters for different modules.
Parameters
----------
args : argparse.Namespace
command-line arguments
CLI : bool
`True` if running pysyd via command line
... | 5,291,340 |
def test_success_plugin(pytester):
"""test a success test"""
pytester.makepyfile(
common_code
+ """
def test_success():
assert True
""")
assertTest(pytester, "test_success", "passed", "OK", "passed", "OK") | 5,291,341 |
def setDict(d, params, val):
"""
d是一个字典或者列表,params是一个列表,通过params修改d中对应项的值为val
"""
index = "".join([f"[params[{i}]]" for i in range(len(params))])
exec(f"d{index} = val") | 5,291,342 |
def cityscapes_palette(num_cls=None):
"""
Generates the Cityscapes data-set color palette.
Data-Set URL:
https://www.cityscapes-dataset.com/
Color palette definition:
https://github.com/mcordts/cityscapesScripts/blob/master/cityscapesscripts/helpers/labels.py
Original source taken from:
... | 5,291,343 |
def entropymatrix(elements):
"""Calculates the unnormalized Shannon entropy for a numpy matrix."""
entropysum = 0
result = 0.0
for (x, y), value in numpy.ndenumerate(elements):
element = elements[x, y]
if element > 0:
result += xlogx(element)
entropysum += element... | 5,291,344 |
def dislodged_unit_type_from_area(
area_id: AreaID, board_state: np.ndarray) -> Optional[UnitType]:
"""Returns the type of any dislodged unit in the province."""
if board_state[area_id, OBSERVATION_DISLODGED_ARMY] > 0:
return UnitType(UnitType.ARMY)
elif board_state[area_id, OBSERVATION_DISLODGED_FLEET] >... | 5,291,345 |
def do_actual_chunks_test(
recipe_fixture,
executor,
inputs_per_chunk,
target_chunks,
error_expectation,
subset_inputs,
specify_nitems_per_input,
):
"""Check that chunking of datasets works as expected."""
RecipeClass, file_pattern, kwargs, ds_expected, target = recipe_fixture
... | 5,291,346 |
def try_with_lazy_context(error_context, f, *args, **kwargs):
"""
Call an arbitrary function with arbitrary args / kwargs, wrapping
in an exception handler that attaches a prefix to the exception
message and then raises (the original stack trace is preserved).
The `error_context` argument should be... | 5,291,347 |
def make_tweet_fn(text, time, lat, lon):
"""An alternate implementation of make_tweet: a tweet is a function.
>>> t = make_tweet_fn("just ate lunch", datetime(2012, 9, 24, 13), 38, 74)
>>> tweet_text_fn(t)
'just ate lunch'
>>> tweet_time_fn(t)
datetime.datetime(2012, 9, 24, 13, 0)
>>> latit... | 5,291,348 |
def user_login():
""" Endpoint for login password submission """
try:
hashfunc = hashlib.sha256()
hashfunc.update(request.form["password"].encode("utf-8"))
stored_hash = DSCLIENT.get(DSCLIENT.key("config", "password_hash"))
if stored_hash is not None:
salt = DSCLIENT... | 5,291,349 |
def initial_wumpus_axioms(xi, yi, width, height, heading='east'):
"""
Generate all of the initial wumpus axioms
xi,yi = initial location
width,height = dimensions of world
heading = str representation of the initial agent heading
"""
axioms = [axiom_generator_initial_location_assertions... | 5,291,350 |
def feed():
"""Live Video Feed """
global accessGranted
print "/feed Requested"
print accessGranted
if accessGranted:
return render_template('index.html')
else:
return redirect(url_for('login')) | 5,291,351 |
def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
op.execute("""
DELETE FROM context_implications WHERE
context_scope = "Program" AND
source_context_scope = "Audit"
""") | 5,291,352 |
def recursive_copy(src, dst):
"""
funcao que copia recursivamente os arquivos do diretorio fonte (src) para o
diretorii destino dst
"""
os.system("cd " + src)
command_copy = "cd config ;cp -Rv " + "." + " " + dst
print(command_copy)
os.system(command_copy) | 5,291,353 |
def load_model_from_vertex(
project: str,
region: str,
endpoint_id: str,
credentials: Optional[google.auth.credentials.Credentials] = None,
input_modalities: Optional[Dict[str, str]] = None
) -> model_lib.Model:
"""Loads a model from Cloud AI Vertex.
Args:
project: AI Platform project name.... | 5,291,354 |
def frametimes_from_file(infile):
"""infile is a frametimes file each row has
[frame number, start dur, stop] in seconds
Returns
-------
ft: array [start, duration, stop] in seconds for each frame
"""
ft = np.loadtxt(infile, delimiter = ',',
usecols = (1,2,3), skiprows =... | 5,291,355 |
def _get_wordpiece_detokenized_text(
token_span: _SpanType, raw_prediction: _RawPredictionType,
tokenizer: tokenization.FullTokenizer) -> str:
"""Gets the normalized answer token text given the token span."""
answer_tokens = tokenizer.convert_ids_to_tokens(
raw_prediction["long_token_ids"][token_span[... | 5,291,356 |
def dump_schema(URL, method, graphversion):
"""
Dump the GraphQL schema via Instrospection
:param URL: URL of the GraphQL instance
:param method: HTTP method to use
:param graphversion: GraphQL version
:return: None
"""
if graphversion > 14:
... | 5,291,357 |
def select_sentiment_by_date(search_string, search_date):
"""
Query column(s) from `search_string` in the tweets table where date LIKE `search_date`
:param search_string: column name(s) to Query
:param search_date: date to search
:return: Query results from search_string and search_date
"""
... | 5,291,358 |
def noaaDateConv(dataframe):
"""
This function takes a dataframe with datetime values and converts it into a format that the NOAA ccg tool can
easily read
:param dataframe: A dataframe that has to have a column labeled 'datetime' which contains dt.datetime formatted
items
:return: the same data... | 5,291,359 |
def sms_rest(msg):
"""
:param msg: <str>
:return: <int> return the difference between length of message and capacity of sms
"""
if sms_is_limited(msg):
return 70 - len(msg)
return 160 - len(msg) | 5,291,360 |
def mel_filter_bank(fs, nfft, lowfreq, maxfreq, widest_nlogfilt, widest_lowfreq, widest_maxfreq,):
"""Compute triangular filterbank for cepstral coefficient computation.
:param fs: sampling frequency of the original signal.
:param nfft: number of points for the Fourier Transform
:param lowfreq: lower l... | 5,291,361 |
def test_print_makefile_runner_image(mocked_print):
"""Tests result of a makefile generation for a runner image."""
name = 'afl-zlib-runner'
image = {
'tag': 'runners/afl/zlib',
'fuzzer': 'afl',
'benchmark': 'zlib',
'context': '.',
'dockerfile': 'docker/benchmark-run... | 5,291,362 |
def mod3():
"""
Create a simple model for multiple incorporation tests
"""
class mod3(mod1, mod1b, Model):
def __init__(self, name, description):
super().__init__(name, "Model 3")
self.a = self.createVariable("a",dimless,"a")
self.b = self.createVariable(... | 5,291,363 |
def git_reset(repo, hash_id):
"""Reset all git repositories to specified hash id
Usage: fab reset:repo=tracks, hash=hash_id
"""
require("fab_hosts", provided_by=[production])
config.hash = hash_id
config.repo = repo
invoke(git_reset) | 5,291,364 |
def is_convex_polygon(polygon): # noqa
"""Return True if the polynomial defined by the sequence of 2D
points is 'strictly convex': points are valid, side lengths non-
zero, interior angles are strictly between zero and a straight
angle, and the polygon does not intersect itself.
See: https://stack... | 5,291,365 |
def make_paragraph(text):
"""
An example function that takes in text and returns a paragraph from it that
can be used in the Knuth-Plass Algorithm.
"""
# Turn chunk of text into a paragraph
L = []
for ch in text:
if ch in ' \n':
# Add the space between words
... | 5,291,366 |
def even_time_series_spacing(dfi, n, t0=None, t_n=None):
"""Interpolate irregularly spaced time series.
To obtain regularly spaced data.
Parameters
----------
dfi : pandas dataframe
dataframe with one dimensional index containing
time stamps as index values.
n : int
n... | 5,291,367 |
def loader(path_zip, file_img):
"""
Load imagefile from zip.
"""
with zipfile.ZipFile(path_zip, 'r') as myzip:
img = Image.open(myzip.open(file_img))
return img.convert('RGB') | 5,291,368 |
def test_list_id_enumeration_3_nistxml_sv_iv_list_id_enumeration_4_2(mode, save_output, output_format):
"""
Type list/ID is restricted by facet enumeration.
"""
assert_bindings(
schema="nistData/list/ID/Schema+Instance/NISTSchema-SV-IV-list-ID-enumeration-4.xsd",
instance="nistData/list/... | 5,291,369 |
def get_triplets_at_q(grid_point,
bz_grid,
reciprocal_rotations=None,
is_time_reversal=True,
swappable=True):
"""Parameters
----------
grid_point : int
A grid point in the grid type chosen by is_dense_gp_map.
... | 5,291,370 |
def search_text_to_suggestion(search_text: SearchText, term: OntologyTerm) -> ConditionMatchingSuggestion:
"""
Does this term match the search_text, if so, add it as a suggestion (possibly with some validation)
"""
cms = ConditionMatchingSuggestion()
if match_info := search_text.matches(term):
... | 5,291,371 |
def get_section_with_options(section_name):
""" Takes section name(str) and returns section with option=value keys as json """
section_dict = {}
option_value = {}
for option, value in SAMBA_CONFIG_PARSER.items(section_name):
option_value[option] = value
section_dict[section_name] =... | 5,291,372 |
def get_bios_reader(model_name: str):
"""
Constructs and returns a Biosbias Reader based on the model name.
"""
if model_name == "BERT":
bert_indexer = PretrainedTransformerIndexer('bert-base-uncased')
tokenizer = PretrainedTransformerTokenizer('bert-base-uncased')
reader = TextC... | 5,291,373 |
def mocked_json_dumps(monkeypatch):
"""Monkeypatch json.dumps."""
mock_dumps = mock.MagicMock()
monkeypatch.setattr(json, "dumps", mock_dumps)
return mock_dumps | 5,291,374 |
def locale_factory(factory):
"""
Decorator which defines a factory function which
set forms locale. If not defined locale 'en_US' is used
:param factory: function
:return: str with locale
"""
global _get_locale
_get_locale = factory
return factory | 5,291,375 |
def get_mne_sample(n_trials=10):
"""Return sample data from the mne dataset.
```
In this experiment, checkerboard patterns were presented to the subject
into the left and right visual field, interspersed by tones to the
left or right ear. The interval between the stimuli was 750 ms.
Occasionall... | 5,291,376 |
def test_23_oadrRequestEvent():
"""
VEN/VTN, EiEvent Service, oadrRequestEvent Payload
oadrRequestEvent many only be sent in the VEN to VTN direction
"""
assert False | 5,291,377 |
def sample_affine_transform(batchsize,
n_dims,
rotation_bounds=False,
scaling_bounds=False,
shearing_bounds=False,
translation_bounds=False,
enable_90_r... | 5,291,378 |
def test_pdb_with_missing_chains(propane_pdb):
""" In response to an observed bug where various conversions would fail with a PDB file
that's missing chain data
"""
mol = propane_pdb
if not mdt.compute.packages.openbabel.force_remote:
pbmol = mdt.interfaces.mol_to_pybel(mol)
assert ... | 5,291,379 |
def get_square_lattice(height: int) -> RectangularLattice:
"""Returns a lattice of all points in a square of the given height.
Args:
height (int): Height of the lattice.
Returns:
The lattice.
"""
return get_rectangle_lattice(height, height) | 5,291,380 |
def fpn_search(fpn_arch, in_channels):
"""Fpn search warpper."""
return FPN_Search(in_channels=in_channels, out_channels=64, num_outs=4, fpn_arch_str=fpn_arch) | 5,291,381 |
def send_notification(weather_emoji, time_slot_emoji, weather_description, tempature):
"""
Send notification with given information
:param weather_emoji: current weather's status emoji string
:type Weather(enum)
:param time_slot: suitable emoji string wrt current time's slot.
:type... | 5,291,382 |
def get_fixture_dicts(
domain: str,
data_type_id: str,
filter_in: Optional[Dict[str, Optional[Iterable]]] = None,
filter_out: Optional[Dict[str, Any]] = None,
) -> List[Dict]:
"""
Returns a list of fixture data items as dictionaries.
They can be filtered using ``filter_in``, where if the it... | 5,291,383 |
def speedup(i):
"""
Input: {
samples1 - list of original empirical results
samples2 - list of new empirical results (lower than original is better)
(key1) - prefix for min/max/mean in return dict
(key2) - prefix for min/max/mean in return dict
... | 5,291,384 |
def create_table(table, params):
"""
"""
table_query = f"""
CREATE TABLE {table}(
year NUMERIC,
quarter NUMERIC,
month NUMERIC,
dayofmonth NUMERIC,
dayofweek NUMERIC,
flightdate DATE NOT NULL,
reporting_airline VARCH... | 5,291,385 |
def deserialize_trade(data: Dict[str, Any]) -> Trade:
"""
Takes a dict trade representation of our common trade format and serializes
it into the Trade object
May raise:
- UnknownAsset: If the fee_currency string is not a known asset
- DeserializationError: If any of the trade dict entr... | 5,291,386 |
def sweepAndSave(
inputDict,
extraInstruments = [],
saveEnable = True,
delay = 0.0,
plotVars = None,
comments = "No comments provided by user",
plotParams = [('go--','linear-linear'),('ro-','lin... | 5,291,387 |
def load_data(file=json_file):
"""Loads json file
:param file: Path object to load data from
:return: JSON data
"""
if not file.is_file():
soup = get_soup()
enchantment_data = generate_enchantments(soup)
minecraft_items = generate_items(enchantment_data)
export_data(... | 5,291,388 |
def tag_to_entity(tag_seq, label_alphabet):
"""
Collect predicted tags(e.g. BIO)
in order to get entities including nested ones
"""
entities = []
for idj, tag in enumerate(tag_seq):
try:
tag = label_alphabet.get_instance(tag)
if tag.split('-', 1)[0] == 'B' or tag... | 5,291,389 |
def calc_d(D_o, t, inner=False):
"""Return the outer or inner diameter [m].
:param float D_o: Outer diameter [m]
:param float t: Layer thickness [m]
:param boolean inner: Select diameter
"""
if inner:
return D_o - 2 * t
else:
return D_o + 2 * t | 5,291,390 |
def tobs():
"""Temperature observations from the last year"""
results = session.query(Stations.name, Measurements.date, Measurements.tobs).\
join(Measurements, Stations.station == Measurements.station).\
filter(Measurements.date> first_date()[0]).\
... | 5,291,391 |
def get_fake_prune_images() -> tuple[int, dict[str, Any]]:
"""Get fake prune images response"""
status_code = 200
response = {
"ImagesDeleted": [FAKE_LONG_ID],
"SpaceReclaimed": 123
}
return status_code, response | 5,291,392 |
def get_function_path(f):
"""
Passes the internal func_code to a attribute called internal_code on the wrapper.
Then we call the wrapper attribute which throws metadata of the internal function, and gets the path.
:param f: function
:return: path
"""
# does the wrapper is defining the new at... | 5,291,393 |
def get_all_completed_labels(engine, label_task_id, dataset_id=None, label_status="admin_complete"):
"""
Get latest label history entries for all completed (approved) labels
:param engine:
:param label_task_id:
:param dataset_id: optionally specify a dataset ID to only return labels for this datase... | 5,291,394 |
def plot_density_with_type(data_dict, title, fig_name, xlabel):
"""
绘制分类标识的概率密度图
:param data_dict: 每一类对应的数据列表的字典
:param title: 图片的标题
:param fig_name: 保存图片的名称
:param xlabel: X轴标题
:return:
"""
plt.figure()
for j, t in enumerate(sorted(list(data_dict.keys()))):
s... | 5,291,395 |
def rnn_stack(params=None,
tier : int = None,
last_tier = False,
dropout = 0,
recurrent_dropout = 0,
):
"""MultiRnn cell. Options
Args:
params = params class with cell args
tier = int designating the tier number
... | 5,291,396 |
def saveLabelList(labelList, filename):
"""
Save the labels informations on a seg file (or signal file)
Args:
labelsFilename: Array of the label of each node
filename: path of the label file
"""
assert filename.endswith('.seg') or filename.endswith('.txt'), 'Wrong file format'
... | 5,291,397 |
def signed_api_call(service: str, path: str = "/", method: str = 'GET',
configuration: Configuration = None,
secrets: Secrets = None,
params: Dict[str, Any] = None) -> requests.Response:
"""
Perform an API call against an AWS service.
This should ... | 5,291,398 |
def test_admin(app, admin_view):
"""Test flask-admin interace."""
# Test activation and deactivation
with app.app_context():
# create user and save url for testing
request_url = url_for("user.action_view")
kwargs = dict(email="test@test.cern", active=False,
pa... | 5,291,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.