content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _prettify(elem,indent_level=0):
"""Return a pretty-printed XML string for the Element.
"""
indent = " "
res = indent_level*indent + '<'+elem.tag.encode('utf-8')
for k in elem.keys():
res += " "+k.encode('utf-8')+'="'+_escape_nl(elem.get(k)).encode('utf-8')+'"'
children = elem.getch... | 5,355,700 |
def predict(text):
"""
Predict the language of a text.
Parameters
----------
text : str
Returns
-------
language_code : str
"""
if language_models is None:
init_language_models(comp_metric, unicode_cutoff=10**6)
x_distribution = get_distribution(text, language_model... | 5,355,701 |
def kgup(baslangic_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"),
bitis_tarihi=__dt.datetime.today().strftime("%Y-%m-%d"), organizasyon_eic="", uevcb_eic=""):
"""
İlgili tarih aralığı için kaynak bazlı kesinleşmiş günlük üretim planı (KGÜP) bilgisini vermektedir.
Not: "organizasyon_eic" değeri ... | 5,355,702 |
def _output_rdf_graph_as_html_no_jinja(theCgi, top_url, error_msg, gbl_cgi_env_list):
"""
This transforms an internal data graph into a HTML document.
"""
page_title = theCgi.m_page_title
grph = theCgi.m_graph
display_html_text_header(page_title)
WrtAsUtf('<body>')
script_informat... | 5,355,703 |
def distance_loop(x1, x2):
""" Returns the Euclidean distance between the 1-d numpy arrays x1 and x2"""
return -1 | 5,355,704 |
def get_ps_calls_and_summary(filtered_guide_counts_matrix, f_map):
"""Calculates protospacer calls per cell and summarizes them
Args:
filtered_guide_counts_matrix: CountMatrix - obtained by selecting features by CRISPR library type on the feature counts matrix
f_map: dict - map of feature ID:fea... | 5,355,705 |
def symbol_by_name(name, aliases={}, imp=None, package=None,
sep='.', default=None, **kwargs):
"""Get symbol by qualified name.
The name should be the full dot-separated path to the class::
modulename.ClassName
Example::
celery.concurrency.processes.TaskPool
... | 5,355,706 |
def coefficients_of_line_from_points(
point_a: Tuple[float, float], point_b: Tuple[float, float]
) -> Tuple[float, float]:
"""Computes the m and c coefficients of the equation (y=mx+c) for
a straight line from two points.
Args:
point_a: point 1 coordinates
point_b: point 2 coordinates
... | 5,355,707 |
def logDirManager():
""" Directory manager for TensorFlow logging """
print('Cleaning and initialising logging directory... \n')
# Ensure function is starting from project root..
if os.getcwd() != "/Users/Oliver/AnacondaProjects/SNSS_TF":
os.chdir("/Users/Oliver/AnacondaProjects/SNSS_TF")
os... | 5,355,708 |
def read_tiff(fname, slc=None):
"""
Read data from tiff file.
Parameters
----------
fname : str
String defining the path of file or file name.
slc : sequence of tuples, optional
Range of values for slicing data in each axis.
((start_1, end_1, step_1), ... , (start_N, end... | 5,355,709 |
def sorted_non_max_suppression_padded(scores,
boxes,
max_output_size,
iou_threshold):
"""A wrapper that handles non-maximum suppression.
Assumption:
* The boxes are sorted by scores unless the box ... | 5,355,710 |
def create_session() -> Session:
"""
Creates a new session using the aforementioned engine
:return: session
"""
return Session(bind=engine) | 5,355,711 |
def test_checkout_start_is_transaction_date(
loan_created, db, params, mock_ensure_item_is_available_for_checkout
):
"""Test checkout start date to transaction date when not set."""
mock_ensure_item_is_available_for_checkout.side_effect = None
number_of_days = timedelta(days=10)
with SwappedNested... | 5,355,712 |
def fft_to_complex_matrix(x):
""" Create matrix with [a -b; b a] entries for complex numbers. """
x_stacked = torch.stack((x, torch.flip(x, (4,))), dim=5).permute(2, 3, 0, 4, 1, 5)
x_stacked[:, :, :, 0, :, 1] *= -1
return x_stacked.reshape(-1, 2 * x.shape[0], 2 * x.shape[1]) | 5,355,713 |
def mcais(A, X, verbose=False):
"""
Returns the maximal constraint-admissible (positive) invariant set O_inf for the system x(t+1) = A x(t) subject to the constraint x in X.
O_inf is also known as maximum output admissible set.
It holds that x(0) in O_inf <=> x(t) in X for all t >= 0.
(Implementatio... | 5,355,714 |
def draw_tree(document: Document,
sid: str,
cases: List[str],
bridging: bool = False,
coreference: bool = False,
fh: Optional[TextIO] = None,
html: bool = False,
) -> None:
"""sid で指定された文の述語項構造・共参照関係をツリー形式で fh に書き出す
... | 5,355,715 |
def evaluation_seasonal_srmse(model_name, variable_name='mean', background='all'):
"""
Evaluate the model in different seasons using the standardized RMSE.
:type model_name: str
:param model_name: The name of the model.
:type variable_name: str
:param variable_name: The name of the variable wh... | 5,355,716 |
def create_message():
"""send_message Send stream of messages to server
Args:
client_obj (object): Client stub class
"""
for _ in range(10):
message_id = f'Client with message ID: {randint(0, 1000)}'
yield pb2.ClientStreamingRequest(client_message=message_id) | 5,355,717 |
def test_logged_social_connect_self(social_config, facebook_user, db_session):
"""Connect self."""
user = db_session.merge(facebook_user)
profile = {
"accounts": [
{
"domain": "facebook.com",
"userid": user.provider_id("facebook"),
}
]... | 5,355,718 |
def generate_accession_id() -> str:
"""Generate Stable ID."""
accessionID = uuid4()
urn = accessionID.urn
LOG.debug(f"generated accession id as: {urn}")
return urn | 5,355,719 |
def _async_device_ha_info(
hass: HomeAssistant, lg_device_id: str
) -> dict | None:
"""Gather information how this ThinQ device is represented in Home Assistant."""
device_registry = dr.async_get(hass)
entity_registry = er.async_get(hass)
hass_device = device_registry.async_get_device(
iden... | 5,355,720 |
def clean(url, full=typer.Option(False, "-f")):
"""Clean the cache"""
db_path = f"cache/{url_to_domain(url)}/posts.db"
ic(db_path)
if not pathlib.Path(db_path).exists():
llog.info("There is no data associated with this URL")
llog.info("There is nothing to do")
return
db = sq... | 5,355,721 |
def get_travis_pr_num() -> Optional[int]:
"""Return the PR number if the job is a pull request, None otherwise
Returns:
int
See also:
- <https://docs.travis-ci.com/user/environment-variables/#default-environment-variables>
""" # noqa E501
try:
travis_pull_request = get_tra... | 5,355,722 |
def get_updated_records(table_name: str, existing_items: List) -> List:
"""
Determine the list of record updates, to be sent to a DDB stream after a PartiQL update operation.
Note: This is currently a fairly expensive operation, as we need to retrieve the list of all items
from the table, and com... | 5,355,723 |
def kill_server():
"""
Kills the forked process that is hosting the Director repositories via
Python's simple HTTP server. This does not affect the Director service
(which handles manifests and responds to requests from Primaries), nor does
it affect the metadata in the repositories or the state of the reposi... | 5,355,724 |
def normalize_record(input_object, parent_name="root_entity"):
"""
This function orchestrates the main normalization.
It will go through the json document and recursively work with the data to:
- unnest (flatten/normalize) keys in objects with the standard <parentkey>_<itemkey> convention
- identi... | 5,355,725 |
def rmse(f, p, xdata, ydata):
"""Root-mean-square error."""
results = np.asarray([f(p, x) for x in xdata])
sqerr = (results - ydata)**2
return np.sqrt(sqerr.mean()) | 5,355,726 |
def get_logger(name=None, propagate=True):
"""Get logger object"""
logger = logging.getLogger(name)
logger.propagate = propagate
loggers.append(logger)
return logger | 5,355,727 |
def load_movielens1m(infile=None, event_dtype=event_dtype_timestamp):
""" load the MovieLens 1m data set
Original file ``ml-1m.zip`` is distributed by the Grouplens Research
Project at the site:
`MovieLens Data Sets <http://www.grouplens.org/node/73>`_.
Parameters
----------
infile : optio... | 5,355,728 |
def load_coco_data(split):
"""load the `split` data containing image and label
Args:
split (str): the split of the dataset (train, val, test)
Returns:
tf.data.Dataset: the dataset contains image and label
image (tf.tensor), shape (224, 224, 3)
label (tf.tensor), shape (1000... | 5,355,729 |
def get_args():
"""
Get User defined arguments, or assign defaults
:rtype: argparse.ArgumentParser()
:return: User defined or default arguments
"""
parser = argparse.ArgumentParser()
# Positional arguments
parser.add_argument("main_args", type=str, nargs="*",
he... | 5,355,730 |
def getMatches(tournamentName=None, matchDate=None, matchPatch=None, matchTeam=None):
"""
Params:
tournamentName: str/List[str]/Tuple(str) : filter by tournament names (e.g. LCK 2020 Spring)
matchDate: str/List[str]/Tuple(str) : date in the format of yyyy-mm-dd
matchPatch: str/List[... | 5,355,731 |
def parse_e_elect(path: str,
zpe_scale_factor: float = 1.,
) -> Optional[float]:
"""
Parse the electronic energy from an sp job output file.
Args:
path (str): The ESS log file to parse from.
zpe_scale_factor (float): The ZPE scaling factor, used only for ... | 5,355,732 |
def test_get_slates():
"""Tests get slates"""
pass | 5,355,733 |
def create_app():
"""Creates the instance of an app."""
configuration_file=os.getcwd()+'/./configuration.cfg'
app=Flask(__name__)
app.config.from_pyfile(configuration_file)
bootstrap.init_app(app)
mail.init_app(app)
from my_app.admin import admin
app.register_blueprint(admin)
from my... | 5,355,734 |
def execute(args):
"""This function invokes the forage model given user inputs.
args - a python dictionary with the following required entries:
args['latitude'] - site latitude in degrees. If south of the equator,
this should be negative
args['prop_legume'] - proportion o... | 5,355,735 |
def start():
"""
Start the application
"""
with settings(user=env.sudouser):
sudo('initctl start %s' % env.appuser) | 5,355,736 |
def get_fields(fields):
"""
From the last column of a GTF, return a dictionary mapping each value.
Parameters:
fields (str): The last column of a GTF
Returns:
attributes (dict): Dictionary created from fields.
"""
attributes = {}
description = fields.strip()
description = [x.strip() for x in description... | 5,355,737 |
def add_log_group_name_params(log_group_name, configs):
"""Add a "log_group_name": log_group_name to every config."""
for config in configs:
config.update({"log_group_name": log_group_name})
return configs | 5,355,738 |
def on_update_user_info(data: dict, activity: Activity) -> (int, Union[str, None]):
"""
broadcast a user info update to a room, or all rooms the user is in if no target.id specified
:param data: activity streams format, must include object.attachments (user info)
:param activity: the parsed activity, s... | 5,355,739 |
def discover(isamAppliance, check_mode=False, force=False):
"""
Discover available updates
"""
return isamAppliance.invoke_get("Discover available updates",
"/updates/available/discover") | 5,355,740 |
def jest_test(name, **kwargs):
"""Wrapper macro around jest_test cli"""
_jest_test(
name = name,
args = [
"--no-cache",
"--no-watchman",
"--no-colors",
"--ci",
],
chdir = native.package_name(),
**kwargs
) | 5,355,741 |
def ENsettimeparam(paramcode, timevalue):
"""Sets the value of a time parameter.
Arguments:
paramcode: time parameter code EN_DURATION
EN_HYDSTEP
EN_QUALSTEP
EN_PATTERNSTEP
... | 5,355,742 |
def ltistep(U, A=A, B=B, C=C):
""" LTI( A B C ): U -> y linear
straight up
"""
U, A, B, C = map(np.asarray, (U, A, B, C))
xk = np.zeros(A.shape[1])
x = [xk]
for u in U[:-1]:
xk = A.dot(xk) + B.dot(u)
x.append(xk.copy())
return np.dot(x, C) | 5,355,743 |
def _registry():
"""Registry to download images from."""
return _registry_config()["host"] | 5,355,744 |
def load_structure(query, reduce=True, strip='solvent&~@/pseudoBonds'):
"""
Load a structure in Chimera. It can be anything accepted by `open` command.
Parameters
==========
query : str
Path to molecular file, or special query for Chimera's open (e.g. pdb:3pk2).
reduce : bool
Ad... | 5,355,745 |
def is_into_keyword(token):
"""
INTO判定
"""
return token.match(T.Keyword, "INTO") | 5,355,746 |
def exp(
value: Union[Tensor, MPCTensor, int, float], iterations: int = 8
) -> Union[MPCTensor, float, Tensor]:
"""Approximates the exponential function using a limit approximation.
exp(x) = lim_{n -> infty} (1 + x / n) ^ n
Here we compute exp by choosing n = 2 ** d for some large d equal to
iterat... | 5,355,747 |
def train(estimator: Estimator, data_root_dir: str, max_steps: int) -> Any:
"""Train a Tensorflow estimator"""
train_spec = tf.estimator.TrainSpec(
input_fn=_build_input_fn(data_root_dir, ModeKeys.TRAIN),
max_steps=max_steps,
)
if max_steps > Training.LONG_TRAINING_STEPS:
throt... | 5,355,748 |
def plot(data_input,categorical_name=[],drop=[],PLOT_COLUMNS_SIZE = 4,bin_size=20,bar_width=0.2,wspace=0.5,hspace=0.8):
"""
This is the main function to give Bivariate analysis between the target variable and the input features.
Parameters
-----------
data_input : Dataframe
This is th... | 5,355,749 |
def assert_similar_time(dt1: datetime, dt2: datetime, threshold: float = 0.5) -> None:
"""Assert the delta between the two datetimes is less than the given threshold (in seconds).
This is required as there seems to be small data loss when marshalling and unmarshalling
datetimes, for example:
2021-09-2... | 5,355,750 |
def isDllInCorrectPath():
"""
Returns True if the BUFFY DLL is present and in the correct location (...\<BTS>\Mods\<BUFFY>\Assets\).
"""
return IS_DLL_IN_CORRECT_PATH | 5,355,751 |
def time_remaining(event_time):
"""
Args:
event_time (time.struct_time): Time of the event.
Returns:
float: Time remaining between now and the event, in
seconds since epoch.
"""
now = time.localtime()
time_remaining = time.mktime(event_time) - time.mktime(now)
re... | 5,355,752 |
def _repeat(values, count):
"""Produces a list of lists suitable for testing interleave.
Args:
values: for each element `x` the result contains `[x] * x`
count: determines how many times to repeat `[x] * x` in the result
Returns:
A list of lists of values suitable for testing interleave.
"""
ret... | 5,355,753 |
def start_selenium_server(logfile=None, jarpath=None, *params):
"""A hook to start the Selenium Server provided with SeleniumLibrary.
`logfile` must be either an opened file (or file-like object) or None. If
not None, Selenium Server log will be written to it.
`jarpath` must be either the absolute pat... | 5,355,754 |
def P2D_l_TAN(df, cond, attr): # P(attr | 'target', cond)
"""Calcule la probabilité d'un attribut sachant la classe et un autre attribut.
Parameters
----------
df : pandas.DataFrame
La base d'examples.
cond : str
Le nom de l'attribut conditionnant.
attr : str
Le nom de ... | 5,355,755 |
def has_no_jump(bigram, peaks_groundtruth):
"""
Tell if the two components of the bigram are same or successive in the sequence of valid peaks or not
For exemple, if groundtruth = [1,2,3], [1,1] or [2,3] have no jump but [1,3] has a jump.
bigram : the bigram to judge
peaks_groundtruth : the lis... | 5,355,756 |
def Base64WSDecode(s):
"""
Return decoded version of given Base64 string. Ignore whitespace.
Uses URL-safe alphabet: - replaces +, _ replaces /. Will convert s of type
unicode to string type first.
@param s: Base64 string to decode
@type s: string
@return: original string that was encoded as Base64
@... | 5,355,757 |
def make_window():
"""create the window"""
window = Tk()
window.title("Pac-Man")
window.geometry("%dx%d+%d+%d" % (
WINDOW_WIDTH,
WINDOW_HEIGHT,
X_WIN_POS,
Y_WIN_POS
)
)
window = window
return window | 5,355,758 |
def construct_scrape_regex_patterns(scrape_info: dict[str, Union[ParseResult, str]]) -> dict[str, Union[ParseResult, str]]:
""" Construct regex patterns for seasons/episodes """
logger.debug("Constructing scrape regexes")
for info in scrape_info:
if info == 'url':
continue
if i... | 5,355,759 |
def hasf(e):
"""
Returns a function which if applied with `x` tests whether `x` has `e`.
Examples
--------
>>> filter(hasf("."), ['statement', 'A sentence.'])
['A sentence.']
"""
return lambda x: e in x | 5,355,760 |
def borehole_model(x, theta):
"""Given x and theta, return matrix of [row x] times [row theta] of values."""
return f | 5,355,761 |
def findNodesOnHostname(hostname):
"""Return the list of nodes name of a (non-dmgr) node on the given hostname, or None
Function parameters:
hostname - the hostname to check, with or without the domain suffix
"""
m = "findNodesOnHostname:"
nodes = []
for nodename in listNodes():... | 5,355,762 |
def test_transaction_saved_from_new(session):
"""Assert that the payment is saved to the table."""
payment_account = factory_payment_account()
payment = factory_payment()
payment_account.save()
payment.save()
invoice = factory_invoice(payment.id, payment_account.id)
invoice.save()
fee_sc... | 5,355,763 |
def MakeControlClass( controlClass, name = None ):
"""Given a CoClass in a generated .py file, this function will return a Class
object which can be used as an OCX control.
This function is used when you do not want to handle any events from the OCX
control. If you need events, then you should derive a class... | 5,355,764 |
def obtenTipoNom(linea):
""" Obtiene por ahora la primera palabra del título, tendría que regresar de que se trata"""
res = linea.split('\t')
return res[6].partition(' ')[0] | 5,355,765 |
def histogramfrom2Darray(array, nbins):
"""
Creates histogram of elements from 2 dimensional array
:param array: input 2 dimensional array
:param nbins: number of bins so that bin size = (maximum value in array - minimum value in array) / nbins
the motivation for returning this array is for th... | 5,355,766 |
def build_pert_reg(unsupervised_regularizer, cut_backg_noise=1.0,
cut_prob=1.0, box_reg_scale_mode='fixed',
box_reg_scale=0.25, box_reg_random_aspect_ratio=False,
cow_sigma_range=(4.0, 8.0), cow_prop_range=(0.0, 1.0),):
"""Build perturbation regularizer."""
i... | 5,355,767 |
def part_5b_avg_std_dev_of_replicates_analysis_completed(*jobs):
"""Check that the initial job data is written to the json files."""
file_written_bool_list = []
all_file_written_bool_pass = False
for job in jobs:
data_written_bool = False
if job.isfile(
f"../../src/engines/go... | 5,355,768 |
def get_ifort_version(conf, fc):
"""get the compiler version"""
version_re = re.compile(r"ifort\s*\(IFORT\)\s*(?P<major>\d*)\.(?P<minor>\d*)", re.I).search
cmd = fc + ['--version']
out, err = fc_config.getoutput(conf, cmd, stdin=False)
if out:
match = version_re(out)
else:
match = version_re(err)
if not mat... | 5,355,769 |
def exportFlatClusterData(filename, root_dir, dataset_name, new_row_header,new_column_header,xt,ind1,ind2,display):
""" Export the clustered results as a text file, only indicating the flat-clusters rather than the tree """
filename = string.replace(filename,'.pdf','.txt')
export_text = export.ExportFi... | 5,355,770 |
def indent_multiline(s: str, indentation: str = " ", add_newlines: bool = True) -> str:
"""Indent the given string if it contains more than one line.
Args:
s: String to indent
indentation: Indentation to prepend to each line.
add_newlines: Whether to add newlines surrounding the result... | 5,355,771 |
def _get_property(self, key: str, *, offset: int = 0) -> Optional[int]:
"""Get a property from the location details.
:param key: The key for the property
:param offset: Any offset to apply to the value (if found)
:returns: The property as an int value if found, None otherwise
"""
value = self.... | 5,355,772 |
def pca_normalization(points):
"""Projects points onto the directions of maximum variance."""
points = np.transpose(points)
pca = PCA(n_components=len(np.transpose(points)))
points = pca.fit_transform(points)
return np.transpose(points) | 5,355,773 |
def _reformTrend(percs, inits):
"""
Helper function to recreate original trend based on percent change data.
"""
trend = []
trend.append(percs[0])
for i in range(1, len(percs)):
newLine = []
newLine.append(percs[i][0]) #append the date
for j in range(1, len(percs[i])): #for each term on date
level =... | 5,355,774 |
def create_zenpack_srcdir(zenpack_name):
"""Create a new ZenPack source directory."""
import shutil
import errno
if os.path.exists(zenpack_name):
sys.exit("{} directory already exists.".format(zenpack_name))
print "Creating source directory for {}:".format(zenpack_name)
zenpack_name_p... | 5,355,775 |
def PET_initialize_compression_structure(N_axial,N_azimuthal,N_u,N_v):
"""Obtain 'offsets' and 'locations' arrays for fully sampled PET compressed projection data. """
descriptor = [{'name':'N_axial','type':'uint','value':N_axial},
{'name':'N_azimuthal','type':'uint','value':N_azimuthal},
... | 5,355,776 |
def tic():
"""Mimics Matlab's tic toc"""
global __start_time_for_tictoc__
__start_time_for_tictoc__ = time.time() | 5,355,777 |
def get_client_from_user_settings(settings_obj):
"""Same as get client, except its argument is a DropboxUserSettingsObject."""
return get_client(settings_obj.owner) | 5,355,778 |
def train_student(
model,
dataset,
test_data,
test_labels,
nb_labels,
nb_teachers,
stdnt_share,
lap_scale,
):
"""This function trains a student using predictions made by an ensemble of
teachers. The student and teacher models are trained using the same neural
network architec... | 5,355,779 |
def create_transition_matrix_numeric(mu, d, v):
"""
Use numerical integration.
This is not so compatible with algopy because it goes through fortran.
Note that d = 2*h - 1 following Kimura 1957.
The rate mu is a catch-all scaling factor.
The finite distribution v is assumed to be a stochastic ve... | 5,355,780 |
def parse_integrate(filename='INTEGRATE.LP'):
"""
Harvest data from INTEGRATE
"""
if not os.path.exists(filename):
return {'failure': 'Integration step failed'}
info = parser.parse(filename, 'integrate')
for batch, frames in zip(info.get('batches',[]), info.pop('batch_frames', [])):
... | 5,355,781 |
def test_backup_replica_resumes_ordering_on_lag_in_checkpoints(
looper, chkFreqPatched, reqs_for_checkpoint,
one_replica_and_others_in_backup_instance,
sdk_pool_handle, sdk_wallet_client, view_change_done, txnPoolNodeSet):
"""
Verifies resumption of ordering 3PC-batches on a backup repli... | 5,355,782 |
def eprint(msg):
"""
Prints given ``msg`` into sys.stderr as nose test runner hides all output
from sys.stdout by default and if we want to pipe stream somewhere we don't
need those verbose messages anyway.
Appends line break.
"""
sys.stderr.write(msg)
sys.stderr.write('\n') | 5,355,783 |
def channelmap(stream: Stream, *args, **kwargs) -> FilterableStream:
"""https://ffmpeg.org/ffmpeg-filters.html#channelmap"""
return filter(stream, channelmap.__name__, *args, **kwargs) | 5,355,784 |
def test_token(current_user: DBUser = Depends(get_current_user)):
"""
Test access-token
"""
return current_user | 5,355,785 |
def locate_data(name, check_exists=True):
"""Locate the named data file.
Data files under mls/data/ are copied when this package is installed.
This function locates these files relative to the install directory.
Parameters
----------
name : str
Path of data file relative to mls/data.
... | 5,355,786 |
def links():
"""
For type hints, read `PEP 484`_.
See the `Python home page <http://www.python.org>`_ for info.
.. _PEP 484:
https://www.python.org/dev/peps/pep-0484/
""" | 5,355,787 |
def process_label_imA(im):
"""Crop a label image so that the result contains
all labels, then return separate images, one for
each label.
Returns a dictionary of images and corresponding
labels (for choosing colours), also a scene bounding
box. Need to run shape statistics to determine
the n... | 5,355,788 |
def render_graphs(csv_data, append_titles=""):
"""
Convenience function. Gets the aggregated `monthlies` data from
`aggregate_monthly_data(csv_data)` and returns a dict of graph
titles mapped to rendered SVGs from `monthly_total_precip_line()`
and `monthly_avg_min_max_temp_line()` using the `monthli... | 5,355,789 |
def _get_location():
"""Return the location as a string, accounting for this function and the parent in the stack."""
return "".join(traceback.format_stack(limit=STACK_LIMIT + 2)[:-2]) | 5,355,790 |
def test_syscall_client_init():
"""Tests SysCallClient.__init__"""
from apyfal.client.syscall import SysCallClient
from apyfal import Accelerator
import apyfal.configuration as cfg
import apyfal.exceptions as exc
# Test: accelerator_executable_available, checks return type
assert type(cfg.a... | 5,355,791 |
def start_session():
"""do nothing here
"""
return Response.failed_response('Error') | 5,355,792 |
def test_pairwise_mlp_init(pairwise_mlp):
"""Test PairwiseMLP.__init__ sets state correctly."""
assert pairwise_mlp.in_features == PROJ_FEATURES
assert pairwise_mlp.hidden_features == PROJ_FEATURES
assert pairwise_mlp.project is not None | 5,355,793 |
def _combine_keras_model_with_trill(embedding_tfhub_handle, aggregating_model):
"""Combines keras model with TRILL model."""
trill_layer = hub.KerasLayer(
handle=embedding_tfhub_handle,
trainable=False,
arguments={'sample_rate': 16000},
output_key='embedding',
output_shape=[None, 2048]... | 5,355,794 |
def phases(times, names=[]):
""" Creates named phases from a set of times defining the edges of hte intervals """
if not names: names = range(len(times)-1)
return {names[i]:[times[i], times[i+1]] for (i, _) in enumerate(times) if i < len(times)-1} | 5,355,795 |
def deploy():
"""
定义一个部署任务
:return:
"""
# 先进行打包
pack()
# 备份服务器上的版本
backup()
# 远程服务器的临时文件
remote_tmp_tar = '/tmp/%s' % TAR_FILE_NAME
run('rm -f %s' % remote_tmp_tar)
# 上传tar文件至远程服务器
put(TAR_FILE_NAME, remote_tmp_tar)
remote_dist_base_dir = '/home/python'
# 如果... | 5,355,796 |
def smesolve(H, rho0, times, c_ops=[], sc_ops=[], e_ops=[],
_safe_mode=True, args={}, **kwargs):
"""
Solve stochastic master equation. Dispatch to specific solvers
depending on the value of the `solver` keyword argument.
Parameters
----------
H : :class:`qutip.Qobj`, or time depen... | 5,355,797 |
def harmonic_vector(n):
"""
create a vector in the form [1,1/2,1/3,...1/n]
"""
return np.array([[1.0 / i] for i in range(1, n + 1)], dtype='double') | 5,355,798 |
def session(connection):
"""
Create a transaction and session per test unit.
Rolling back a transaction removes even committed rows
(``session.commit``) from the database.
"""
transaction = connection.begin()
session = Session(bind=connection)
yield session
session.close()
trans... | 5,355,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.