content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_CV_current(CV):
"""
Helper function to compute CV current.
Args:
CV (pd.DataFrame): CV segement of charge
Returns:
(float): current reached at the end of the CV segment
"""
if not CV.empty:
return(CV.current.iat[-1]) | 5,289,200 |
def tanh(x):
""" Calculate hyperbolic tangent of the input AD object, integer, or float
INPUTS
=======
x: input value, an AD object, int, or float
RETURNS
========
result: hyperbolic tangent of x
EXAMPLES
=========
>>> x = ad.AD(2.0, [1.0,0.0])
>>> print(tanh(x... | 5,289,201 |
def vis_annotation_and_computed_vs(annotations_path,
images_path,
masks_path,
inspexp_file_path,
output_path,
save=True):
"""
Computes an... | 5,289,202 |
def init_weights(shape):
""" Weight initialization """
weights = np.asarray(np.random.randn(*shape) * 0.01, dtype=theano.config.floatX)
return theano.shared(weights) | 5,289,203 |
def config(path="config.yml", force_reload=False):
"""
Read the config for this module.
Priority is env, config.yml then defaults.
"""
global CONFIG, DEFAULT_CONFIG
if CONFIG is not None and not force_reload:
return CONFIG
# 1. Defaults. All items should have keys here.
config ... | 5,289,204 |
def start():
"""Presents LaTeX File Maker's main menu"""
print("LaTex File Maker\n===============")
# Menu Options
options = [
("N", "Create a new LaTeX file", create),
("L", "Edit an existing LaTeX file", load),
("Q", "Quit Program", quit)
]
print("Options\n===========\... | 5,289,205 |
def process_person(first_name, last_name, company):
"""Unpack Tuple of a Person."""
logger.info("First Name => {}".format(first_name))
logger.info("Last Name => {}".format(last_name))
logger.info("Company => {}".format(company)) | 5,289,206 |
def generate_sound_file(text_to_read, lang_to_use):
"""
creates a mp3 file with read word
"""
tmp_file_name = '%s/tmp_%s.mp3' % (sound_tmp_dir, str(random.uniform(1, 10e6)).replace('.', ''))
try:
tts = gTTS(text=text_to_read, lang=lang_to_use)
tts.save(tmp_file_name)
return ... | 5,289,207 |
def wait_for_test(wwt, timeout, for_render=False):
"""
On macOS with software OpenGL, every so often a single call to
`app.processEvents()` will take 15-30 seconds to execute. In order for the
tests like `test_full` to properly update the WWT rendering, it seems that
*several* such "long" iterations... | 5,289,208 |
def get_img_mask_generators(dataset_path,
target_size,
img_path="img",
ann_path="ann",
img_preprocessor=None,
mask_preprocessor=None,
SEED=1,):
"""
... | 5,289,209 |
def dump_exception():
"""create execption info for json response."""
info = sys.exc_info()
message = {"name": str(info[0]), "message": str(info[1])}
if __debug__:
buff = StringIO()
traceback.print_exc(file=buff)
message["traceback"] = buff.getvalue()
return message | 5,289,210 |
def explode(coords):
"""Explode a GeoJSON geometry's coordinates object and yield coordinate
tuples. As long as the input is conforming, the type of the
geometry doesn't matter.
Source:
https://gis.stackexchange.com/questions/90553/fiona-get-each-feature-extent-bounds
"""
for e in coords:
if i... | 5,289,211 |
def prepare_noise_cov(noise_cov, info, ch_names=None, rank=None,
scalings=None, verbose=None):
"""Prepare noise covariance matrix.
Parameters
----------
noise_cov : instance of Covariance
The noise covariance to process.
info : dict
The measurement info (used t... | 5,289,212 |
def gsl_blas_zgemm(*args, **kwargs):
"""
gsl_blas_zgemm(CBLAS_TRANSPOSE_t TransA, CBLAS_TRANSPOSE_t TransB,
gsl_complex alpha, gsl_matrix_complex A, gsl_matrix_complex B,
gsl_complex beta, gsl_matrix_complex C) -> int
"""
return _gslwrap.gsl_blas_zgemm(*args, **kwargs) | 5,289,213 |
def get_login_api(username, password):
"""
登入系统
"""
s = requests.session()
lt = get_ticker(s)
url = 'http://ids.sdufe.edu.cn/authserver/login?service=http%3A%2F%2Flibst.sdufe.edu.cn%2Fcas%2Findex.php%3Fcallback%3Dhttp%3A%2F%2Flibst.sdufe.edu.cn%2Fhome%2Fweb%2Ff_second'
data = {'lt': lt,
... | 5,289,214 |
def sparsify_array(array):
"""Convert a np.array into a torch.sparse.FloatTensor
Args:
array (np.array)
returns:
sparse (torch.sparse.Tensor)
"""
return sparsify_tensor(torch.FloatTensor(array)) | 5,289,215 |
def tracer(pid):
"""tracer(pid) -> int
Arguments:
pid (int): PID of the process.
Returns:
PID of the process tracing `pid`, or None if no `pid` is not being traced.
Example:
>>> tracer(os.getpid()) is None
True
"""
tpid = int(status(pid)['TracerPid'])
retur... | 5,289,216 |
async def staking_config_cms(
project: str,
db=Depends(get_db),
):
"""
Get config
"""
try:
return get_staking_config_by_name(db, project)
except Exception as e:
return JSONResponse(
status_code=status.HTTP_400_BAD_REQUEST, content=f"{str(e)}"
) | 5,289,217 |
def validate_file(path, validate_yamls, tmpdir=None, lock=None):
"""Validate a file on disk.
Parameters
----------
path : str
The path to the file.
validate_yamls : dict
A dictionary mapping the filename of the validation yaml to its
contents.
tmpdir : str, optional
... | 5,289,218 |
def do_bisect(bisect_type, source_id, project_name, engine, sanitizer,
architecture, fuzz_target, old_commit, new_commit, testcase):
"""Do the actual bisect."""
import bisector
import build_specified_commit
with tempfile.NamedTemporaryFile() as f:
f.write(testcase)
f.flush()
build_da... | 5,289,219 |
def _unstack(array):
"""Similar to `tf.unstack`."""
num_splits = int(array.shape[0])
return [torch.squeeze(x, dim=0) for x in np.split(array, num_splits, axis=0)] | 5,289,220 |
def load(mib):
"""dummy load"""
pass | 5,289,221 |
def by_included_absolute_path(path, df_logs_formated):
"""
return subset of conversations that contains specific node
@param path path: array
"""
print("filtering.by_included_absolute_path() is DEPRECATED and will be removed in a future release. ")
# create an empty dataframe with the same colum... | 5,289,222 |
def predict(images, model, alpha, rho=0, return_model=False):
"""Apply background subtraction to a batch of images
Args:
images: numpy array with shape [num_ims, height, width, channel]
containing the images to process.
model: tuple (mean, std) obtaining with create_model() function.
... | 5,289,223 |
def set_UV_editor_texture(mesh):
""" set the image for the face.tex layer on all the faces
so we have a rough idea of what the mesh will look like
in the 3D view's Texture render mode"""
# load the mesh data into a bmesh object
bm = bmesh.new()
bm.from_mesh(mesh)
bm.faces.ensure_lookup_table... | 5,289,224 |
def normalize(sightline, full_wavelength, full_flux):
"""
Normalize spectrum by dividing the mean value of continnum at lambda[left,right]
------------------------------------------
parameters:
sightline: dla_cnn.data_model.Sightline.Sightline object;
full_flux: list, flux of the spectra
... | 5,289,225 |
def test_update_key_set():
"""
Keys should be added to a set of stored keys.
"""
m = Matrix()
m.set_pair('a', 'b', 1)
m.set_pair('a', 'c', 2)
assert m.keys == set(['a', 'b', 'c']) | 5,289,226 |
def test_compute_horse_auc():
"""plot the AUC for the horse colic data"""
data, labels = utils.load_tsv_datafile('data/horseColicTraining.txt')
classifier_array, aggregated_class_estimates =\
ada_boost.train_dataset(data, labels, 40)
ada_boost.plot_roc(aggregated_class_estimates.T, labels) | 5,289,227 |
def stations_by_river(stations):
"""This function creates a dictionary with river names as a key and a list of all the
station names on the respective river"""
rivers = rivers_with_station(stations)
river_dictionary = {}
for river in rivers:
river_dictionary[river] = [] #Generating Empty Di... | 5,289,228 |
def filter_nick(name):
"""
filter_nick(name) -> String
Process the name and get rid of all whitespace, invisible characters and
make it all lower case.
This function is intended to mimic euphoria's name pinging system, however
it is slightly less pedantic, allowing for punctuation within names... | 5,289,229 |
def get_mondays():
"""Returns a tuple with start and end Time Stamp Strings from last monday to midnight this monday.
Unless it is a monday. In that case we actually want the previous period."""
today = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)
if today.weekday() < 6:
# ... | 5,289,230 |
def tfidf_score_str(tokens, texts, tfidf_function_name, number_all_texts_in_db, m=10,*args):
# Same as tfidf_score, only takes tfidf_function name as input instead of function itself.
"""Assigns score to documents based on tfidf_function metric.
Args:
tokens (list): List of tokens (tokenized query).... | 5,289,231 |
def text_to_handwriting(
string: str, save_to: str = "pywhatkit.png", rgb: tuple = (0, 0, 0)
) -> None:
"""Convert the given String to Handwritten Characters"""
data = requests.get(
f"https://pywhatkit.herokuapp.com/handwriting?text={string}&rgb={rgb[0]},{rgb[1]},{rgb[2]}"
).content
with op... | 5,289,232 |
def test_PSA(args, input_len):
"""Test the time and CUDA memory consumption of Prob-sparse self attention."""
handle = pynvml.nvmlDeviceGetHandleByIndex(1)
meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
init_mem = meminfo.used / 1024**3
LSA_Layer = ProbSparseAttention(args).to(args.device)
op... | 5,289,233 |
def remove_bindings(ctx):
"""Remove all Bindings for Dynamic configutation"""
config_db = ConfigDBConnector()
config_db.connect()
binding_table_name = 'NAT_BINDINGS'
binding_dict = config_db.get_table(binding_table_name)
if binding_dict:
for binding_key_name in binding_dict.keys():
... | 5,289,234 |
def distort_img(input_img, d_limit=4):
"""
Apply warpPerspective transformation on image, with 4 key points, randomly generated around the corners
with uniform distribution with a range of [-d_limit, d_limit]
:param input_img:
:param d_limit:
:return:
"""
if d_limit == 0:
return ... | 5,289,235 |
def run_opreport(event, report_file):
""" Run opreport and exit if an error happens """
opreport_cmd = OPREPORT + " --debug-info --symbols --details "
opreport_cmd += "--xml event:{0} -o {1}".format(event, report_file)
status, output = core.execute_stdout(opreport_cmd)
if status != 0:
sys.st... | 5,289,236 |
def delete_v1_session(session_id): # noqa: E501
"""DELETE /v1/session
Delete the session by session id
"""
with BosEtcdClient() as bec:
key = "{}/{}/".format(BASEKEY, session_id)
resp = bec.delete_prefix(key)
if resp.deleted >= 1:
return '', 204
else:
... | 5,289,237 |
def makeCube(pre, scienceFrameList, observationDirectory, log, over):
""" Reformat the data into a 3-D datacube using iraf.nifcube. Output: If
telluric correction to be applied, -->catfbrsgn. Else, -->ctfbrsgn.
NIFCUBE - Construct 3D NIFS datacubes.
NIFCUBE takes input from data output by either NFFIT... | 5,289,238 |
def thread_messages():
"""Load some threads"""
content = io.StringIO()
path = os.path.join(settings.BASE_DIR, 'tests', 'data', 'thread.mail')
call_command('clear_index', interactive=False, stdout=content)
call_command('load', path, listname='acme', summary=True, stdout=content) | 5,289,239 |
def label_name(event_data):
"""Get the label name from a label-related webhook event."""
return event_data["label"]["name"] | 5,289,240 |
def post_file_list():
"""
Upload one or more files and return parsed result back as JSON array
:return:
"""
files = request.files
if not files:
LOGGER.info("No file found in request")
raise BadRequest("No file found in request")
result = []
for file in files:
i... | 5,289,241 |
def write_tfrecord(example_list, save_file):
"""
Writes TFRecord from example protocol.
:param list example_list: List of example protocol.
:param save_file: Output file path.
"""
with tf.io.TFRecordWriter(save_file) as writer:
for example in example_list:
writer.write(examp... | 5,289,242 |
def new_event(dtstart=None, dtend=None, summary=None, timezone=None,
_now=datetime.now):
"""create a new event
:param dtstart: starttime of that event
:type dtstart: datetime
:param dtend: end time of that event
:type dtend: datetime
:param summary: description of the event, used ... | 5,289,243 |
def create_not_exists(path):
""" 创建目录 """
if not os.path.exists(path):
os.makedirs(path) | 5,289,244 |
def getCashflowsByUserID(db, userID):
"""
Get cash flows by user's ID
:param db: database object
:param userID: user's ID
:return: Tuple of cash flow
((flowID, userID, amount, message, date), ((flowID, userID, amount, message, date)))
"""
if db is None:
return None
try:
... | 5,289,245 |
def test_mocked_backend(measurement):
"""Test mocked backend"""
circuit = Circuit()
circuit += ops.DefinitionFloat(name='ro', length=1, is_output=True)
circuit += ops.DefinitionComplex(name='ro', length=1, is_output=True)
circuit += ops.DefinitionBit(name='ro', length=1, is_output=True)
circuit ... | 5,289,246 |
async def test_subscription_duplicates():
"""
If we receive subscription events while catching up, we buffer them internally.
If we restart the conversation at that point we need to make sure we clear our buffer
and do not raise duplicate events.
=> Request historical
<= Empty
=> Subscribe to str... | 5,289,247 |
def generic_user_is_403_forbidden_test(ar, auth_header, path):
"""Test if unauthorized/unauthenticated user is getting 403 access denied
Helper function meant to simplify writing multiple tests testing the
same thing for different endpoints.
Arguments:
ar: Admin Router object, an instance of r... | 5,289,248 |
def predict_fn(self, x):
"""
Overrides the predict function for models, provided that the predict
function takes in one argument.
"""
predict_array = self.predict(x)
return convert_prediction_to_event(self, predict_array, x) | 5,289,249 |
def run(config: Dict[str, Any],
data_class: Type[DataModule],
model_class: Type[Module],
optuna: Optional[Optuna] = None,
runner: Optional[Runner] = None) -> Trainer:
"""Run the pipeline by give configuration, model_class, data_class, optuna
and runner
Args:
config: ... | 5,289,250 |
def concretePolynomialLoad():
"""
pytest fixture that returns a PolynomialLoad object with concrete parameters
:return: PolynomialLoad object initialized with concrete values
"""
addnl_params = dict(p=0.5, q=0.98, r=2678.88)
test_load_params = dict(a=0.01, b=0.05, c=0.1, j_load=0.1, p=0.5, q = ... | 5,289,251 |
def decode(data):
"""
Decodes URL safe base64 encoded value
"""
padding = 4 - (len(data) % 4)
data += ('=' * padding)
return urlsafe_b64decode(data).decode() | 5,289,252 |
def upload(**kwargs):
"""Upload integration or pack to Demisto instance.
DEMISTO_BASE_URL environment variable should contain the Demisto server base URL.
DEMISTO_API_KEY environment variable should contain a valid Demisto API Key.
* Note: Uploading classifiers to Cortex XSOAR is available from version ... | 5,289,253 |
def get_resource(html, extensions):
"""
Content:リソース取得
html:HTML
extensions:拡張子のリスト
"""
resource_list = []
soup = bs4.BeautifulSoup(html)
for a_tag in soup.find_all("a"):
href_str = a_tag.get("href")
try:
(path, ext) = os.path.splitext(href_str)
if ext in extensions:
resource_list.append(href... | 5,289,254 |
def _fill_textSize_form(driver, ss_path, id_infix):
"""
fills the text size with required information
"""
driver.find_element_by_id("id_{}size".format(id_infix)).clear()
driver.find_element_by_id("id_{}size".format(id_infix)).send_keys("10000")
Select(driver.find_element_by_id("id_{}sizeUnit".fo... | 5,289,255 |
def bit_length_power_of_2(value):
"""Return the smallest power of 2 greater than a numeric value.
:param value: Number to find the smallest power of 2
:type value: ``int``
:returns: ``int``
"""
return 2 ** (int(value) - 1).bit_length() | 5,289,256 |
def clip_but_pass_gradient(x, l=-1., h=1.):
"""
Stole this function from SpinningUp
Args:
x: data to be clipped.
l: lower bound
h: upper bound.
Return:
if x < l:
l
elif x > h:
h
else:
x
"""
clip_up = tf.cast(x > ... | 5,289,257 |
async def test_validate_dependencies(mocker):
"""validate_dependencies should do nothing if all dependencies exist"""
dependency_exists_stub = mocker.async_patch("release.dependency_exists")
dependency_exists_stub.return_value = True
await validate_dependencies()
for dependency in ("node", "git", GI... | 5,289,258 |
def delete_endpoint(project_id, location_id, namespace_id, service_id,
endpoint_id):
"""Deletes a endpoin in the given service."""
client = servicedirectory_v1.RegistrationServiceClient()
endpoint_name = client.endpoint_path(project_id, location_id, namespace_id,
... | 5,289,259 |
def get_encryption_algs():
"""Return a list of available encryption algorithms"""
return _enc_algs | 5,289,260 |
def get_statements_by_hash(hash_list, simple_response=False, *args, **kwargs):
"""Get fully formed statements from a list of hashes.
Parameters
----------
hash_list : list[int or str]
A list of statement hashes.
simple_response : bool
If True, a simple list of statements is returned... | 5,289,261 |
def main(dir):
"""
Takes a folder of TEM images (preferably in dm3 or dm4 format) and calculates
aggregate statistics for particle sizes. Creates a plot and a .csv for
manual/custom plotting, if desired. Automatically detects and sizes
particles, and outputs a visualization after each detection so t... | 5,289,262 |
def _get_prop(props_dict, spec):
"""Gets the given property specification from the dictionary
The specification can be a string or a pair of string and a callable.
:param dict props_dict: The dictionary to retrieve the property.
:param spec: The specification of the property, it can be a string, or a
... | 5,289,263 |
def real_time(
minutes: float = 5,
increment: int = 8,
variant: Variant = Variant.STANDARD,
color: Color = Color.RANDOM,
) -> Match:
"""Start a live match that two players can join
:param minutes: :class:`float`
The number of minutes for the match (excluding increment)
:param increm... | 5,289,264 |
def typing(session):
"""Type chec the program with mypy."""
session.install(".[typing]")
session.run("mypy", "src/", "tests/") | 5,289,265 |
def _RevisionRangeFromSummary(summary):
"""Uses regex to extract revision range from bug a summary string.
Note: Information such as test path and revision range for a bug could
also be gotten by querying the datastore for Anomaly entities for
each bug ID. However, these queries might be relatively costly. Als... | 5,289,266 |
def cmd_reload_all():
"""Reload all apps"""
print("= Reload all")
for app in listdir(APP_ROOT):
if not app.startswith((".", "_")):
_reload_app(app) | 5,289,267 |
def json_top_atom_count(json_str):
"""Count the number of atoms in a JSON topology used by wepy HDF5."""
top_d = json.loads(json_str)
atom_count = 0
atom_count = 0
for chain in top_d['chains']:
for residue in chain['residues']:
atom_count += len(residue['atoms'])
return ato... | 5,289,268 |
def length_squared(point):
"""
square of length from origin of a point
Args:
point (QPointF) the point
Returns
square of length
"""
return point.x()*point.x() + point.y()*point.y() | 5,289,269 |
def api_report_conference_role(conference_id, role_id):
"""
Takes a role ID and report data and reports the object with the
provided ID.
"""
return api_report_conference_child(conference_id, request.json, role_id, object_type="role") | 5,289,270 |
def plot_planckian_locus_in_chromaticity_diagram_CIE1960UCS(
illuminants: Union[str, Sequence[str]],
chromaticity_diagram_callable_CIE1960UCS: Callable = (
plot_chromaticity_diagram_CIE1960UCS # type: ignore[has-type]
),
annotate_kwargs: Optional[Union[Dict, List[Dict]]] = None,
plot_kwargs... | 5,289,271 |
def addSA1(sess,rramTensors, percentSA1):
"""
This function adds the SAF low defects into the crossbar.
"""
allParameters = [sess.run(v) for v in rramTensors]
shapes = [v.get_shape().as_list() for v in rramTensors]
minValues = []
for i in range(len(allParameters)):
minValues.append(np.amin(allParameter... | 5,289,272 |
def topSort(G):
"""
使用BFS实现拓扑排序。
每次找到入度为0的节点放入列队,遍历与入度为0的点相邻的节点,并将度数减少1,如果度数变为0则放入列队。直到列队为空。
"""
Q = [] # 列队存储每个节点
counter = 0
sort = {}
for i in G:
if i.degree == 0:
Q.append(i)
while len(Q) != 0:
vertex = Q.pop()
sort[vertex] = counter
counter += 1
if vertex.c == None:
continue
for j in... | 5,289,273 |
def _process_hooks(hooks):
"""Prepare hooks data for report."""
hooks_ctx = []
for hook in hooks:
hook_ctx = {"name": hook["config"]["action"][0],
"desc": hook["config"].get("description", ""),
"additive": [], "complete": []}
for res in hook["results"... | 5,289,274 |
def find_nearest_index(seq, value):
"""
Return the index of the value in the sequence that is closest to the
given value
"""
return (np.abs(np.array(seq)-value)).argmin() | 5,289,275 |
def get(params_config, params=None, is_show_help=True):
"""标准化处理参数
根据提供的params_config参数,提供参数params中的字段,返回字典
params_config例:
{
'username':
{'must':False,'data':True,'short':'U','long':'username','default':'root'},
'password':
{'must':True,'data... | 5,289,276 |
def level1_destripe(filename,options):
"""Plot hit maps for feeds
Arguments:
filename: the name of the COMAP Level-1 file
"""
# Get the inputs:
parameters = ParserClass.Parser(filename)
title = parameters['Inputs']['title']
for k1,v1 in options.items():
if len(options.... | 5,289,277 |
def do_upgrade(env, ver, cursor):
"""Convert time values from integer seconds to integer microseconds."""
tables = [
('attachment', {'time': ('int', 'int64')}),
('wiki', {'time': ('int', 'int64')}),
('revision', {'time': ('int', 'int64')}),
('ticket', {'time': ('int', 'int64'),
... | 5,289,278 |
async def log_request(request: AsyncRequest, session: ClientSession) -> Union[str, None]:
"""
Logging wrapper around AsyncRequest.send method.
"""
log = get_default_logger()
base_url = session._base_url # pylint: disable=protected-access
request_full_url = request.url if base_url is None else s... | 5,289,279 |
def get_pv_asp_n(n):
"""Returns ASP PV associated with neg(-) beam species, either -.
Required for Main Buncher.
Arguments:
n(str or int): module or buncher number
"""
return get_pv_asp(n, '+') | 5,289,280 |
def test_host_with_scheme_and_scheme_in_definition(responses: RequestsMock, tmpdir):
"""
Assert that if there is not host in OpenAPI definition and host is provided by client.
This host is used, but the scheme used should be the one provided in the OpenAPI definition.
"""
responses.add(
resp... | 5,289,281 |
def get_ancestor(taxid, tree, stop_nodes):
"""Walk up tree until reach a stop node, or root."""
t = taxid
while True:
if t in stop_nodes:
return t
elif not t or t == tree[t]:
return t # root
else:
t = tree[t] | 5,289,282 |
def start_bank():
"""The main bank balance service.
This opens the socket, and listens for incoming grpc conformant packets"""
server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))
balance_pb2_grpc.add_BalanceServiceServicer_to_server(Listener(), server)
server.add_insecure_port("[::]:999... | 5,289,283 |
def save_checkpoint(checkpoint_dir, model, optimizer, metrics, epoch, defsave=False):
"""Save model, optimizer, and metrics state to a checkpoint in checkpoint_dir
for the specified epoch. If checkpoint_dir is None it does not do anything."""
if checkpoint_dir is not None:
if model:
xmkd... | 5,289,284 |
def plot_theory(ax: Axes,
x: array,
thry: array,
numl: Union[array, Sequence[array]],
xlab: str,
ylab: str,
legloc: str,
textopts: Options,
lgtxtopt: Options):
"""plot theory + simulation
... | 5,289,285 |
def wkhtmltopdf(pages, output=None, **kwargs):
"""
Converts html to PDF using http://wkhtmltopdf.org/.
pages: List of file paths or URLs of the html to be converted.
output: Optional output file path. If None, the output is returned.
**kwargs: Passed to wkhtmltopdf via _extra_args() (See
... | 5,289,286 |
def display_image(obd, mime_type):
"""Display the opaque binary response data with the image using IPython's
display.Image class
:param str obd: The opaque binary data
:param str mime_type: The image mime_type
:rtype: IPython.display.Image
"""
filename = write_temp_file(obd, mime_type)
... | 5,289,287 |
def test_creation():
""" Test ``InitLR.__init__`` raises when configured improperly."""
model = LRModel(dataset=None, log_dir='', inputs=['input', 'target'], outputs=['output'])
with pytest.raises(TypeError):
InitLR(model=42, value=0.1)
with pytest.raises(KeyError):
InitLR(model=model, v... | 5,289,288 |
def load_checkpoint_train(cpdir, model, optimizer):
"""Load model and optimizer parameters for training
Note:
This is simply a wrapper to load_checkpoint so that
global_step and epoch are updated correctly.
If cpdir is None, do not load checkpoint and returns
0 for global_step an... | 5,289,289 |
def plot_emb2d(emb, colors=None, filename=None):
"""
Generates a scatter plot of the given embeddings. Optional colors for the nodes can be provided as well as
a filename to store the results. If dim of embeddings > 2, uses t-SNE to reduce it to 2.
Parameters
----------
emb : matrix
A N... | 5,289,290 |
def enable_assistant():
"""Enable the TensorFlow MRI assistant."""
global _ENABLE_ASSISTANT
_ENABLE_ASSISTANT = True | 5,289,291 |
def separable_conv1d(x, depthwise_kernel, pointwise_kernel, strides=1,
padding='valid', data_format=None, dilation_rate=1):
"""1D convolution with separable filters.
# Arguments
x: input tensor
depthwise_kernel: convolution kernel for the depthwise convolution.
poin... | 5,289,292 |
def has_sub_tasks(task):
"""Returns True if the task has sub tasks"""
if istask(task):
return True
elif isinstance(task, list):
return any(has_sub_tasks(i) for i in task)
else:
return False | 5,289,293 |
async def _update_game(url, game, session):
"""Internal wrapper to update a Game object"""
json = await async_request(url, session, url_mods={'game_id': game.game_id}) # noqa
game.update_data(json) | 5,289,294 |
def draw(graph, predicted_path, reference_path, output_filename, **kwargs):
"""Generates a plot showing the graph, predicted and reference paths.
Args:
graph: A networkx graph.
predicted_path: A list with the ids of the nodes in the predicted path.
reference_path: A list with the ids of the nodes in th... | 5,289,295 |
def test_kooi_2016(plot=False):
"""check theory against observations in Kooi 2016, figure 4"""
nsamples = 1000
rng = np.random.default_rng(seed=1)
rho_min, rho_max = 930, 970
rho = rng.uniform(
rho_min, rho_max, nsamples
) # plastic density not stated; this mimics a selection of LDPE an... | 5,289,296 |
def largest_values_in_row_colums(xs: np.array) -> List[float]:
""" Approximates the largest value in each row/column.
"""
if xs.shape == (0, ):
return [0]
assert len(xs.shape) == 2
# resize matrix to square dimensions if needed
if xs.shape[0] != xs.shape[1]:
xs = _resize_to_squ... | 5,289,297 |
async def test_create_playlist_link(
get_playlist_info_mock: AsyncMock,
) -> None:
"""Check create playlist if everything is fine."""
playlist_id: str = "37i9dQZF1DZ06evO0Co11u"
link: str = f"https://open.spotify.com/playlist/{playlist_id}"
playlist_info: Dict[str, str] = {
"url": "test_... | 5,289,298 |
def delete_vm(client, session, vm, params):
"""Delete (ie: terminate) a virtual machine."""
if vm['state'] is None:
return {'changed': False}
xmlrpc(client, 'vm.action', session, 'terminate', vm['id'])
return {'changed': True, 'vm_id': -1, 'actions': ['terminated']} | 5,289,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.