content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_multiserver_mode(pattern, options):
"""
Testing NetGear's Multi-Server Mode with three unique servers
"""
# initialize
frame_server = None
stream = None
server_1 = None
server_2 = None
server_3 = None
client = None
# define client-end dict to save frames i... | 67,700 |
def read_data_from_fp_numpy(fp):
"""
Read the data from a single Silixa xml file. Using a simple approach
Parameters
----------
fp : file, str, or pathlib.Path
File path
Returns
-------
data : ndarray
The data of the file as numpy array of shape (nx, ncols)
Notes
... | 67,701 |
def schedule_jobs(
fns, concurrency=DEFAULT_THREADS,
progress=None, total=None, green=False
):
"""
Given a list of functions, execute them concurrently until
all complete.
fns: iterable of functions
concurrency: number of threads
progress: Falsey (no progress), String: Progress + description
... | 67,702 |
def Hamming_bit_decoder(N,kind='bit',read=True,name='decoder'):
"""Hamming Gate resistant to bit-fips"""
circ=HammingCircuit(N, ancillas=N)
if kind=='phase':
circ.h([*range(2**N)])
circ.append(syndrome(N),[*range(2**N+N)])
circ.append(apply_syndrome(N),[*range(2**N+N)])
if read==True: ci... | 67,703 |
def _does_string_pass_simple_jndi_regex(input_string: str) -> bool:
"""Returns True/False if string contains at least one JNDI match, based on a simple regex"""
result = re.search(SIMPLE_JNDI_REGEX_PATTERN, input_string)
if result:
logger.debug(f"String passes simple JNDI regex: `{input_string}`")
... | 67,704 |
def test_cgac_agency_filter():
""" Ensure the CGAC agency filter is working """
# Create TAS models
tas1 = mommy.make('accounts.TreasuryAppropriationAccount', agency_id='NOT')
tas2 = mommy.make('accounts.TreasuryAppropriationAccount', agency_id='CGC')
# Create file B models
mommy.make('financia... | 67,705 |
def test_device_property(coresys):
"""Test device cgroup policy."""
device = Device(
"ttyACM0",
Path("/dev/ttyACM0"),
Path("/sys/bus/usb/001"),
"tty",
[Path("/dev/serial/by-id/fixed-device")],
{"MAJOR": "5", "MINOR": "10"},
)
assert device.by_id == device... | 67,706 |
def KeycodeToDIK(keycode):
"""
Convert a (Tkinter) keycode to a DirectInput Key code
If not in table, return keycode as hex
"""
_res = f'0x{keycode:02x}'
for dik, entry in DirectInputKeyCodeTable.items():
if entry[1] == keycode:
_res = dik
break
return _res | 67,707 |
def __string(input_string, name="", internal=False):
"""
Internal method for basic string validation.
"""
if input_string is None:
__ex("The %s is missing." % name, internal, ValueError)
if input_string == "":
__ex("The %s must not be empty." % name, internal, ValueError) | 67,708 |
def tts_request(announcement="Text to speech example announcement!") ->str:
"""Test function to check that the text to speech is working appropriately"""
engine = pyttsx3.init()
engine.say(announcement)
engine.runAndWait()
logging.info('tts test run')
return "Hello text-to-speech example" | 67,709 |
def roll_relationships(relationship_points: int, min_icons: int) -> List[IconRelationship]:
"""
:param relationship_points:
How many points are spent to relationship.
:param min_icons:
Minimum number of different icons to have a relationship to.
:return:
A list of icon relations... | 67,710 |
def ALMAUVFITSTab(inUV, filename, outDisk, err, \
exclude=["AIPS HI", "AIPS AN", "AIPS FQ", "AIPS SL", "AIPS PL"], \
include=[], logfile=""):
"""
Write Tables on UV data as FITS file
Write Tables from a UV data set (but no data) as a FITAB format file
History written... | 67,711 |
def create_children(input_node, node_holder, max_frag=0, smiles=None, log_file=None, recurse=True):
"""
Create a series of edges from an input molecule. Iteratively
:param input_node:
:param max_frag: Max initial fragments (or no limit if 0)
:param smiles: A SMILES string, for log/diagnostics only.
... | 67,712 |
def resolve_relations(
items: List[BibliographicItem],
) -> Dict[str, BibliographicItem]:
"""
For every given :class:`~relaton.models.bibdata.BibliographicItem`
of ``items``, scans for any relations that are ``formattedref``-only links.
Fetches all referenced documents and returns a dictionary
... | 67,713 |
def test_remove_correctly_removes(three_word_trie_no_overlap):
"""Test that a word is correctly removed from trie."""
three_word_trie_no_overlap.remove('cat')
assert three_word_trie_no_overlap.size() == 2
assert three_word_trie_no_overlap.contains('cat') is False | 67,714 |
def rabbit_breed():
"""
This function breeds rabbits. This modifies rabbits by appending to the
list.
The older the rabbit, the more kittens they might produce.
Returns
-------
None.
"""
#print("breed")
for i in range(len(rabbits)):
number_of_kittens = random.... | 67,715 |
def typify(node):
"""Convert the input into the appropriate
type of ExpressionBase-derived Node. Will
apply pattern matching to determine if a
passed string looks like a numerical constant
or if the input is a numerical constant, return
the appropriate node type.
Parameters
----------
... | 67,716 |
def file_exists(file_path):
""" Returns true if file exists, false if it doesnt """
file = pathlib.Path(file_path)
return file.is_file() | 67,717 |
def hasher(obj):
"""Returns non-cryptographic hash of a JSON-serializable object."""
h = hashlib.md5(json.dumps(obj).encode())
return h.hexdigest() | 67,718 |
def long_word_pct(df):
"""
Get percentage of long words.
Long words are defined as having more than 8 chars.
Needs features:
Words
Adds features:
Long_word_percent: percentage of long words
:param: the dataframe with the dataset
:returns: the dataframe with the added f... | 67,719 |
def check_answer(question_id, answers_list):
"""
Check answers for question.
Convert answers to boolean values for comparing with correct answers.
Answer wil get point if correct, not empty and all correct choices was chosen.
@param question_id: Question object id --> int
@param answers_list: ... | 67,720 |
def _to_float(expr):
"""Converts a sympy expression to a Python float
The given expression must be a sympy ``Number`` isinstance, or ValueError
will be raised.
"""
res = expr.evalf()
if isinstance(res, Number):
return float(res)
else:
raise ValueError(
'Expressi... | 67,721 |
def atom_count(gra, dummy=False, with_implicit=True):
""" count the number of atoms in this molecule
by default, this includes implicit hydrogens and excludes dummy atoms
"""
if not dummy:
gra = without_dummy_atoms(gra)
natms = len(atoms(gra))
if with_implicit:
atm_imp_hyd_vlc_d... | 67,722 |
def isstarboard(ctx, scene, node1, node2):
""" Returns True if node1 is on the right of node2 based on a view matrix
calculated from the 'face' of node 2.
For node1 to be on the right of node2:
- node2 to must be considered to have a front face.
- the view transformed bounding box o... | 67,723 |
def get_tls_path(opts, id_type, namespace, release):
"""Get path to the directory containing TLS materials for a node
Args:
opts (dict): Nephos options dict.
id_type (str): Type of ID we use.
namespace (str): Name of namespace.
release (str): Name of release/n... | 67,724 |
def _length_hint(obj):
"""Returns the length hint of an object."""
try:
return len(obj)
except TypeError:
try:
get_hint = type(obj).__length_hint__
except AttributeError:
return None
try:
hint = get_hint(obj)
except TypeError:
... | 67,725 |
def add_system_to_temp_database(temp_db, config_tmp_path, runner):
""" Fixture to add and delete system from existing database """
result = runner.invoke(sap_cli,
args=["-path", config_tmp_path.config_path,
"add",
"-sys... | 67,726 |
def _save_given_shuffled_titles(
session: Session,
given_on: datetime,
new_titles: NewShuffledTitles,
):
"""Adds new given shuffled titles to database"""
for participant_id, title in zip(
new_titles.get_participant_ids(), new_titles.titles
):
record = GivenShuffledTitle(
... | 67,727 |
def _root_sort_key(root):
"""
Allow root comparison when sorting.
Args:
root (str or re.Pattern): Root.
Returns:
str: Comparable root string.
"""
try:
return root.pattern
except AttributeError:
return root | 67,728 |
async def delete_name(message):
"""
Allows the player to delete a name from the list before submitting, in the case of a bugged text detection.
:param message:
:return:
"""
if message_state[message.author.id] == 'VALIDATING':
if len(char_name_dict[message.author.id]) > 1:
tar... | 67,729 |
def optics_propagate(empty_lamda, grid_size, PASSVALUE):
"""
#TODO pass complex datacube for photon phases
propagates instantaneous complex E-field through the optical system in loop over wavelength range
this function is called as a 'prescription' by proper
uses PyPROPER3 to generate the complex... | 67,730 |
def get_layer(keras_tensor):
"""
Returns the corresponding layer to a keras tensor.
"""
layer = keras_tensor._keras_history[0]
return layer | 67,731 |
def test_correctness(vpath: str) -> None:
"""Test Reader correctness by comparing with OpenCV Reader
Args:
vpath (str): path to video
"""
# open reader
reader = Reader(vpath)
# opencv cv reader
cv2_reader = cv2.VideoCapture(vpath)
for frame in reader:
assert np.array_e... | 67,732 |
def cp(src, dst, force=False):
"""
Copy data from src to dst.
Parameters
----------
src : string
Input filename
dst : string
Output path or filename where to copy src
"""
if force and not os.path.isdir(dst):
mkdir(os.path.dirname(dst))
shutil.copyfile(src, ds... | 67,733 |
def unique(table, key=None, presorted=False, buffersize=None, tempdir=None,
cache=True):
"""
Select rows with unique values under a given key (or unique rows
if no key is given). E.g.::
>>> import petl as etl
>>> table1 = [['foo', 'bar', 'baz'],
... ['A', 1, 2],... | 67,734 |
def apply_over_axes(func, a, axes):
"""
Applies a function repeatedly over multiple axes.
`func` is called as `res = func(a, axis)`, where `axis` is the first element of `axes`.
The result `res` of the function call must have either the same dimensions as `a` or
one less dimension. If `res` has one... | 67,735 |
def history(dynamodb_client, table_name, metric, i, interval=50):
"""
Returns an event's history (items in a DynamoDB table) as a DataFrame
:param dynamodb_client: Connection to DynamoDB service
:param table_name: Name of DynamoDB table (string)
:param metric: Name of metric subtopic (string)
:p... | 67,736 |
def with_migrations(*migrations):
"""
Decorator taking a list of migrations. Creates a temporary directory writes
each migration to a file (named '0.py', '1.py', '2.py' etc), calls the
decorated function with the directory name as the first argument, and
cleans up the temporary directory on exit.
... | 67,737 |
def cleanObject(data):
"""
input raw pandas dataframe
output : cleaned form object
"""
# =============================================================================
# load data
# =============================================================================
#clean id
data=data... | 67,738 |
def test_name002_2113_name002_2113_v(mode, save_output, output_format):
"""
TEST :Facet Schemas for string : value=_foo
"""
assert_bindings(
schema="msData/datatypes/Name.xsd",
instance="msData/datatypes/Name002.xml",
class_name="Root",
version="1.1",
mode=mode,
... | 67,739 |
def create_lm_ds_kilt_eli5(
*,
tokenizer,
context_window_size, # pylint: disable=unused-argument
dataset_name, # pylint: disable=unused-argument
batch_size,
split,
db_path, # pylint: disable=unused-argument
random_seed,
use_subset, # pylint: disable=unused-argument
subset_siz... | 67,740 |
def memoize(**kwargs):
"""
Memoize Function.
Arguments:
until: func, memoize until time specified (seconds, using time.time)
disable_kw bool, do not memoize around kwargs. This is a significant performance benefit.
ignore_nulls: bool, do not store null values in the cache.... | 67,741 |
def logberkopec_hypergeometric_tail_inverse(k, m, log_delta, M, start='below'):
"""
Computes the pseudo-inverse of the hypergeometric distribution tail for a logarithmic delta term and with a logarithmic algorithm to avoid under- and overflows and less memory usage.
Args:
k (int): Number of errors ... | 67,742 |
def MFInt(indices):
"""
indices a (N,) array of integers
"""
return " ".join([('%i' % i) for i in indices]) | 67,743 |
def change_link_state(link_list,linkstate):
""" Link State Change Function
Calling this function with a list of interface names and a desired
state will have the netlink library attempt to enforce the desired
state on the specified links in the list
"""
# Initialize the pyroute2 library
ip =... | 67,744 |
def ecdump(ec_file, verbose):
"""
Print out information about a binary EC file (ec_file)
"""
utils.configure_logging(verbose)
methods.ecdump(ec_file) | 67,745 |
def isolated_recovery_rate_10():
"""
Real Name: b'isolated recovery rate 10'
Original Eqn: b'Isolated 10*(1-fraction of critical cases 10)/isolation duration 10'
Units: b'person/Day'
Limits: (None, None)
Type: component
b''
"""
return isolated_10() * (1 - fraction_of_critical_cases_... | 67,746 |
def celery(package, config=None, module_path=None):
"""Run a celery server(worker or beat)"""
_set_server_config('celery', package, module_path, config_file=config)
celery_app.serve() | 67,747 |
def invert_jacdict(jacdict, unknowns, targets, tau, test_invertible=False):
"""Given a nested dict of ATI Jacobians that maps unknowns -> targets, e.g. an asymptotic
H_U matrix, get the inverse H_U^(-1) as a nested dict.
This is implemented by inverting the FFT-based multiplication that was implemented abo... | 67,748 |
def test_pandas_timestamp_tz():
"""Test that Pandas Timestamp tz objects are not considered as daily."""
ts = pd.Timestamp("2020/12/30", tz="America/Chicago")
ob = observation.Observation("XXX", "XXX", ts)
assert ob.data["_isdaily"] is False
assert ob.data["valid"] == utc(2020, 12, 30, 6) | 67,749 |
def stream_view() -> Response:
"""/"""
# Generator
rows = generate()
# returns Response to stream the data
return Response(stream_with_context(stream_template('layouts/row.html', rows=rows))) | 67,750 |
async def validate_usb_connection(self, device_path=None) -> dict[str, str]:
"""Test if device_path is a real Plugwise USB-Stick."""
errors = {}
# Avoid creating a 2nd connection to an already configured stick
if device_path in plugwise_stick_entries(self):
errors[CONF_BASE] = "already_configur... | 67,751 |
def _validate_and_fill_dertype(dertype=None):
"""Issue `do_gradient=True` unless `dertype` is energy or nonsense."""
if dertype is None:
do_gradient = True
elif der0th.match(str(dertype)):
do_gradient = False
elif der1st.match(str(dertype)):
do_gradient = True
else:
... | 67,752 |
def accepted(message: Any = None) -> Response:
"""
Returns an HTTP 202 Accepted response, with optional message;
sent as plain text or JSON.
"""
return status_code(202, message) | 67,753 |
def test_story_contract_representation_with_spec_with_args(m):
"""
Show collected story composition contract as mounted story
attribute. We show each story arguments.
"""
class T(m.ParamChild, m.StringMethod):
pass
class Q(m.ParamParent, m.NormalParentMethod, T):
pass
cla... | 67,754 |
def readheader(struct,hdu):
"""read image from HDU structure"""
headerdata=[]
try:
headerdata = struct[hdu].header
except:
raise SaltIOError('Cannot read header data from HDU '+str(hdu))
return headerdata | 67,755 |
def subsample_files_in_tree(root, filename_pattern, size):
"""
Sub-sample list of filenames under root folder.
This ensures to keep sample balance among folders.
Arguments:
root: Root folder to search files from.
filename_pattern: Wildcard pattern like: '*.png'.
size:
... | 67,756 |
def can_handle(ctx, permission: str):
""" Checks if bot has permissions or is in DMs right now """
return isinstance(ctx.channel, discord.DMChannel) or getattr(
ctx.channel.permissions_for(ctx.guild.me), permission
) | 67,757 |
def s3_buckets(s3_bucket_name, aws_s3_client, aws_region) -> List[str]:
"""
The s3_buckets fixture creates moto-buckets for the s3_bucket_name
fixture, with a numeric suffix for each bucket, where the
moto-buckets are cleaned up on exit.
:return: a list of bucket names
"""
with mock_s3():
... | 67,758 |
def parse_trace(ifile):
"""parse the trace data file
Args:
ifile: input trace data file
Return:
None
"""
fd = open(ifile, 'rb')
while True:
global TSC_BEGIN, TSC_END
try:
line = fd.read(struct.calcsize(TRCREC))
if not line:
... | 67,759 |
def sumtype(
typename: str,
variant_specs: List[ Tuple[str, List[Tuple[str, type]] ] ],
*,
typecheck='always',
constants=False,
verbose=False,
allow_zero_constructors=False,
_module_name=None
) -> type:
"""
`typecheck` must be one of ('always', 'debug', 'never')
"""
if not allow_zero_constructor... | 67,760 |
def get_text(item_id):
"""
Returns the text of an item
:param item_id: Id of the item
:return: str: Text
"""
if item_id in all_items:
return all_items[item_id]['text']
return None | 67,761 |
def run(parser, args):
"""Perform NCBIWWW of the seeds."""
logger.info("Starting NCBI WWW BLAST of seed sequences and reference.")
logger.info("Arguments are %s", vars(args))
out_dir = os.path.dirname(args.in_tsv)
jobs = []
logger.info("Running NCBI WWW BLAST for each sequence...")
header... | 67,762 |
def _matches_generator_helper(type_obj, allowed_types):
"""Check if type_obj matches a Generator/AsyncGenerator type."""
if isinstance(type_obj, _typing.Union):
return all(_matches_generator_helper(sub_type, allowed_types)
for sub_type in type_obj.options)
else:
base_cls = type_obj
if i... | 67,763 |
def handle_failure(request):
""" Handles failure message from paytrail """
# Get parameters
order_number = request.GET.get('ORDER_NUMBER', '')
timestamp = request.GET.get('TIMESTAMP', '')
authcode = request.GET.get('RETURN_AUTHCODE', '')
secret = settings.VMAKSUT_SECRET
# Validate, and mar... | 67,764 |
def test_generate_video_dont_enlarge(tmpdir, fmt):
"""Video dimensions should not be enlarged."""
base, ext = os.path.splitext(TEST_VIDEO)
dstfile = str(tmpdir.join(base + '.' + fmt))
settings = create_settings(video_size=(1000, 1000), video_format=fmt)
generate_video(SRCFILE, dstfile, settings)
... | 67,765 |
def _get_transformer_list(estimators):
"""
Construct (name, trans, column) tuples from list
"""
transformers, columns = zip(*estimators)
names, _ = zip(*_name_estimators(transformers))
transformer_list = list(zip(names, transformers, columns))
return transformer_list | 67,766 |
def dl_github_repo(install_path, api_url, html_url):
"""
Downloads all files from a Github repo, uses the frontend as much as
possible in order to minimize API requests.
:param install_path: Where to "clone" the repo.
:param api_url: Github repo API url, of the form
`repos/<owne... | 67,767 |
def pane_list(pane, ids=None, list_all=False):
"""Get a list of panes.
This makes it easier to target panes from the command line.
"""
if ids is None:
ids = []
if list_all or pane.identifier != -1:
ids.append(pane)
for p in pane.panes:
pane_list(p, ids, list_all=list_all... | 67,768 |
def nopush(ui, repo):
# The doc string below will show up in hg help.
"""Prohibit pushes from predefined directories."""
pwd = os.getcwd()
dirs = ui.configlist('nopush', 'nopush_dirs', default=None, untrusted=False)
try:
for dir in dirs:
if pwd == dir:
# Raise an Abort exception if the node has only one ... | 67,769 |
def make_undo_button(player):
"""Show undo button in player color."""
if player.color == 'W':
button_color = WHITE
else:
button_color = GRAY
undo_button = Button((BUTTON_MEASURES[0] + 50, BUTTON_MEASURES[1] + 20),
"UNDO", 40, button_color, BLUE, 1.5)
undo_but... | 67,770 |
def _load_image_set_index(_year, _image_set):
"""
Load the indexes listed in this dataset's image set file.
"""
# Example path to image set file:
# self._devkit_path + /VOCdevkit2007/VOC2007/ImageSets/Main/val.txt
_devkit_path = os.path.join(cfg.DATA_DIR, 'VOCdevkit' + _y... | 67,771 |
def check_indent(codestr):
"""If the code is indented, add a top level piece of code to 'remove' the indentation"""
i = 0
while codestr[i] in ["\n", "\t", " "]:
i = i + 1
if i == 0:
return codestr
if codestr[i-1] == "\t" or codestr[i-1] == " ":
if codestr[0] == "\n":
... | 67,772 |
def agentGet(_id):
""" Responds to GET requests sent to the /v1/agents/<_id> API endpoint. """
if request.args.get('attrs') is None:
attrs = None
else:
attrs = request.args.get('attrs')
return ContextBroker.Agents.getAgent(_id, attrs) | 67,773 |
def run_SAM(df_data, skeleton=None, device=None, **kwargs):
"""Execute the SAM model.
:param df_data: Input data; either np.array or pd.DataFrame
"""
device = SETTINGS.get_default(device=device)
train_epochs = kwargs.get('train_epochs', 1000)
test_epochs = kwargs.get('test_epochs', 1000)
ba... | 67,774 |
def normalize_path(path):
"""
Strip non-alphanumeric characters from path and downcase it.
"""
stripped = NORMALIZER.sub('', path)
downed = stripped.lower()
return downed | 67,775 |
def target_encode_loo(X, y=None, cols=None, dtype='float64', bayesian_c=None):
"""Leave-one-out target encode columns in a DataFrame.
Replaces category values in categorical column(s) with the mean target
(dependent variable) value for each category, using a leave-one-out
strategy such that no sample's... | 67,776 |
def save_files(folder: Filepath, file_data: Dict[Filepath, str]) -> bool:
"""Save all `file_data` under `folder`.
All paths in `file_data` are relative to `folder`.
Inputs:
folder: Filepath
file_data: Dict[Filepath, str]
The file name (relative to `folder`) and its content.
... | 67,777 |
def build_forecast(
data,
forecast_range,
truncate_range=0
):
"""build a forecast for publishing
Args:
data (:obj:`pandas.data_frame`): data to build prediction
forecast_range (int): how much time into the future to forecast
truncate_range (int, optional): trunca... | 67,778 |
def assert_version():
"""
assert repo version integreity
"""
output = run_cmd("make show-version")
clean_version = None
bumped_clean_version = None
for line in output.splitlines():
if "bumped clean version:" in line:
bumped_clean_version = line.split(': ')[1]
... | 67,779 |
def institute(
institute_id,
sanger_recipient,
coverage_cutoff,
frequency_cutoff,
display_name,
remove_sanger,
):
"""
Update an institute
"""
adapter = store
LOG.info("Running scout update institute")
try:
adapter.update_institute(
internal_id=institu... | 67,780 |
def get_psycopg2_connection_kwargs(_id: str) -> dict:
"""Get connection kwargs for psycopg2"""
return get_connection_kwargs(_id, credentials_mapping=PSYCOPG2_CONNECTION_KWARG_MAP) | 67,781 |
def motivation_adjustment():
"""
Real Name: Motivation Adjustment
Original Eqn: (Income - Motivation) / Motivation Adjustment Time
Units: 1/Month
Limits: (None, None)
Type: component
"""
return (income() - motivation()) / motivation_adjustment_time() | 67,782 |
def distance(data,a,b,variables_numeriques):
"""
Cette fonction permet de calculer la distance entre deux éléments.
Les paramètres sont :
- Les données du graph
- Noeud du départ graphe
- Noeud de la destination graphe
- Les coordonnées latitude et longitude
"""
... | 67,783 |
def login(session, url, username, password):
"""
Login to given url with given username and password.
Use given request session (requests.session)
"""
log.debug("Trying to login to {0} with user: {1} and pass {2}".format(url,username,password))
response = session.post(url,
... | 67,784 |
def pick_card(deck_to_pick_from):
"""Returns a random card from the deck"""
return random.choice(deck_to_pick_from) | 67,785 |
def bbox_iou(box1, box2, xyxy=True):
"""Compute Intersection over Union (IoU) of two given bounding boxes."""
# get x1, x2, y1, y2 coordinates for each box
box2 = box2.t()
if not xyxy:
b1_x1, b1_y1, b1_x2, b1_y2 = xywh2xyxy(box1)
b2_x1, b2_y1, b2_x2, b2_y2 = xywh2xyxy(box2)
else:
... | 67,786 |
def confirm(
changeset_id,
api_key=None,
client_secret=None,
auth_token_manager=None,
timeout=None,
):
"""Confirm asset change notifications.
"""
auth_token_manager = flex_auth(
api_key=api_key,
client_secret=client_secret,
auth_token_manager=auth_token_manager,
... | 67,787 |
def get_hash(string):
"""
Returns a hash from a string
Parameters:
string (str): the string used to generate the hash
Returns:
hash(string): the hash of the string
"""
byte_string = string.encode()
digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
digest.up... | 67,788 |
def default_options() -> (OptionSet,
Mapping[str, Labels],
Sequence[int],
Sequence[int]):
"""
Default options for plotting data
Returns
-------
opts = dict of dicts of options for plots
opts['im']
opt... | 67,789 |
def tfds_path(*relative_path: PathLike) -> ReadOnlyPath:
"""Path to `tensorflow_datasets/` root dir.
The following examples are equivalent:
```py
path = tfds.core.tfds_path() / 'path/to/data.txt'
path = tfds.core.tfds_path('path/to/data.txt')
path = tfds.core.tfds_path('path', 'to', 'data.txt')
```
N... | 67,790 |
def get_dictum_info(channel):
"""
获取每日一句。
:return:str
"""
if not channel:
return None
source = DICTUM_NAME_DICT.get(channel, '')
if source:
addon = importlib.import_module('everyday_wechat.control.onewords.' + source, __package__)
dictum = addon.get_one_words()
... | 67,791 |
def process_file(arg, filename):
"""Process the xcpp file. """
cfg = get_cfg(arg, 'cpp', DEFAULTS)
cfg['xcpp']['filename'] = extract_name(filename)
xcfile = FileParser(filename).parse()
check_inputs(xcfile, cfg, 'cpp')
for func in xcfile.function:
process_function(xcfile, cfg, func) | 67,792 |
def graph_users(request):
"""Grafico plot del modelo de usuarios."""
user = User.objects.all().values()
df = pd.DataFrame(user, columns=['date_joined'])
data = df['date_joined'].dt.month_name().value_counts()
data = data.sort_values(ascending=True)
data.plot.bar(xlabel="Mes", ylabel="Usuarios", ... | 67,793 |
def create_user(**params: str) -> User:
"""Creates a User with a given params"""
return get_user_model().objects.create_user(**params) | 67,794 |
def crossover(population, parents, gp_par):
"""
Generates offspring by crossovers
"""
if len(parents) % 2 != 0:
raise ValueError("Number of parents for crossover must be even number")
crossover_offspring = []
max_attempts = 100
for _ in range(gp_par.n_offspring_crossover):
... | 67,795 |
def spacy_evaluator(ner_model, examples):
"""
Evaluate the created NER model using different metrics
Args:
ner_model (spacy model object): The dataset
examples (list): testing examples
Returns:
score_object (score object): object with different scoring metrics
"""
try:... | 67,796 |
def _process_list_for_saving(l: [list, tuple]) -> [list, tuple]:
"""
The yaml.dump function can't save PyTorch tensors, numpy arrays, or callables, so we cast them to types it can save.
:param l: list or tuple containing parameters to save
:return: list or tuple with values processable by yaml.dump
... | 67,797 |
def road_curvature_F5(curvature, ego_vehicle_speed):
"""
The method estimate the magnitude of the road curvature using the curvature of a number of regions of the road
ahead the vehicle. The closest to vehicle regions are more important so we use higher values of weights in an
equation with weights for ... | 67,798 |
def all_graphs_before_tuning():
"""
Plot graphs for data before the tuning phase
"""
algos = []
episodes = []
moving_avgs_rewards = []
moving_avgs_timesteps = []
from dates_for_graphs.date_for_graphs_before_tuning_path2 import sarsa
from dates_for_graphs.date_for_graphs_before_tunin... | 67,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.