content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def is_coroutine_generator(obj):
"""
Returns whether the given `obj` is a coroutine generator created by an `async def` function, and can be used inside
of an `async for` loop.
Returns
-------
is_coroutine_generator : `bool`
"""
if isinstance(obj, AsyncGeneratorType):
code =... | 4,500 |
def get_scheme(scheme_id):
"""
Retrieve the scheme dict identified by the supplied scheme ID
Returns: An scheme dict
"""
for node in sd["nodes"]:
if scheme_id == node["id"]:
return node | 4,501 |
def compute_vtable(cls: ClassIR) -> None:
"""Compute the vtable structure for a class."""
if cls.vtable is not None: return
if not cls.is_generated:
cls.has_dict = any(x.inherits_python for x in cls.mro)
for t in cls.mro[1:]:
# Make sure all ancestors are processed first
comput... | 4,502 |
def Axicon(phi, n1, x_shift, y_shift, Fin):
"""
Fout = Axicon(phi, n1, x_shift, y_shift, Fin)
:ref:`Propagates the field through an axicon. <Axicon>`
Args::
phi: top angle of the axicon in radians
n1: refractive index of the axicon material
x_shift, y_shift: shift from ... | 4,503 |
def addrAndNameToURI(addr, sname):
"""addrAndNameToURI(addr, sname) -> URI
Create a valid corbaname URI from an address string and a stringified name"""
# *** Note that this function does not properly check the address
# string. It should raise InvalidAddress if the address looks
# invalid.
impor... | 4,504 |
def blkdev_uname_to_taptype(uname):
"""Take a blkdev uname and return the blktap type."""
return parse_uname(uname)[1] | 4,505 |
def _write_ldif(lines, dn, keytab, admin_principal):
"""Issue an update to LDAP via ldapmodify in the form of lines of an LDIF
file.
:param lines: ldif file as a sequence of lines
"""
cmd = 'kinit -t {keytab} {principal} ldapmodify'.format(
keytab=keytab,
principal=admin_principal,... | 4,506 |
def detection_layer(inputs, n_classes, anchors, img_size, data_format):
"""Creates Yolo final detection layer.
Detects boxes with respect to anchors.
Args:
inputs: Tensor input.
n_classes: Number of labels.
anchors: A list of anchor sizes.
img_size: The input size of the mo... | 4,507 |
def main():
"""
Prepares an :obj:`~PyQt5.QtWidgets.QApplication` instance and starts the
*GuiPy* application.
"""
# Obtain application instance
qapp = QW.QApplication.instance()
# If qapp is None, create a new one
if qapp is None:
QW.QApplication.setAttribute(QC.Qt.AA_EnableHi... | 4,508 |
def create_position_tear_sheet(returns, positions,
show_and_plot_top_pos=2, hide_positions=False,
sector_mappings=None, transactions=None,
estimate_intraday='infer', return_fig=False):
"""
Generate a number of plots for... | 4,509 |
def statement_view(request, statement_id=None):
"""Send a CSV version of the statement with the given
``statement_id`` to the user's browser.
"""
statement = get_object_or_404(
Statement, pk=statement_id, account__user=request.user)
response = HttpResponse(mimetype='text/csv')
filena... | 4,510 |
def get_proton_gamma(energy):
"""Returns relativistic gamma for protons."""
return energy / PROTON_MASS | 4,511 |
def test_login_and_authenticated(server):
"""
Whitebox test. Check the internal client variables are being set on login.
"""
add_mock_user(server, 'u1', 'password')
# Before Login
with server.application.test_request_context('/'):
user = server.application.restful_auth.storage.get_client... | 4,512 |
def generate_heatmap_cube(locus_generator, overlap_df, snp_df, peak_df, heatmap_folder, color_scheme, specific_locus=None, show_plots=True):
"""
This function is under maintence as in I ran out of time to finish this. Nevertheless.
the goal of this function is to show a 3D version of the overlap memberships... | 4,513 |
def demandNameItem(listDb,phrase2,mot):
"""
put database name of all items in string to insert in database
listDb: list with datbase name of all items
phrase2: string with database name of all items
mot: database name of an item
return a string with database name of all items separated with ','
... | 4,514 |
def escape_yaml(data: str) -> str:
"""
Jinja2 фильтр для экранирования строк в yaml
экранирует `$`
"""
return data.replace("$", "$$") | 4,515 |
def test_empty_result():
"""Test the client when POST to tefas returns empty list"""
Crawler._do_post = MagicMock(return_value=[])
crawler = Crawler()
crawler.fetch(start="2020-11-20") | 4,516 |
def stokes_linear(theta):
"""Stokes vector for light polarized at angle theta from the horizontal plane."""
if np.isscalar(theta):
return np.array([1, np.cos(2*theta), np.sin(2*theta), 0])
theta = np.asarray(theta)
return np.array([np.ones_like(theta),
np.cos(2*theta),
... | 4,517 |
def validate_item_field(attr_value, attr_form):
"""
:param attr_value: item的属性
:param attr_form: item category的属性规则
:return:
"""
if not isinstance(attr_form, dict):
return -1, {"error": "attr_form is not a dict."}
required = attr_form.get('required')
if required == 'false':
... | 4,518 |
def display_instances(image, boxes, masks, ids, names, scores):
"""
take the image and results and apply the mask, box, and Label
"""
n_instances = boxes.shape[0]
colors = random_colors(n_instances)
if not n_instances:
print('NO INSTANCES TO DISPLAY')
else:
assert boxes.... | 4,519 |
def run():
"""
Run game.
"""
words = load_words(WORDFILE)
wrangler = provided.WordWrangler(words, remove_duplicates,
intersect, merge_sort,
gen_all_strings)
provided.run_game(wrangler) | 4,520 |
def read_squad_examples(input_file, is_training):
"""Read a SQuAD json file into a list of SquadExample."""
with tf.io.gfile.GFile(input_file, "r") as reader:
input_data = json.load(reader)["data"]
examples = []
for entry in input_data:
for paragraph in entry["paragraphs"]:
paragraph_text = parag... | 4,521 |
def load_gamma_telescope():
"""https://archive.ics.uci.edu/ml/datasets/MAGIC+Gamma+Telescope"""
url='https://archive.ics.uci.edu/ml/machine-learning-databases/magic/magic04.data'
filepath = os.path.join(get_data_dir(), "magic04.data")
maybe_download(filepath, url)
data = pd.read_csv(filepath)
da... | 4,522 |
def qarange(start, end, step):
"""
Convert the cyclic measurement and control data into the required array
:param start:
:param end:
:param step:
:return: np.array
"""
if Decimal(str(end)) - Decimal(str(start)) < Decimal(str(step)) or step == 0:
return [start]
start... | 4,523 |
def checkFull(t, e, maxval, minval):
"""Check the maximum and minimum bounds for the type given by e"""
checkType(t, e, maxval, 1)
checkType(t, e, minval, -1) | 4,524 |
def get_default_render_layer():
"""Returns the default render layer
:return:
"""
return pm.ls(type='renderLayer')[0].defaultRenderLayer() | 4,525 |
def translation(shift):
"""Translation Matrix for 2D"""
return np.asarray(planar.Affine.translation(shift)).reshape(3, 3) | 4,526 |
def pad(adjacency_matrices, size):
"""Pads adjacency matricies to the desired size
This will pad the adjacency matricies to the specified size, appending
zeros as required. The output adjacency matricies will all be of size
'size' x 'size'.
Args:
adjacency_matrices: The input list of adjac... | 4,527 |
def test_merge_configuration():
""" Test merging two simple configurations works as expected. """
one = {"alpha": [0, 1], BernoulliNB: {"fit_prior": [True, False]}}
two = {"alpha": [0, 2], GaussianNB: {"fit_prior": [True, False]}}
expected_merged = {
"alpha": [0, 1, 2],
GaussianNB: {"fi... | 4,528 |
def test_launch_with_longer_multiword_domain_name() -> None:
"""This test is important because we want to make it convenient for users to launch nodes with
an arbitrary number of words."""
# COMMAND: "hagrid launch United Nations"
args: List[str] = ["United", "States", "of", "America"]
verb = cli.... | 4,529 |
def mapping_activities_from_log(log, name_of_activity):
"""
Returns mapping activities of activities.
:param name_of_activity:
:param log:
:return: mapping
"""
mapping_activities = dict()
unique_activities = unique_activities_from_log(log, name_of_activity)
for index, activity in e... | 4,530 |
def bubble_sort(nums) -> List[int]:
"""Sorts numbers from in ascending order.
It is:
- quadratic time
- constant space
- stable
- iterative
- mutative
- internal algorithm
"""
# TODO: implement the algorithm!
pass | 4,531 |
def pad(x, paddings, axes=None):
"""
Pads a tensor with zeroes along each of its dimensions.
TODO: clean up slice / unslice used here
Arguments:
x: the tensor to be padded
paddings: the length of the padding along each dimension.
should be an array with the same length as x.axes.
... | 4,532 |
def labels_to_1hotmatrix(labels, dtype=int):
"""
Maps restricted growth string to a one-hot flag matrix. The input and
the output are equivalent representations of a partition of a set of
n elelements.
labels: restricted growth string: n-vector with entries in {0,...,n-1}.
The fi... | 4,533 |
def model_counter_increment(instance):
"""Word Count map function."""
instance.counter += 1
instance.save()
yield (instance.pk, "{0}".format(instance.counter)) | 4,534 |
def gen_cues_adp(model_type, thresh, batch_size, size, cues_dir, set_name, is_verbose):
"""Generate weak segmentation cues for ADP (helper function)
Parameters
----------
model_type : str
The name of the model to use for generating cues (i.e. 'M1', 'M2', 'M3', 'M4', 'M5', 'M6', 'M7', 'X1.7', 'M... | 4,535 |
def recall(logits, target, topk=[1,5,10], typeN=8):
"""Compute top K recalls of a batch.
Args:
logits (B x max_entities, B x max_entities x max_rois):
target (B x max_entities, B x max_entities x max_rois):
topk: top k recalls to compute
Returns:
N: number of entities i... | 4,536 |
def n(request) -> int:
"""A test fixture enumerate values for `n`."""
return request.param | 4,537 |
def create_color_lot(x_tick_labels, y_tick_labels, data, xlabel, ylabel, colorlabel, title):
"""
Generate 2D plot for the given data and labels
"""
fig, ax = plot.subplots()
heatmap = ax.pcolor(data)
colorbar = plot.colorbar(heatmap)
colorbar.set_label(colorlabel, rotation=90)
... | 4,538 |
def decode(ciphered_text):
"""
Decodes the ciphered text into human readable text.
Returns a string.
"""
text = ciphered_text.replace(' ', '') # We remove all whitespaces
return ''.join([decode_map[x] if decode_map.get(x) else x for x in text]) | 4,539 |
def _collect_fields(resource):
"""Collect fields from the JSON.
:param resource: ResourceBase or CompositeField instance.
:returns: generator of tuples (key, field)
"""
for attr in dir(resource.__class__):
field = getattr(resource.__class__, attr)
if isinstance(field, Field):
... | 4,540 |
def parse(s):
""" Date parsing tool.
Change the formats here cause a changement in the whole application.
"""
formats = ['%Y-%m-%dT%H:%M:%S.%fZ','%d/%m/%Y %H:%M:%S','%d/%m/%Y%H:%M:%S', '%d/%m/%Y','%H:%M:%S']
d = None
for format in formats:
try:
d = datetime.strptime(s, fo... | 4,541 |
def openstack(request):
""" Context processor necessary for OpenStack Dashboard functionality.
The following variables are added to the request context:
``authorized_tenants``
A list of tenant objects which the current user has access to.
``regions``
A dictionary containing informati... | 4,542 |
def get_align_mismatch_pairs(align, ref_genome_dict=None) -> list:
"""input a pysam AlignedSegment object
Args:
align (pysam.AlignedSeqment object): pysam.AlignedSeqment object
ref_genome_dict (dict, optional): returned dict from load_reference_fasta_as_dict(). Defaults to None.
Returns:
... | 4,543 |
def get_int(name, default=None):
"""
:type name: str
:type default: int
:rtype: int
"""
return int(get_parameter(name, default)) | 4,544 |
def display_instances(image, boxes, masks, keypoints, class_id=1, class_name='person',
scores=None, title="",
figsize=(16, 16), ax=None,
show_mask=True, show_bbox=True,
show_keypoint=True,
colors=None, captions... | 4,545 |
def run_test(series: pd.Series, randtest_name, **kwargs) -> TestResult:
"""Run a statistical test on RNG output
Parameters
----------
series : ``Series``
Output of the RNG being tested
randtest_name : ``str``
Name of statistical test
**kwargs
Keyword arguments to pass to... | 4,546 |
def radians(x):
"""
Convert degrees to radians
"""
if isinstance(x, UncertainFunction):
mcpts = np.radians(x._mcpts)
return UncertainFunction(mcpts)
else:
return np.radians(x) | 4,547 |
def screen_poisson_objective(pp_image, hp_w,hp_b, data):
"""Objective function."""
return (stencil_residual(pp_image, hp_w,hp_b, data) ** 2).sum() | 4,548 |
def remove_auto_shutdown_jobs():
"""
clears the job scheduler off auto shutdown jobs
"""
jobs = schedule.get_jobs("auto_off")
if jobs:
#print(jobs)
schedule.clear("auto_off")
#print("auto shutdown cancelled") | 4,549 |
async def test_no_port(event_loop, test_log, mock_server_command):
"""Check that process that didn't bind any endpoints is handled correctly.
"""
# Case 1: process didn't bind an endpoint in time.
PORT_TIMEOUT = 0.5
process = polled_process.PolledProcess(
mock_server_command(socket_count=0),... | 4,550 |
def learn(request, artwork_genre=None):
"""
Returns an art genre.
"""
_genre = get_object_or_404(Genre, slug=artwork_genre)
return render_to_response('t_learn.html',
{'genre': _genre},
context_instance=RequestContext(request)) | 4,551 |
def plot_corr_matrix(corr_dat, labels, save_out=False, fig_info=FigInfo()):
"""Plot correlation data.
Parameters
----------
corr_data : 2d array
Matrix of correlation data to plot.
labels : list of str
Labels for the rows & columns of `corr_data`.
save_out : boolean, optional (defa... | 4,552 |
def plot_column(path: str, column: str, outpath: str = ""):
"""Plot a single column and save to file."""
df = to_df(path)
col_df = df.set_index(["name", "datetime"])[column].unstack("name")
ax = col_df.plot(grid=True)
ax.set_xlabel("Time")
ax.set_ylabel(LABEL_MAP[column])
if outpath:
... | 4,553 |
def get_loader():
"""Returns torch.utils.data.DataLoader for custom Pypipes dataset. """
data_loader = None
return data_loader | 4,554 |
def attention_decoder_cell_fn(decoder_rnn_cell, memories, attention_type,
decoder_type, decoder_num_units, decoder_dropout,
mode, batch_size, beam_width=1, decoder_initial_state=None, reuse=False):
"""Create an decoder cell with attention. It takes decoder... | 4,555 |
def scan_recurse(path: PrettyPath, _resolved: ResolvedDotfilesJson) -> ActionResult:
"""Scan action: Recurse into this directory for more dotfiles.
""" | 4,556 |
def test_json_to_spark_schema_invalid(invalid_schema, missed_key):
"""json_to_spark_schema should raise KeyError for missing key."""
# Arrange & Act
with pytest.raises(KeyError) as key_error:
json_to_spark_schema(create_json_schema(invalid_schema))
# Assert
assert "Missing key: '{0}'. Valid... | 4,557 |
async def post_user_income(user: str, income: Income):
"""
This functions create a new income in the DB. It checks whether
the user exists and returns a message in case no user exists.
In the other case, creates a new document in DB with the users
new Income.
user: users uuid.
income: Incom... | 4,558 |
def process_axfr_response(origin, nameserver, owner, overwrite=False):
"""
origin: string domain name
nameserver: IP of the DNS server
"""
origin = Name((origin.rstrip('.') + '.').split('.'))
axfr_query = dns.query.xfr(nameserver, origin, timeout=5, relativize=False, lifetime=10)
try:
... | 4,559 |
def bind_rng_to_host_device(rng: jnp.ndarray,
axis_name: str,
bind_to: Optional[str] = None) -> jnp.ndarray:
"""Binds a rng to the host/device we are on.
Must be called from within a pmapped function. Note that when binding to
"device", we also bind the rng... | 4,560 |
async def snobpic(ctx):
"""command for personalised profile picture, input a color (RGB or HEX) output a reply with the profile picture"""
await snobBot.snobpic(ctx) | 4,561 |
def get_child_ids(pid, models, myself=True, ids: set = None) -> set:
"""
获取models模型的子id集合
:param pid: models模型类ID
:param models: models模型对象
:param myself: 是否包含pid
:param ids: 所有ID集合(默认为None)
:return: ids(所有ID集合)
"""
if ids is None:
ids = set()
queryset = models.objects.fi... | 4,562 |
def get_tenant_id(khoros_object, community_details=None):
"""This function retrieves the tenant ID of the environment.
.. versionadded:: 2.1.0
:param khoros_object: The core :py:class:`khoros.Khoros` object
:type khoros_object: class[khoros.Khoros]
:param community_details: Dictionary containing c... | 4,563 |
def pretty_print_output(critter, matches, contigs, pd, mc, mp):
"""Write some nice output to stdout"""
unique_matches = sum([1 for node, uce in matches.iteritems()])
out = "\t {0}: {1} ({2:.2f}%) uniques of {3} contigs, {4} dupe probe matches, " + \
"{5} UCE probes matching multiple contigs, {6}... | 4,564 |
def obfuscatable_variable(tokens, index):
"""
Given a list of *tokens* and an *index* (representing the current position),
returns the token string if it is a variable name that can be safely
obfuscated.
Returns '__skipline__' if the rest of the tokens on this line should be skipped.
Returns '_... | 4,565 |
def concat_data(labelsfile, notes_file):
"""
INPUTS:
labelsfile: sorted by hadm id, contains one label per line
notes_file: sorted by hadm id, contains one note per line
"""
with open(labelsfile, 'r') as lf:
print("CONCATENATING")
with open(notes_file, 'r') as notesfile:
... | 4,566 |
def replace_text_comment(comments, new_text):
"""Replace "# text = " comment (if any) with one using new_text instead."""
new_text = new_text.replace('\n', ' ') # newlines cannot be represented
new_text = new_text.strip(' ')
new_comments, replaced = [], False
for comment in comments:
if c... | 4,567 |
def mkSmartMask(**kwargs):
"""Routine to produce sky maps, according to defined macro-bins.
"""
logger.info('SmartMask production...')
assert(kwargs['config'].endswith('.py'))
get_var_from_file(kwargs['config'])
macro_bins = data.MACRO_BINS
mask_label = data.MASK_LABEL
in_labels_list = d... | 4,568 |
def init_show_booking_loader(response, item=None):
"""
init ShowingBookingLoader with optional ShowingBooking item
"""
loader = ShowingBookingLoader(response=response)
if item:
loader.add_value(None, item)
return loader | 4,569 |
def main(args):
"""Entry point"""
args.entry_point(args) | 4,570 |
def get_dpifac():
"""get user dpi, source: node_wrangler.py"""
prefs = bpy.context.preferences.system
return prefs.dpi * prefs.pixel_size / 72 | 4,571 |
def seq_row(
repeats: int = 1,
trigger: str = Trigger.IMMEDIATE,
position: int = 0,
half_duration: int = MIN_PULSE,
live: int = 0,
dead: int = 0,
) -> List:
"""Create a 50% duty cycle pulse with phase1 having given live/dead values"""
row = [
repeats,
trigger,
pos... | 4,572 |
def github_repos(message):
"""
リポジトリの一覧を返す
"""
text = ""
for repo in org.get_repos():
text += "- <{}|{}> {}\n".format(repo.html_url,
repo.name,
repo.description)
attachments = [{
'pretext': '{} のリポジト... | 4,573 |
def call_nelder_mead_method(
f,
verts,
x_tolerance=1e-6,
y_tolerance=1e-6,
computational_budget=1000,
f_difference=10,
calls=0,
terminate_criterion=terminate_criterion_x,
alpha=1,
gamma=2,
rho=0.5,
sigma=0.5,
values=[],
):
"""Return an approximation of a local op... | 4,574 |
def get_auth_claims_from_request(request):
"""Authenticates the request and returns claims about its authorizer.
Oppia specifically expects the request to have a Subject Identifier for the
user (Claim Name: 'sub'), and an optional custom claim for super-admin users
(Claim Name: 'role').
Args:
... | 4,575 |
def decrypt(**kwargs):
"""
Returns a CryptoResult containing decrypted bytes.
This function requires that 'data' is in the format generated by the
encrypt functionality in this SDK as well as other OCI SDKs that support
client side encryption.
Note this function cannot decrypt data encrypted b... | 4,576 |
def format_result(result: Union[Pose, PackedPose]) -> Tuple[str, Dict[Any, Any]]:
"""
:param: result: Pose or PackedPose object.
:return: tuple of (pdb_string, metadata)
Given a `Pose` or `PackedPose` object, return a tuple containing
the pdb string and a scores dictionary.
"""
_pdbstring =... | 4,577 |
def str_array( listString):
"""
Becase the way tha Python prints an array is different from CPLEX,
this function goes the proper CPLEX writing of Arrays
:param listString: A list of values
:type listString: List[]
:returns: The String printing of the array, in CPLEX format
:rtype: String
"""
... | 4,578 |
def read_gene_annos(phenoFile):
"""Read in gene-based metadata from an HDF5 file
Args:
phenoFile (str): filename for the relevant HDF5 file
Returns:
dictionary with feature annotations
"""
fpheno = h5py.File(phenoFile,'r')
# Feature annotations:
geneAnn = {}
for key... | 4,579 |
def update_rating_deviation(session_id, dict):
"""
updates the rating_deviations of music genres in the database with new ratings_deviations as a Json(dict)
Args:
session_id (int): id of a user's session
dict (dict): dictionary of rating_deviations
"""
cursor, connection = open_d... | 4,580 |
def cache(builds, cache_dir, ssl_verify=True):
"""
Download all the builds' artifacts into our cache directory.
:param set builds: set of Build objects
:param str cache_dir: path to a destination directory
:param ssl_verify: verify HTTPS connection or not (default: True)
"""
session = reque... | 4,581 |
def hex_xformat_decode(s: str) -> Optional[bytes]:
"""
Reverse :func:`hex_xformat_encode`.
The parameter is a hex-encoded BLOB like
.. code-block:: none
"X'CDE7A24B1A9DBA3148BCB7A0B9DA5BB6A424486C'"
Original purpose and notes:
- SPECIAL HANDLING for BLOBs: a string like ``X'01FF'`` ... | 4,582 |
def threshold(data, direction):
"""
Find a suitable threshold value which maximizes explained variance of the data projected onto direction.
NOTE: the chosen hyperplane would be described mathematically as $ x \dot direction = threshold $.
"""
projected_data = np.inner(data, direction)
sorted_x ... | 4,583 |
def StrType_any(*x):
""" Ignores all parameters to return a StrType """
return StrType() | 4,584 |
def _download(url, dest, timeout=30):
"""Simple HTTP/HTTPS downloader."""
# Optional import: requests is not needed for local big data setup.
import requests
dest = os.path.abspath(dest)
with requests.get(url, stream=True, timeout=timeout) as r:
with open(dest, 'w+b') as data:
... | 4,585 |
def height(tree):
"""Return the height of tree."""
if tree.is_empty():
return 0
else:
return 1+ max(height(tree.left_child()),\
height(tree.right_child())) | 4,586 |
def applyTelluric(model, tell_alpha=1.0, airmass=1.5, pwv=0.5):
"""
Apply the telluric model on the science model.
Parameters
----------
model : model object
BT Settl model
alpha : float
telluric scaling factor (the power on the flux)
Returns
-------
model : model object
BT Settl model times... | 4,587 |
def max_power_rule(mod, g, tmp):
"""
**Constraint Name**: DAC_Max_Power_Constraint
**Enforced Over**: DAC_OPR_TMPS
Power consumption cannot exceed capacity.
"""
return (
mod.DAC_Consume_Power_MW[g, tmp]
<= mod.Capacity_MW[g, mod.period[tmp]] * mod.Availability_Derate[g, tmp]
... | 4,588 |
async def list_subs(request: Request):
"""
List all subscription objects
"""
# Check for master token
if not request.headers.get("Master") == os.environ.get("MASTER_TOKEN"):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid authentication ... | 4,589 |
def check_archs(
copied_libs, # type: Mapping[Text, Mapping[Text, Text]]
require_archs=(), # type: Union[Text, Iterable[Text]]
stop_fast=False, # type: bool
):
# type: (...) -> Set[Union[Tuple[Text, FrozenSet[Text]], Tuple[Text, Text, FrozenSet[Text]]]] # noqa: E501
"""Check compatibility of ar... | 4,590 |
def create_data_table(headers, columns, match_tol=20) -> pd.DataFrame:
"""Based on headers and column data, create the data table."""
# Store the bottom y values of all of the row headers
header_tops = np.array([h.top for h in headers])
# Set up the grid: nrows by ncols
nrows = len(headers)
nc... | 4,591 |
def interp2d_vis(model, model_lsts, model_freqs, data_lsts, data_freqs, flags=None,
kind='cubic', flag_extrapolate=True, medfilt_flagged=True, medfilt_window=(3, 7),
fill_value=None):
"""
Interpolate complex visibility model onto the time & frequency basis of
a data visibil... | 4,592 |
def eps_divide(n, d, eps=K.epsilon()):
""" perform division using eps """
return (n + eps) / (d + eps) | 4,593 |
def generate_preflib_election(experiment=None, model=None, name=None,
num_voters=None, num_candidates=None, folder=None,
selection_method='random'):
""" main function: generate elections"""
votes = generate_votes_preflib(model, selection_method=select... | 4,594 |
def display_multi_grid(kline_settings={}):
"""显示多图"""
from vnpy.trader.ui import create_qapp
qApp = create_qapp()
w = GridKline(kline_settings=kline_settings)
w.showMaximized()
sys.exit(qApp.exec_()) | 4,595 |
def test_invalid_interface():
"""An invalid interface should raise a 'ValueError'."""
psutil.net_if_addrs = MagicMock(return_value=test_net_if_addrs)
with pytest.raises(ValueError):
interface_subnets('invalid') | 4,596 |
def bootstrapping_state_tomography(data_dict, keys_in, store_rhos=False,
verbose=False, **params):
"""
Computes bootstrapping statistics of the density matrix fidelity.
:param data_dict: OrderedDict containing thresholded shots specified by
keys_in, and where proce... | 4,597 |
def get_mc_uuid(username):
"""Gets the Minecraft UUID for a username"""
url = f"https://api.mojang.com/users/profiles/minecraft/{username}"
res = requests.get(url)
if res.status_code == 204:
raise ValueError("Users must have a valid MC username")
else:
return res.json().get("id") | 4,598 |
def _resolve_credentials(fqdn, login):
"""Look up special forms of credential references."""
result = login
if "$" in result:
result = os.path.expandvars(result)
if result.startswith("netrc:"):
result = result.split(':', 1)[1]
if result:
result = os.path.abspath(os.p... | 4,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.