content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def write_change_det_fd_section(father_item, change_det_fd_obj):
"""
place older function to be developed yet , if required
"""
pass | 48,300 |
def create_auto_edge_set(graph, transport_guid):
"""Set up an automatic MultiEdgeSet for the intersite graph
From within MS-ADTS 6.2.2.3.4.4
:param graph: the intersite graph object
:param transport_guid: a transport type GUID
:return: a MultiEdgeSet
"""
e_set = MultiEdgeSet()
# use a ... | 48,301 |
def jaccard(box_a, box_b):
"""Compute the jaccard overlap of two sets of boxes. The jaccard overlap
is simply the intersection over union of two boxes. Here we operate on
ground truth boxes and default boxes.
E.g.:
A ∩ B / A ∪ B = A ∩ B / (area(A) + area(B) - A ∩ B)
Args:
bo... | 48,302 |
def concat(input, axis, main_program=None, startup_program=None):
"""
This function concats the input along the axis mentioned
and returns that as the output.
"""
helper = LayerHelper('concat', **locals())
out = helper.create_tmp_variable(dtype=helper.input_dtype())
helper.append_op(
... | 48,303 |
def is_available():
"""Return true if a pdfjs installation is available."""
try:
get_pdfjs_res('build/pdf.js')
get_pdfjs_res('web/viewer.html')
except PDFJSNotFound:
return False
else:
return True | 48,304 |
def problem6():
"""
Runs simulations and make histograms for problem 6.
Runs multiple simulations to show the relationship between administration
of multiple drugs and patient outcome.
Histograms of final total virus populations are displayed for lag times of
150, 75, 0 timesteps b... | 48,305 |
def print_info(msg: str, fd: TextIO = None):
"""
Print with prefix ``INFO:``
:param msg: The message to be printed.
:param fd: If given, write the output also to the file. See also :func:`MatrixTestRunner.run() <MatrixTest.MatrixTestRunner.MatrixTestRunner.run>`.
:return:
"""
print("INFO: "... | 48,306 |
def reissueMissingJobs(updatedJobFiles, jobBatcher, batchSystem,
childJobFileToParentJob, childCounts, config,
killAfterNTimesMissing=3):
"""Check all the current job ids are in the list of currently running batch system jobs.
If a job is missing, we mark it as so, ... | 48,307 |
def all_children(wid):
"""Return all children of a widget."""
_list = wid.winfo_children()
for item in _list:
if item.winfo_children():
_list.extend(item.winfo_children())
return _list | 48,308 |
def test_OMMBIP():
"""
test OMMBIP (OpenMMBaseIntegratorPropagator) in the baoab regime on the harmonic test system;
specifically, we validate the init, apply, _get_global_integrator_variables, _get_context_parameters methods.
For the sake of testing all of the internal methods, we equip an OMMLI in... | 48,309 |
def logout():
"""------------- Log out -----------------------"""
# remove user session cookies
flash("You Have Been Logged Out")
session.pop("user")
return redirect(url_for("login")) | 48,310 |
def add_num(*args, **kwargs):
"""
Adds all arguments as numbers of type int or float. Prints results to stdout.
You have to specify "type=int" or "type=float" as last argument.
"""
t = globals()['__builtins__'][kwargs['type']]
print(sum(map(t, args))) | 48,311 |
def listtodict(l: ty.Sequence) -> ty.Mapping:
"""Converts list to dictionary"""
return dict(zip(l[::2], l[1::2])) | 48,312 |
def sqrtspace(a, b, n_points):
"""
:return: Distribute n_points quadratically from point a to point b, inclusive
"""
return np.linspace(0, 1, n_points)**2*(b-a)+a | 48,313 |
def tstr2iso(input_string: str) -> datetime:
"""
Convert a specific type of ISO string that are compliant with file pathing requirement to ISO datetime.
:return:
"""
no_colon_input_string = input_string.replace(":", "")
iso_datetime = tstr2iso_nocolon(no_colon_input_string)
return iso_dateti... | 48,314 |
def test_processing_hooks_are_inherited():
"""Processing hooks are inherited from base classes if missing.
"""
class TestView(DummyBase):
def __call__(self, *args, **kwargs):
return self.count
testview = create_view(TestView)
assert [testview(), testview(), testview()] == ... | 48,315 |
def main():
"""Main program.
"""
import argparse
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--force', action='store_true',
help='Run calib processes even if files already exist?')
parser.add_argument('--ccds', help='Set ccds.fits file to load... | 48,316 |
def _draw_colorbar(fig, mmimap, tdict):
"""Draw an MMI colorbar in a separate axis from the map.
Args:
fig (Figure): Matplotlib Figure object.
mmimap (ColorPalette): Impactutils MMI ColorPalette instance.
tdict (dict): Dictionary containing the text strings in the user's
cho... | 48,317 |
def lesson(request, order, slug):
"""
One lesson can be viewed in two different ways:
(1) as independent lesson
(2) as part of one course
As (1) it is well, independent. And it is not really
important to jump to next in order lesson or not.
It is more important in this conetxt to d... | 48,318 |
def test_paragraph_series_n_bq_t_nl_bq_fb_nl_without_bq():
"""
Test case: Block quote, text, newline, block quote, fenced block with newlines
not prefaced by block quotes
"""
# Arrange
source_markdown = """> uvw
> ```
> def
> ```"""
expected_tokens = [
"[block-quote(1... | 48,319 |
def getNum(n, res_num):
"""TODO: docstring"""
res, num = res_num
try:
idx = res.index(n)
return num[idx]
except ValueError:
raise ValueError(f'{n} is not in a list of residues!') | 48,320 |
def _run_prospector(filename,
stamp_file_name,
disabled_linters,
show_lint_files):
"""Run prospector."""
linter_tools = [
"pep257",
"pep8",
"pyflakes"
]
if can_run_pylint():
linter_tools.append("pylint")
# ... | 48,321 |
def dEuler212(q, w):
"""
dEuler212(Q,W)
dq = dEuler212(Q,W) returns the (2-1-2) euler angle derivative
vector for a given (2-1-2) euler angle vector Q and body
angular velocity vector w.
dQ/dt = [B(Q)] w
"""
return np.dot(BmatEuler212(q), w) | 48,322 |
def with_zero_out_padding_outputs(
graph_net: Callable[[gn_graph.GraphsTuple], gn_graph.GraphsTuple]
) -> Callable[[gn_graph.GraphsTuple], gn_graph.GraphsTuple]:
"""A wrapper for graph to graph functions that zeroes padded d output values.
See `zero_out_padding` for a full explanation of the method.
Args:
... | 48,323 |
def processInlineSummaries(tree, paths):
"""Move inline documentation to .summary subpaths.
The nodes matching the values in path are such that inline values are moved
to .summary subnodes for greater consistency and lower variance.
E.g. the following:
.Function.f.param.x:This is param x.
... | 48,324 |
def write_file(dict_data, csv_file):
"""
Writes a list of dictionaries to csv file.
Parameters:
dict_data: list of dictionaries
csv_file: file name to write to
"""
try:
with open(csv_file, 'w') as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=dict_data[0].keys())
for data in dict_data:
wri... | 48,325 |
def as_bytes(x) -> bytes:
"""Convert a value to bytes by converting it to string and encoding in utf8."""
if _is_bytes(x):
return bytes(x)
if not isinstance(x, str):
x = str(x)
return x.encode('utf8') | 48,326 |
def test_move_transition_matrix() -> None:
"""It should return the move transition matrix."""
pass_id = spadl.config.actiontypes.index("pass")
success_id = spadl.config.results.index("success")
spadl_actions = pd.DataFrame(
[
{
"start_x": 10.0,
"end_x"... | 48,327 |
def getGeneCount(person, geneSetDictionary):
"""
determines how many genes a person is assumed to have based upon the query information provided
"""
if person in geneSetDictionary["no_genes"]:
gene_count = 0
elif person in geneSetDictionary["one_gene"]:
gene_count = 1
else:
... | 48,328 |
def merge_json(*args):
"""
Take a list of json files and merges them together
Input: list of json file
Output: dictionary of merged json
"""
json_out = dict()
for json_file in args:
try:
if isinstance(json_file, dict):
json_out = {**json_out, **json_file... | 48,329 |
def hamming_test():
"""Algorithm was verified with this simple test."""
test_data = bytearray(256)
for index in range(128):
test_data[index] = index
for index in range(128):
test_data[index + 128] = 128 - index
hamming_code = hamming_compute_256(test_data)
print(
"Hammin... | 48,330 |
def check_validation_error(exc_info, expected_msg: str,
index: int = 0):
"""Check ValidationError instance for expected message.
:param ExceptionInfo exc_info: ValidationError instance raised and captured
by pytest.
:param str expected_msg: message expected to be provided by e... | 48,331 |
def TestGroupAddWithOptions():
"""gnt-group add with options"""
(group1, ) = qa_utils.GetNonexistentGroups(1)
AssertCommand(["gnt-group", "add", "--alloc-policy", "notvalid", group1],
fail=True)
AssertCommand(["gnt-group", "add", "--alloc-policy", "last_resort",
"--node-parame... | 48,332 |
def hyp2f1_small_argument(a, b, c, z, name=None):
"""Compute the Hypergeometric function 2f1(a, b, c, z) when |z| <= 1.
Given `a, b, c` and `z`, compute Gauss' Hypergeometric Function, specified
by the series:
`1 + (a * b/c) * z + (a * (a + 1) * b * (b + 1) / ((c * (c + 1)) * z**2 / 2 +
... (a)_n * (b)_n / ... | 48,333 |
def test_isotopequantity_eq(iq):
"""Test IsotopeQuantity equality magic method"""
iq2 = copy.deepcopy(iq)
assert iq == iq2
dt_s = min(iq.half_life, 10 * 86400)
date = iq.ref_date + datetime.timedelta(seconds=dt_s)
iq3 = IsotopeQuantity(iq.isotope, date=date, atoms=iq.atoms_at(date))
assert... | 48,334 |
def get_KPP_PL_tag(last_tag, tag_prefix='T'):
""" Get the next P/L tag in a format T??? """
assert (len(last_tag) == 4), "Tag must be 4 characers long! (e.g. T???)"
last_tag_num = int(last_tag[1:])
return '{}{:0>3}'.format(tag_prefix, last_tag_num+1) | 48,335 |
def update(isamAppliance, description, properties, check_mode=False, force=False):
"""
Update a specified Attribute Matcher
"""
id, update_required, json_data = _check(isamAppliance, description, properties)
if id is None:
from ibmsecurity.appliance.ibmappliance import IBMError
... | 48,336 |
def name_has_image_suffix(fname):
"""Test whether file fname has an image suffix in the allowed list."""
extension = os.path.splitext(fname)[1]
return extension in allowed_image_file_suffixes | 48,337 |
def get_all_themes(config, brand_id):
"""
Get all themes for the given brand id.
:param config: context config
:param brand_id: the brand id for the relevant help center
:return list: list of all themes
"""
url = f"https://{config['subdomain']}.zendesk.com/api/guide/theming/{brand_id}/themes... | 48,338 |
def maximum_radius_test(gpu_memory=None, number_of_gpu=None):
"""
:return:
"""
if gpu_memory is None and number_of_gpu is None:
gpu_memory, number_of_gpu = tfu.client.read_gpu_memory()
logging.info('GPU Memory={:.2f} Number of GPU={}'.format(gpu_memory, number_of_gpu))
if 10 <= gpu_memor... | 48,339 |
def entry_point(result_location, output_file, chunks_file, chunk_ids):
"""Method to complete: you have to raise an exception if an error occured in the program.
Given a list of chunk ids, merges all the chunks system output present in the list.
Args:
result_location (str): Path to get the result o... | 48,340 |
def get_module(value, signature):
"""
Creates a module for value, in order to do the type checking.
"""
from vistrails.core.modules.basic_modules import Boolean, String, Integer, Float, List
if isinstance(value, Constant):
return type(value)
elif isinstance(value, bool):
return... | 48,341 |
def ValidateUpdateInstancesArgs(args):
"""Validates update arguments provided by the user.
Args:
args: arguments provided by the user.
"""
if args.action == 'restart':
if args.version_original:
raise exceptions.InvalidArgumentException(
'--version-original', 'can\'t be specified for --a... | 48,342 |
def tca_plus(source, target):
"""
TCA: Transfer Component Analysis
:param source:
:param target:
:param n_rep: number of repeats
:return: result
"""
result = dict()
metric = 'process'
for src_name in source:
try:
stats = []
val = []
src... | 48,343 |
async def open_oco_orders(recv_window):
"""
Weight: 2
"""
payload = {
'recvWindow': recv_window,
'timestamp': get_timestamp()
}
builder = Builder(endpoint='api/v3/openOrderList', payload=payload).set_security()
await builder.send_http_req()
builder.handle_response().ge... | 48,344 |
def reinitialize(
pool_allocator=False,
managed_memory=False,
initial_pool_size=None,
maximum_pool_size=None,
devices=0,
logging=False,
log_file_name=None,
):
"""
Finalizes and then initializes RMM using the options passed. Using memory
from a previous initialization of RMM is un... | 48,345 |
def local_2d_self_attention_spatial_blocks(query_antecedent,
kv_channels,
heads,
memory_h_dim=None,
memory_w_dim=None,
... | 48,346 |
def polling_locations_import_from_structured_json(structured_json):
"""
This pathway in requires a we_vote_id, and is not used when we import from Google Civic
:param structured_json:
:return:
"""
polling_location_manager = PollingLocationManager()
polling_locations_saved = 0
polling_loc... | 48,347 |
def add_model_architecture_args(parser: argparse.PARSER, model='vae', nlayers=3, depth=3, N=32):
"""Arguments defining the model architecture"""
parser.add_argument('--model', default=model,
help='[vae, conv-vae, gmm, gaussian-toy, sbm, gaussian-vae]')
parser.add_argument('--hdim', d... | 48,348 |
def _mgSeqIdToTaxonId(seqId):
"""
Extracts a taxonId from sequence id used in the Amphora or Silva mg databases (ends with '|ncbid:taxonId")
@param seqId: sequence id used in mg databases
@return: taxonId
@rtype: int
"""
return int(seqId.rsplit('|', 1)[1].rsplit(':', 1)[... | 48,349 |
def _convert_dict_to_xml_recurse(parent, dictitem, listnames):
"""Helper Function for XML conversion."""
# we can't convert bare lists
assert not isinstance(dictitem, list)
if isinstance(dictitem, dict):
for (tag, child) in sorted(dictitem.iteritems()):
if isinstance(child, list):
... | 48,350 |
def has_progress(toppath):
"""Return `True` if there exist paths that have already been
imported under `toppath`.
"""
with progress_state() as state:
return len(state[toppath]) != 0 | 48,351 |
def show_stats() -> None:
"""
stats.provider.exから過去(デフォルト1時間)の収益データを得て
1日あたりの収益量を計算し表示
"""
PERIOD = 1 # hour
userdata = get_userdata(("addr",))
params = {
"method": "stats.provider.ex",
"addr": userdata["addr"],
"from": int(time.time())-(3600*PERIOD+300)
}
... | 48,352 |
def run_both_transfers(model: BiVAE, *args, **kwargs):
"""
Run both content-transfer and style-transfer on the each pair of the content-representative tensor images
:param model: Trained BiVAE model
:param class_reps: a dictionary of string class_id <-> a single 3dim Tensor (C,H,W)
:param log_dir: P... | 48,353 |
def se_mobilenet_075():
"""
Construct SE_MobileNet.
"""
model = SE_MobileNet(widen_factor=0.75, num_classes=1000)
return model | 48,354 |
def canonicalize_lookup_info(
lookup: SshPubKeyLookupInfo,
ssh_auth_dir_root: Path,
template_vars: SshPubKeyFileTemplateVars
) -> SshPubKeyLookupInfo:
"""Expand the template variables and ensure that paths are made absolute.
"""
ad_root = ssh_auth_dir_root
expd = expand_file_template_vars
... | 48,355 |
def test_has_object_destroy_permission_other(
mock_parent_permission, api_rf, entry_comment_factory
):
"""
The permissions required to destroy a comment on a journal entry
should be equivalent to those required to write to a journal entry.
"""
comment = entry_comment_factory()
request = api_... | 48,356 |
def combination_preview(bg_conf: Dict, dyn_conf: Dict, sta_confs: Dict) -> None:
"""
image preview using matplotlib
:param bg_conf: background component configuration
:param dyn_conf: dynamic component configuration
:param sta_confs: static component configurations list
:return: None
"""
... | 48,357 |
def compare_gathers(first, second, drop_cols=None, check_types=False, same_survey=True):
"""compare_gathers"""
first_attrs = first.__dict__
second_attrs = second.__dict__
assert len(set(first_attrs) & set(second_attrs)) == len(first_attrs)
first_headers = first.headers.reset_index()
second_hea... | 48,358 |
def reprojection_rms(impoints_known, impoints_reprojected):
"""
Compute root mean square (RMS) error of points
reprojection (cv2.projectPoints).
Both input NumPy arrays should be of shape (n_points, 2)
"""
diff = impoints_known - impoints_reprojected
squared_distances = np.sum(np.square(d... | 48,359 |
def macro_accuracy_one_sub(**kwargs: dict) -> bool:
"""
Calculates whether the predicted output, after the postprocessing step of
selecting the single most 'changed' substation has been applied, wholly
matches the true output.
Differs from micro_accuracy_one_sub in that it doesn't check the
elem... | 48,360 |
def main(argv):
"""Download utility to simplify the download of USPTO patent data
USPTO patent applications are currently hosted by Google. In most cases, you
will be interested in all patents from a specific year or which lie in a
relevant period of time. Since downloading each compressed file separately
is... | 48,361 |
def modified_euler(f, y0, t0, t1, n):
""" Use the modified Euler method to compute an approximate solution
to the ODE y' = f(t, y) at n equispaced parameter values from t0 to t1
with initial conditions y(t0) = y0.
y0 is assumed to be either a constant or a one-dimensional numpy array.
t and t0 ... | 48,362 |
def attack_trace_set(trace_set, result, conf=None, params=None):
"""
Perform CPA attack on a trace set using correlation as a metric. Assumes the traces in trace_set are real signals.
"""
# Init on first call. Use correlations as the score.
if result.guess_sample_score_matrix is None:
result... | 48,363 |
def read_tree(sha1=None, data=None):
"""Read tree object with given SHA-1 (hex string) or data, and return list
of (mode, path, sha1) tuples.
"""
if sha1 is not None:
obj_type, data = read_object(sha1)
assert obj_type == 'tree'
elif data is None:
raise TypeError('must specify... | 48,364 |
def cluster(T, m):
"""
Runs PCCA++ [1] to compute a metastable decomposition of MSM states.
(i.e. find clusters using transition matrix and PCCA)
Parameters
----------
T: a probability transition matrix.
m : Desired number of metastable sets (int).
Notes
-----
The metastable de... | 48,365 |
def fine_tune_class_vector(nr_class, *, exclusive_classes=True, **cfg):
"""Select features from the class-vectors from the last hidden state,
softmax them, and then mean-pool them to produce one feature per vector.
The gradients of the class vectors are incremented in the backward pass,
to allow fine-tu... | 48,366 |
def _recommend_aals_annoy(est, userid, R, n, filter_items,
recalculate_user, filter_previously_rated,
return_scores, recommend_function,
scaling_function, *args, **kwargs):
"""Produce recommendations for Annoy and NMS ALS algorithms"""
... | 48,367 |
def url_to_filename(url):
"""Converts a URL to a valid filename."""
return url.replace('/', '_') | 48,368 |
def _parallel_dict_from_expr_if_gens(exprs, opt):
"""Transform expressions into a multinomial form given generators."""
indices = {g: i for i, g in enumerate(opt.gens)}
zero_monom = [0]*len(opt.gens)
polys = []
for expr in exprs:
poly = {}
for term in Add.make_args(expr):
... | 48,369 |
def main():
"""
Main loop
"""
newlines = []
ifile = get_cli_params()
lines = read_file(ifile)
for line in lines:
# remove any leading or trailing whitespace and convert to lowercase
s = line.strip().lower()
# check if there is something left
if len(s) > 0:
... | 48,370 |
def getMObjectHandle(value):
"""
Method used to get an MObjectHandle from any given value.
:type value: Union[str, om.MObject, om.MObjectHandle, om.MDagPath]
:rtype: om.MObjectHandle
"""
# Check for redundancy
#
if isinstance(value, om.MObjectHandle):
return value
else:
... | 48,371 |
def test_for_loop_v2(parser):
"""Tests parsing of for-loop without initialization."""
code = """
int main(int argc, const char **argv){
int i = 0;
for(; i < 10; i++) {
}
}
"""
parser.parse(code) | 48,372 |
def create_solution(solution, translation, master, upload):
"""Create final solution csv file."""
solution = pd.read_csv(solution)
translation = pd.read_csv(
translation, sep='\t', header=None, names=['basename', 'new_name'])
basename = solution['filename'].apply(os.path.basename)
solution =... | 48,373 |
def remove_dupes(inds1, inds2, inds3=None, inds4=None, tol=1e-6):
"""
Remove duplicates so as to not brake the interpolator.
Parameters
----------
inds1, inds2, inds3 : list or np.array()
to find unique values, must be same length
just_two : Bool [False]
do not include inds3
... | 48,374 |
def try_to_create_directory(directory_path):
"""Attempt to create a directory that is globally readable/writable.
Args:
directory_path: The path of the directory to create.
"""
if not os.path.exists(directory_path):
try:
os.makedirs(directory_path)
except OSError as ... | 48,375 |
def filter_punctuation(fst: 'pynini.FstLike') -> 'pynini.FstLike':
"""
Helper function for parsing number strings. Converts common cardinal strings (groups of three digits delineated by 'cardinal_separator' - see graph_utils)
and converts to a string of digits:
"1 000" -> "1000"
"1.000.000" ... | 48,376 |
def block(bot, update, args):
"""Get information on the block"""
bot.send_message(
chat_id=update.message.chat_id,
parse_mode=telegram.ParseMode.MARKDOWN,
text=_block_view(' '.join(args))
) | 48,377 |
def pixbuf2image(pix):
"""Convert gdkpixbuf to PIL image"""
data = pix.get_pixels()
w = pix.props.width
h = pix.props.height
stride = pix.props.rowstride
mode = "RGB"
if pix.props.has_alpha == True:
mode = "RGBA"
im = Image.frombytes(mode, (w, h), data, "raw", mode, stride)
r... | 48,378 |
def to_edges(l):
"""
treat `l` as a Graph and returns it's edges
to_edges(['a','b','c','d']) -> [(a,b), (b,c),(c,d)]
"""
it = iter(l)
last = next(it)
for current in it:
yield last, current
last = current | 48,379 |
def save(volume, path, interactive):
"""Save your docker volume locally."""
exporting_time = str(datetime.datetime.now().strftime("%Y-%m-%d_%H%M%S"))
filename = volume + "_" + exporting_time + ".tar.gz"
save_cmd = utils.save_cmd.format(volume, path, filename)
if not utils.docker_volume_exist(volum... | 48,380 |
def setup_s3_client(job_data):
"""Creates an S3 client
Uses the credentials passed in the event by CodePipeline. These
credentials can be used to access the artifact bucket.
Args:
job_data: The job data structure
Returns:
An S3 client with the appropriate... | 48,381 |
def verbose_popen(cmd):
"""Run a command with streaming output.
Args:
cmd (str): A command to run with popen.
Raises:
CalledProcessError: If the returncode is not 0.
"""
proc = subprocess.Popen(shlex.split(cmd))
proc.wait()
if proc.returncode != 0:
raise subprocess... | 48,382 |
async def get_subscriptions_handler(request: Request) -> data.SubscriptionsListResponse:
"""
Get user's subscriptions.
"""
token = request.state.token
params = {
"type": BUGOUT_RESOURCE_TYPE_SUBSCRIPTION,
"user_id": str(request.state.user.id),
}
try:
resources: Bugout... | 48,383 |
def unique_doc_key(doc):
"""
Creates a key that allows to check for record uniqueness
"""
keyparts = [doc['type']]
for attr in ('level', 'country', 'state', 'region', 'district', 'city'):
if attr in doc:
keyparts.append(doc[attr])
key = json.dumps(keyparts)
return key | 48,384 |
def parse_tag(vt):
"""
Get a VTag from a label
Parameters
----------
vt : str
A label that we want to get the VTag
Raises
------
UnknownTypeError
If the label is not known in VTag
"""
vt = vt.strip()
if vt == "C":
return TAG_CRITICAL
if vt == "L"... | 48,385 |
def fetch_stock_revive_info(start_date: date = None, end_date: date = None, retry: int = 10) -> list:
"""
歷年上櫃減資資訊資料表
輸出格式: [{'code': '4153', 'name': '鈺緯', 'revive_date': date(2020-10-19), 'old_price': 27.20, 'new_price': 30.62}]
"""
result = []
if not start_date:
start_date = date(2013,... | 48,386 |
def _read_one(stream: BytesIO) -> int:
"""
Read 1 byte, converting it into an int
"""
c = stream.read(1)
if c == b"":
raise EOFError("Unexpected EOF while reading bytes")
return ord(c) | 48,387 |
def new_thread_mails(post, users_and_watches):
"""Return an interable of EmailMessages to send when a new thread is
created."""
c = {'post': post.content,
'post_html': post.content_parsed,
'author': post.creator.username,
'host': Site.objects.get_current().domain,
'thread... | 48,388 |
def known(words):
"""The subset of `words` that appear in the dictionary of WORDS."""
return set(w for w in words if w in WORDS) | 48,389 |
def load_transform_data(human_dataset, bot_dataset, drop_features, bins, logger, **kwargs):
"""
Load and preprocess data, returning the examples and labels as numpy.
"""
# Load data for humans.
df1 = pd.read_csv(human_dataset)
df1 = df1.drop("screen_name", axis=1) # remove screen_name column
... | 48,390 |
def latest():
"""
Latest route returns latest performed searches.
"""
return jsonify(get_latest_searches()) | 48,391 |
def extract_zip(inzip: str, path: str) -> List[str]:
"""
Extract content of a zipfile inside a given directory.
Parameters:
===========
inzip: str
Input zip file.
path: str
Output path.
Returns:
========
namelist: List
List of files extracted from the zip.
... | 48,392 |
def actions(board):
"""
Returns set of all possible actions (i, j) available on the board.
"""
PossActions = []
# Find empty positions
for i in range(3):
for j in range(3):
if(board[i][j] == EMPTY):
PossActions.append((i,j))
return Po... | 48,393 |
def getCity(html):
"""This function uses the ``html`` passed to it as a string to extract, parse and return a City object
Parameters
----------
html : str
the html returned when a get request to view the city is made. This request can be made with the following statement: ``s.get(urlCiudad + id)``, where urlCiuda... | 48,394 |
def test04():
"""
add another container
"""
assert isinstance(p, Pod)
assert p.spec.containers[1].name == "db" | 48,395 |
def server_hostname(config):
"""
Reads the ambari server name from the config or using the supplied script
"""
global cached_server_hostname
if cached_server_hostname is not None:
return cached_server_hostname
if config.has_option('server', 'hostname_script'):
scriptname = config.get('server', 'hos... | 48,396 |
def remove_axis_listener(listener):
"""Removes the specified axis listener."""
_axis_listeners.discard(listener) | 48,397 |
def test_query_topics_by_pattern(volttron_instance, influxdb_client):
"""
Test basic functionality of query_topics_by_pattern method in InfluxdbHistorian.
Inserts a specific number of data and call ``get_topics_by_pattern`` method
through a new built agent. The format of a query for regex pattern is:
... | 48,398 |
def print_val(values, length=4):
"""Basic function to print out the values in a 'grid'.
Args:
values ([type]): The rewards
length (int, optional): Lenght of grid. Defaults to 4.
"""
for i in range(len(values) // length):
sub_list = values[i * length:(i + 1) * length]
pri... | 48,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.