content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def check_seal(item):
"""
Given a message object, use the "seal" attribute - a cryptographic
signature to prove the provenance of the message - to check it is valid.
Returns a boolean indication of validity.
"""
try:
item_dict = to_dict(item)
raw_sig = item_dict['seal']
s... | 14,700 |
def plot_win_prob(times, diff, end_lim, probs, team_abr, bools):
""" This function plots the win probability and
score differential for the game
@param times (list): list containing actual_times
and times. times contains all of the times at
which win probability was calculated
@param di... | 14,701 |
def add_office():
"""Given that i am an admin i should be able to add a political office
When i visit ../api/v2/offices endpoint using POST method"""
if is_admin() is not True:
return is_admin()
errors = []
try:
if not request.get_json(): errors.append(
make_response(j... | 14,702 |
def gen(iterable):
"""
gen(iter: iterable)
accept a iterable object; return a generator
implement:
for e in iterable: yield e
"""
for e in iterable:
yield e | 14,703 |
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info('making final data set from raw data')
cycle3 = pd.read_csv(Path(inp... | 14,704 |
def send_message(
mg: mailgun.MailGun,
templates: t.Tuple[str, str],
contact_name: str,
contact_email: str,
sender: str,
reply_to: str,
sponsorship_package: t.Optional[Path],
dry_run: bool,
) -> bool:
"""
Send an individual email and report if it was successful
:param mg: the... | 14,705 |
def UABD(cpu_context: ProcessorContext, instruction: Instruction):
"""Unsigned absolute difference (vector form)"""
logger.debug("%s instruction not currently implemented.", instruction.mnem) | 14,706 |
def test_var_length_list_of_lists():
"""Check that length of dict <= number of lists when passed a list of lists."""
plots = make_qqplot(data_lists,print_plots=False)
assert len(plots.keys()) <= len(data_lists) | 14,707 |
def test_default():
""" Tests default metadata cube generated """
cube = generate_metadata(MANDATORY_ATTRIBUTE_DEFAULTS)
assert cube.name() == NAME_DEFAULT
assert cube.standard_name == NAME_DEFAULT
assert cube.units == UNITS_DEFAULT
assert cube.ndim == NDIMS_DEFAULT
assert cube.shape == (E... | 14,708 |
def multi_class5_classification_dataset_sparse_labels() -> tf.data.Dataset:
"""
TensorFlow dataset instance with multi-class sparse labels (5 classes)
:return: Multi-class sparse (labels) classification dataset
"""
# Create features
X = tf.random.normal(shape=(100, 3))
# Create one multi-... | 14,709 |
def skipIfNAN(proteinPath):
""" Test if there is a NAN (not a number) in the lists """
overlapArrayWhole = None
overlapArrayInterface = None
overlapTApproxWhole = None
overlapTApproxInterface = None
try:
overlapArrayWhole = np.loadtxt(proteinPath+"overlapArrayWhole.txt")
except IOErr... | 14,710 |
def alignment_view(request, project_uid, alignment_group_uid):
"""View of a single AlignmentGroup.
"""
project = get_object_or_404(Project, owner=request.user.get_profile(),
uid=project_uid)
alignment_group = get_object_or_404(AlignmentGroup,
reference_genome__project=project, u... | 14,711 |
async def get_latest_disclosure(compass_id: int, api: ci.CompassInterface = Depends(ci_user)) -> Optional[ci.MemberDisclosure]:
"""Gets the latest disclosure for the member given by `compass_id`."""
logger.debug(f"Getting /{{compass_id}}/latest-disclosure for {api.user.membership_number}")
async with error_... | 14,712 |
def get_matching_string(matches, inputText, limit=0.99):
"""Return the matching string with all of the license IDs matched with the input license text if none matches then it returns empty string.
Arguments:
matches {dictionary} -- Contains the license IDs(which matched with the input text) with th... | 14,713 |
def get_review(annotation):
"""
Get annotation's review (if exists).
"""
try:
review = Comment.objects.get(annotation=annotation)
return review
except Comment.DoesNotExist:
return None | 14,714 |
def load_grid(grdfiles, blocks, dimpart, nsigma, **kwargs):
"""Setup a `grid` by reading `grdfiles` on `blocks`
"""
ncgrid = nct.MDataset(grdfiles, blocks, dimpart, **kwargs)
# dummy time, to be updated later
time = ma.Marray(np.arange(10), dims=tdims)
lat = nct.readmarray(ncgrid, "lat_rho", h... | 14,715 |
def with_patch_inspect(f):
"""decorator for monkeypatching inspect.findsource"""
def wrapped(*args, **kwargs):
save_findsource = inspect.findsource
save_getargs = inspect.getargs
inspect.findsource = findsource
inspect.getargs = getargs
try:
return f(*args, *... | 14,716 |
def apply_hux_f_model(r_initial, dr_vec, dp_vec, r0=30 * 695700, alpha=0.15, rh=50 * 695700, add_v_acc=True,
omega_rot=(2 * np.pi) / (25.38 * 86400)):
"""Apply 1d upwind model to the inviscid burgers equation.
r/phi grid. return and save all radial velocity slices.
:param r_initial: 1... | 14,717 |
def requires_request_arg(method):
"""
Helper function to handle deprecation of old ActionMenuItem API where get_url, is_show,
get_context and render_html all accepted both 'request' and 'parent_context' as arguments
"""
try:
# see if this is a pre-2.15 get_url method that takes both request ... | 14,718 |
def show_output_to_df(
show_output: str,
spark_session: SparkSession,
default_data_type: str = 'string'
):
"""
Takes a string containing the output of a Spark DataFrame.show() call and
"rehydrates" it into a new Spark DataFrame instance. Example input:
+--------+--------+
|co... | 14,719 |
def Schwefel(arr: np.ndarray, seed: int = 0) -> float:
"""Implementation for BBOB Schwefel function."""
del seed
dim = len(arr)
bernoulli_arr = np.array([pow(-1, i + 1) for i in range(dim)])
x_opt = 4.2096874633 / 2.0 * bernoulli_arr
x_hat = 2.0 * (bernoulli_arr * arr) # Element-wise multiplication
z_ha... | 14,720 |
def article_idx_to_words_row(article_idx):
"""
Given a tuple with an article and an index, return a Row with the
index ad a list of the words in the article.
The words in the article are normalized, by removing all
non-'a-z|A-Z' characters.
Any stop words (words of less than 2 characters) are ... | 14,721 |
def get_device_strategy(device, half=False, XLA=False, verbose=True):
"""
Returns the distributed strategy object, the tune policy anb the number of replicas.
Parameters
----------
device : str
Possible values are "TPU", "GPU", "CPU"
verbose : bool
Whether to pri... | 14,722 |
def make_mask(
pois_gdf,
link_gdf,
):
"""
:param pois_gdf:
:param link_gdf:
:return:
"""
mask = np.array([])
enum = np.array([])
return mask, enum | 14,723 |
def SEMIMINUS(r1, r2):
"""aka NOT MATCHING
(macro)"""
return MINUS(r1, SEMIJOIN(r1, r2)) | 14,724 |
def send(url: str, webhookname: str, messages: List[str]) -> None:
"""SQS経由でWebhookにメッセージを送る.
Args:
url (str): SQSのURL
webhookname (str): Webhook名
messages (List[str]): メッセージのリスト
"""
logger.info(f'sqs.send: sending {len(messages)} message(s).')
splited = (messages[idx:idx + ... | 14,725 |
def Ineg_wrapper(valS, valI):
"""
Function used to wrap Inequalities into a suitable form for optimisation
valS > valI --> Inequality is satisfied
valS and valI can be float or 1d array
"""
epsilon = 1e-6
top = 1e3
ecart = valI - valS
if ecart < epsilon:
out = np.... | 14,726 |
def preprocess_imgs(set_name, img_size):
"""
Resize and apply VGG-15 preprocessing
"""
set_new = []
for img in set_name:
img = cv2.resize(
img,
dsize=img_size,
interpolation=cv2.INTER_CUBIC
)
set_new.append(tf.keras.applications.vgg16.prepr... | 14,727 |
def get_shapes(galsim_img, center):
""" Get shapes
This function compute the moments of an image. Then return the sigma of the
window function used (size of the object) and the amplitude
(flux of the object).
Parameters
---------
galsim_img : galsim.image.Image
Galsim.image object ... | 14,728 |
def consolidate_mouse_probes(data_containers, filename_or_fileobj, object_name='mouse_data_frame', poobah_column='poobah_pval', poobah_sig=0.05):
""" these probes have 'Multi'|'Random' in `design` col of mouse manifest. used to populate 'mouse_probes.pkl'.
pre v1.4.6: ILLUMINA_MOUSE specific probes (starting wi... | 14,729 |
def test_field_map_ctf():
"""Test that field mapping can be done with CTF data."""
raw = read_raw_fif(raw_ctf_fname).crop(0, 1)
raw.apply_gradient_compensation(3)
events = make_fixed_length_events(raw, duration=0.5)
evoked = Epochs(raw, events).average()
evoked.pick_channels(evoked.ch_names[:50]... | 14,730 |
def ascending_super_operator(hamAB, hamBA, w_isometry, v_isometry, unitary,
refsym):
"""
ascending super operator for a modified binary MERA
ascends 'hamAB' and 'hamBA' up one layer
Args:
hamAB (tf.Tensor): local Hamiltonian on the A-B lattice
hamBA (tf.Tenso... | 14,731 |
def filteredhash(repo, maxrev):
"""build hash of filtered revisions in the current repoview.
Multiple caches perform up-to-date validation by checking that the
tiprev and tipnode stored in the cache file match the current repository.
However, this is not sufficient for validating repoviews because the ... | 14,732 |
def test_NodeBipartite_observation(solving_model):
"""Observation of NodeBipartite is a type with array attributes."""
obs = make_obs(O.NodeBipartite(), solving_model)
assert isinstance(obs, O.NodeBipartiteObs)
assert_array(obs.column_features, ndim=2)
assert_array(obs.row_features, ndim=2)
asse... | 14,733 |
def filter_blast_by_amplicon(blast_hits, min_amplicon_len, max_amplicon_len):
"""
Filtering primers by putative amplicon that would be generated.
If the amplicon size is outsize of the min/max, then the primers not legit off-targets.
"""
logging.info('Filtering to only hits producing a legitimate am... | 14,734 |
def cropImage(img):
"""
Crop the screen for only the relevant inventory section.
Args:
img (ndarray): The image of the Warframe inventory.
Returns:
ndarray: The image of only the inventory section containing items.
"""
#TODO: Allow user to manually define inventory section inst... | 14,735 |
def determine_channel(channel_as_text):
"""Determine which channel the review is for according to the channel
parameter as text, and whether we should be in content-review only mode."""
if channel_as_text == 'content':
# 'content' is not a real channel, just a different review mode for
# lis... | 14,736 |
def parse_workflow_args(input: List[str] = None) -> argparse.Namespace:
"""Parses command-line style flags for the workflow.
All unknown args are discarded to allow multiple parses on args.
Args:
input: An optional list of strings in the style of sys.argv. Will
default to argparse's int... | 14,737 |
def get_device_config(device_name, dnac_jwt_token):
"""
This function will get the configuration file for the device with the name {device_name}
:param device_name: device hostname
:param dnac_jwt_token: DNA C token
:return: configuration file
"""
device_id = get_device_id_name(device_name, ... | 14,738 |
def release_not_found(pp, release_task, nick):
"""
Return a deferred that when fired returns a message about this missing
release.
:param pp: txproductpages.Connection object
:param release_task: ReleaseTask object
:param nick: str, user who asked about this release_task.
"""
template =... | 14,739 |
def get_ideas():
"""
Gets all ideas from mongo
"""
return find('ideas') | 14,740 |
def uppercase_dtype(dtype):
""" Convert a dtype to upper case. A helper function.
Do not use.
"""
pairs = dict([(key.upper(), dtype.fields[key]) for key in dtype.names])
dtype = numpy.dtype(pairs)
return dtype | 14,741 |
def test_no_header_without_setting():
"""Make sure that the endpoint has no authorization header if either username or password is missing"""
client1 = PublicationDataApi("no-url", "dummy", None)
client2 = PublicationDataApi("no-url", None, "abc")
client3 = PublicationDataApi("no-url", None, None)
h... | 14,742 |
def download_files_by_name(accession, file_name, ftp_download_enabled, input_folder, output_folder):
"""
This script download files from FTP or copy from the file system
"""
raw_files = Files()
logging.info("accession: " + accession)
if ftp_download_enabled:
logging.info("Data will be... | 14,743 |
async def async_setup(hass, config):
"""Set up the sisyphus component."""
from sisyphus_control import Table
tables = hass.data.setdefault(DATA_SISYPHUS, {})
table_configs = config.get(DOMAIN)
session = async_get_clientsession(hass)
async def add_table(host, name=None):
"""Add platforms... | 14,744 |
def mlp_prior(input_dim: int, zdim: int = 2) -> Dict[str, jnp.array]:
"""Priors over weights and biases in the default Bayesian MLP"""
hdim = [64, 32]
def _bnn_prior(task_dim: int):
w1 = sample_weights("w1", input_dim, hdim[0], task_dim)
b1 = sample_biases("b1", hdim[0], task_dim)
w... | 14,745 |
def main():
"""Main entry point."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apk', dest='apk_path', type=str, default=None,
help='Path to an APK to install on the device.')
parser.add_argument('--refresh-bins', action='store_true', default=Fals... | 14,746 |
def get_biggest_spread_by_symbol(exchanges, symbol):
"""Get biggest spread by symbol."""
ask_exchange_id = ""
min_ask_price = 99999999
bid_exchange_id = ""
max_bid_price = 0
for exchange_id in exchanges:
exchange = eval("ccxt.{0}()".format(exchange_id))
try:
order_... | 14,747 |
def gmag_filename(dates, stations):
"""Create a list of tuples for downloading: remote_file, local_file"""
prefs = pyspedas.get_spedas_prefs()
if 'themis_remote' in prefs:
remote_path = prefs['themis_remote']
else:
raise NameError('remote_path is not found in spd_prefs_txt.py')
if 'd... | 14,748 |
def always_mocked_kubernetes_client(mocker):
"""
We do not test the Kubernetes client, so everything there should be mocked.
Also, no external calls must be made under any circumstances.
"""
mocker.patch('kubernetes.watch')
mocker.patch('kubernetes.client') | 14,749 |
def test_compile_hourly_statistics_unchanged(hass_recorder):
"""Test compiling hourly statistics, with no changes during the hour."""
hass = hass_recorder()
recorder = hass.data[DATA_INSTANCE]
setup_component(hass, "sensor", {})
zero, four, states = record_states(hass)
hist = history.get_signifi... | 14,750 |
def count_ends(d):
"""
count number of consecutive letters
:param d:
:return:
"""
con=0
for i in range(len(d)-1):
if d[i][-1] == d[i+1][-1]:
con+=1
print("{} consecutive letters".format(con)) | 14,751 |
def print_results(results):
"""Prints `results` (the results of validation) to stdout.
Args:
results: A list of FileValidationResults instances.
"""
for file_result in sorted(results, key=operator.attrgetter("filepath")):
print_horizontal_rule()
print_level(logger.info, "[-] Re... | 14,752 |
def update_user():
"""User update route
:return: action status
"""
if 'data' in request.json:
data = request.json['data']
if ('profile' in data) and ('theme' in data['profile']):
current_user.profile.theme = data['profile']['theme']
services.db.session.commit()
r... | 14,753 |
def on_deck(elements: List[int], all_vars):
"""all of the elements must be within the deck"""
rules = []
for element in elements:
var = all_vars[element - 1]
rules.append(var >= 1)
rules.append(var <= 52)
return rules | 14,754 |
def transform_data_to_dictionary(elements):
"""Parses each element in the list and parses it in a dictionary
Args:
elements (list): list of html elements
Returns:
dictionary: treated information.
"""
url_informations = {}
for n in range(0, len(elements), 2):
... | 14,755 |
def postprocess_new(u, x, lr_min, lr_max, num_itr, rho=0.0, with_l1=False,s=math.log(9.0)):
"""
:param u: utility matrix, u is assumed to be symmetric, in batch
:param x: RNA sequence, in batch
:param lr_min: learning rate for minimization step
:param lr_max: learning rate for maximization step (for... | 14,756 |
def _assert_zone_state(hass, mode, hvac, current_temp, target_temp, preset, action):
"""Assert zone climate state."""
state = hass.states.get("climate.zone_1")
assert hass.states.is_state("climate.zone_1", hvac)
assert state.attributes["current_temperature"] == current_temp
assert state.attributes[... | 14,757 |
def upgrade(ctx, config_file_path, skip_config_decryption):
"""Upgrade existing CSE installation/entities to match CSE 3.1.1.
\b
- Add CSE, RDE version, Legacy mode info to VCD's extension data for CSE
- Register defined entities schema of CSE k8s clusters with VCD
- Create placement compute policies u... | 14,758 |
def test_orion(provider, keyid, secret, token, imageid, subscription, tenant, projectid,
instancetype, user, localpath, region, zone, sriov, kernel):
"""
Run Orion test.
:param provider Service provider to be used e.g. azure, aws, gce.
:param keyid: user key for executing remote connectio... | 14,759 |
def parse_api_error(response):
"""
Parse the error-message from the API Response.
Assumes, that a check if there is an error present was done beforehand.
:param response: Dict of the request response ([imdata][0][....])
:type response: ``dict``
:returns: Parsed Error-Text
:rtype: ``str``
... | 14,760 |
def test_dataset_pubtabnet_returns_image() -> None:
"""
test dataset pubtabnet returns image
"""
# Arrange
pubtabnet = Pubtabnet()
pubtabnet.dataflow.get_workdir = get_test_path # type: ignore
pubtabnet.dataflow.annotation_files = {"all": "test_file.jsonl"}
df = pubtabnet.dataflow.buil... | 14,761 |
def set_api_file(name, file):
"""Set an URL generator populated with data from `file`.
Use `file` to populate a new `DocUrlGenerator` instance and register it
as `name`.
:Parameters:
`name` : `str`
the name of the generator to be registered
`file` : `str` or file
the file t... | 14,762 |
def test_check_ensemble_build_no_lc():
"""[Utils] check_ensemble_build : raises error on no LC."""
lc = clone(LAYER_CONTAINER)
del lc.stack
np.testing.assert_raises(AttributeError, check_ensemble_build, lc) | 14,763 |
def access_settings(service, groupId, settings):
"""Retrieves a group's settings and updates the access permissions to it.
Args:
service: object service for the Group Settings API.
groupId: string identifier of the group@domain.
settings: dictionary key-value pairs of properties of group.
"""
# Ge... | 14,764 |
def test_breadth_first_traversal(testing_bst):
"""test that values will come out correctly for a breath first traversal"""
answer = []
def do_this(current):
answer.append(current.val.val)
breadth_first_traversal(testing_bst, do_this)
assert answer == [20, 17, 21, 16, 18, 22] | 14,765 |
def test_instantiate():
"""Test whether UncertaintyQuantificationBase fails to instantiate."""
if sys.version[0] == 2:
d = UncertaintyQuantificationBase()
else:
# abstract base class type error not raised
# in python 3.
raise (TypeError) | 14,766 |
def create_tasks(
tasks: List[Union[Task, Dict]],
*,
pool: Union[Pool, Training, Dict, str, None] = None,
toloka_conn_id: str = 'toloka_default',
additional_args: Optional[Dict] = None,
) -> None:
"""Create a list of tasks for a given pool.
Args:
tasks: List of either a `Task` object... | 14,767 |
def login_manual_user_device(username: str, password: str, mac_address: str) -> Union[str, Token]:
"""Try to login by username and password. A token for auto-login is returned"""
possible_user = User.get_by_username(username)
if possible_user is None:
fail_msg = f"No user with username: {username}."... | 14,768 |
def corrector_new(Ybus, Ibus, Sbus, V0, pv, pq, lam0, Sxfr, Vprv, lamprv, z, step, parametrization, tol, max_it,
verbose, max_it_internal=10):
"""
Solves the corrector step of a continuation power flow using a full Newton method
with selected parametrization scheme.
solves for bus vol... | 14,769 |
def retrieve_files(dir, suffix='png|jpg'):
""" retrive files with specific suffix under dir and sub-dirs recursively
"""
def retrieve_files_recursively(dir, file_lst):
for d in sorted(os.listdir(dir)):
dd = osp.join(dir, d)
if osp.isdir(dd):
retrieve_files_r... | 14,770 |
def clique_ring(n_cluster=3, n_in_cluster=5):
"""Get adjacency matrix for cluster domain used by Schapiro et al 2013.
Args:
n_cluster: number of clusters, connected in a ring.
n_in_cluster: number of nodes in each cluster. Each node is connected to all
other nodes in cluster, except the edge connecti... | 14,771 |
def get_halfnormal_mean_from_scale(scale: float) -> float:
"""Returns the mean of the half-normal distribition."""
# https://en.wikipedia.org/wiki/Half-normal_distribution
return scale * np.sqrt(2) / np.sqrt(np.pi) | 14,772 |
def cal_pr(y_hat, y_score):
"""
calculate the precision and recall curve
:param y_hat: ground-truth label, [n_sample]
:param y_score: predicted similarity score, [n_sample]
:return: [n_sample]
"""
thresholds = np.arange(1, -0.001, -0.001)
fps, tps = cal_binary_cls_curve(y_hat, y_score, t... | 14,773 |
def alert_source_create(context, values):
"""Create an alert source."""
return IMPL.alert_source_create(context, values) | 14,774 |
def node_class_new(Node : list, name, extend, method) -> None:
"""
Node_class
/ | \
name extend method
"""
Node.append(["node_class", name, extend, method]) | 14,775 |
def sanitise_utf8(s):
"""Ensure an 8-bit string is utf-8.
s -- 8-bit string (or None)
Returns the sanitised string. If the string was already valid utf-8, returns
the same object.
This replaces bad characters with ascii question marks (I don't want to use
a unicode replacement character, beca... | 14,776 |
def do_show_etf_chart():
""" ETF charts
"""
period_item = st.session_state.get("period", "daily")
period = PERIOD_DICT[period_item]
for sect in st.session_state.get("selected_sectors", DEFAULT_SECTORS):
st.subheader(sect)
for k,v in etf_dict[sect].items():
st.image(f"htt... | 14,777 |
def trans_r2xy(r, phi, r_e, phi_e):
"""r,phi -> x,y """
x = np.array(r) * np.cos(phi)
y = np.array(r) * np.sin(phi)
err = np.array(
[polar_err(i, j, k, l) for i, j, k, l in zip(r, phi, r_e, phi_e)]
)
return x, y, err[:, 0], err[:, 1] | 14,778 |
def ldpc_bp_decode(llr_vec, ldpc_code_params, decoder_algorithm, n_iters):
"""
LDPC Decoder using Belief Propagation (BP).
Parameters
----------
llr_vec : 1D array of float
Received codeword LLR values from the channel.
ldpc_code_params : dictionary
Parameters of the LDPC code.... | 14,779 |
def test_atomic_g_day_max_exclusive_1_nistxml_sv_iv_atomic_g_day_max_exclusive_2_5(mode, save_output, output_format):
"""
Type atomic/gDay is restricted by facet maxExclusive with value ---25.
"""
assert_bindings(
schema="nistData/atomic/gDay/Schema+Instance/NISTSchema-SV-IV-atomic-gDay-maxExclu... | 14,780 |
def edit_style_formats(style_format_id, **kwargs):
"""Create or edit styles formats.
:param style_format_id: identifier of a specific style format
"""
if request.method == "POST":
args = request.get_json()
errors = StyleFormatsSchema().validate(args)
if err... | 14,781 |
def restore_snapshots():
""" Restore snapshot into correct directories.
Returns:
True on success, False otherwise.
"""
logging.info("Restoring Cassandra snapshots.")
for directory in CASSANDRA_DATA_SUBDIRS:
data_dir = "{0}/{1}/{2}/".format(APPSCALE_DATA_DIR, "cassandra",
directory)
logging... | 14,782 |
def volume_to_vtk(volelement, origin=(0.0, 0.0, 0.0)):
"""Convert the volume element to a VTK data object.
Args:
volelement (:class:`omf.volume.VolumeElement`): The volume element to
convert
"""
output = volume_grid_geom_to_vtk(volelement.geometry, origin=origin)
shp = get_volu... | 14,783 |
def test_fn014_detail(api_client, project):
"""The gear detail object should return 5 basic elements - the
project code, gear code, gear description, start date and end
date.
"""
prj_cd = project.prj_cd
gr = "GL01"
eff = "038"
url = reverse(
"fn_portal_api:fn014-detail", kwargs=... | 14,784 |
def import_post_office_csv():
"""データベースに日本郵便Webサイトの郵便番号CSVデータを格納"""
post_office_csv = PostOfficeCSV()
factory = AreaAddressFactory()
for row in post_office_csv.lists:
factory.create(**row)
db = DB()
try:
service = AreaAddressService(db)
for area_address in factory.items... | 14,785 |
def plot_heat_capacity(Cv, dCv, temperature_list, file_name="heat_capacity.pdf"):
"""
Given an array of temperature-dependent heat capacity values and the uncertainties in their estimates, this function plots the heat capacity curve.
:param Cv: The heat capacity data to plot.
:type Cv: ... | 14,786 |
def _in_delta(value, target_value, delta) -> bool:
"""
Check if value is equal to target value within delta
"""
return abs(value - target_value) < delta | 14,787 |
def getpar(key, file='DATA/Par_file', sep='=', cast=str):
""" Reads parameter from SPECFEM parfile
"""
val = None
with open(file, 'r') as f:
# read line by line
for line in f:
if find(line, key) == 0:
# read key
key, val = _split(line, sep)
... | 14,788 |
def replace_links(text: str, replace, site: 'pywikibot.site.BaseSite') -> str:
"""Replace wikilinks selectively.
The text is searched for a link and on each link it replaces the text
depending on the result for that link. If the result is just None it skips
that link. When it's False it unlinks it and ... | 14,789 |
def create_ok_response() -> flask.Response:
"""Creates a 200 OK response.
:return: flask.Response.
"""
ok_body: Dict[str, str] = {"status": "OK"}
return make_response(jsonify(ok_body), HTTP_200_OK) | 14,790 |
async def test_camera_off(hass):
"""Test the camera turn off service."""
await setup_platform(hass, CAMERA_DOMAIN)
with patch("abodepy.AbodeCamera.privacy_mode") as mock_capture:
await hass.services.async_call(
CAMERA_DOMAIN,
"turn_off",
{ATTR_ENTITY_ID: "camera.... | 14,791 |
def compile_ui_if_needed(ui_file_path: str, ignore_mtime: bool=False):
"""
The following will dynamically compile the Qt Designer '.ui' file
given by C{ui_file_path}, and import and load the generated Python
module. The generated module will have the name:
C{ui_file_path} + '_ui.py'
... | 14,792 |
def test_len_drops_symlinks_from_the_job_count_to_avoid_double_counting(proj):
"""
Test that __len__ has the correct behaviour when symlinks
are present
"""
symlink = proj.basepath / "AutoPick" / "autopick2"
symlink.symlink_to(proj.basepath / "AutoPick" / "job006")
sym_autopick = proj.autopi... | 14,793 |
def pickleExists(name):
"""
Returns True if there is a pickle with name in cache, False otherwise. Used to prevent
cache misses
:param name: Name to look for in cache
:return: True on hit, False on miss
"""
fileNames = [f for f in os.listdir(PICKLE_DIR) if name in f]
return not len(fileN... | 14,794 |
def main():
"""
This handles the command line input of the runner
(it's most often called by evennia.py)
"""
parser = OptionParser(usage="%prog [options] start",
description="This runner should normally *not* be called directly - it is called automatically from the evennia.py main program. It... | 14,795 |
def procs() -> None:
""" Entry point for liftoff-procs.
"""
opts = parse_options()
display_procs(get_running_liftoffs(opts.experiment, opts.results_path)) | 14,796 |
def format_timestamp(timestamp):
"""Formats an UTC timestamp into a date string.
>>> format_timestamp("2014-04-08T12:41:34+0100")
'Tue, 08 Apr 2014 12:41:34'
"""
t = iso8601.parse_date(timestamp).timetuple()
return time.strftime("%a, %d %b %Y %H:%M:%S", t) | 14,797 |
def _flat(xvals):
"""
Function for flat surface y=0, with boundary conditions
Parameters
----------
xvals : np.array
x-values of the surface.
Returns
-------
yvals : np.array
y-Values of the initialized surface.
"""
yvals = np.zeros_like(xvals)
return yvals | 14,798 |
def regularized_laplacian(weights, labels, alpha):
"""Uses the laplacian graph to smooth the labels matrix by "propagating" labels
Args:
weights: Tensor of shape (batch, n, n)
labels: Tensor of shape (batch, n, n_classes)
alpha: Scaler, acts as a smoothing factor
apply_log: if T... | 14,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.