content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def foreign_key(
table_name: str, schema: str, parent_name: str, parent_schema: str
) -> str:
"""Return column names (child and parent) of the foreign key."""
return f"""
SELECT
att2.attname as child_column,
att.attname as parent_column
FROM
(SELECT
unnest(con1.co... | 69,600 |
def available_models():
"""Check for available neural network models.
This function returns a list of all neural network models saved.
If None is available, it returns a message informing there's no models previously
saved.
Returns
-------
dirs : list
List of all neural network mod... | 69,601 |
def problem33(nr_digits):
"""Problem 33 - Digit canceling fractions"""
a_sum = 1
b_sum = 1
for a in range(10**(nr_digits - 1), (10**nr_digits) - 1):
for b in range(a + 1, 10**nr_digits):
# print(a/b);
a_str = str(a)
b_str = str(b)
for sa in rang... | 69,602 |
async def test(ctx):
"""Tests if the parameters taken in the function match the parameters that the event has"""
return ctx | 69,603 |
def set_avg_rgb(poly_cstr, lyrname, out_field, rast_cstr, srs, where=None, geom_field="geometry", id_field="ogc_fid"):
"""
Extract avg rgb from a raster inside polygons and store in out_field (string) as r,g,b
Requires int32 id field like ogc_fid
Must use common srs (srs param)
"""
transfer_rast... | 69,604 |
def add_entrypoints(setupcfg: ConfigUpdater, opts: ScaffoldOpts):
"""Add [options.entry_points] to setup.cfg"""
new_section_name = "options.entry_points"
if new_section_name in setupcfg:
return setupcfg, opts
new_section = ConfigUpdater()
new_section.read_string(templates.setup_cfg(opts))
... | 69,605 |
def create_top_video_photo():
"""
Creates a video which contains the estimated lane line markers using a top view and the top view image
:return:
"""
def process_image(image):
warped, warped_cam, perspec = lane_finder.find_lanes_using_window(image)
return warped_cam
find_lanes_... | 69,606 |
def expr2bdd(expr):
"""Convert an expression into a binary decision diagram."""
return bdd(expr2bddnode(expr)) | 69,607 |
def connect(host, port, chan):
"""Connect to IRC host, on port, and join chan"""
debug('Connecting to server {}:{} and joining {}'.format(
host, port, chan))
global B
global IRC_PARSER
global CUST_PARSER
B = Bot(host, int(port), debug=DEBUG)
IRC_PARSER = Parser(B, chan, IRC_DEFIN... | 69,608 |
def extCalcLayers(
cz,
r_detector,
prop_height,
detector_depth,
max_layers,
min_detector_depth,
rhos,
YeFrac,
YeOuterRadius,
default_elec_frac,
coszen_limit,
radii):
"""Layer density/distance calculator for each coszen s... | 69,609 |
def xyz2lammpstrj(xyztraj, lammpstrj_name, cell_info, xyzftype="xyz"):
"""Rewrite an xyz file to a lammpstrj file.
Parameters
----------
xyztraj : str
the name of the file with the xyz trajectory.
lammpstrj_name : str
the name of the file with the lammpstrj trajectory.
cell_in... | 69,610 |
def count():
"""Continuously receives data from client"""
global SERVER_IP
while True:
unpacker = struct.Struct('! B B i i i i i i i I')
(data, addr) = mySocket.recvfrom(unpacker.size)
if data.startswith('r' * 35):
received_parts = data.split()
receivedList = ... | 69,611 |
def iterative_decompress(
stream, offset, size, chunk_size=4096, wbits=DETECT_HEADER, retry=False
):
""" decompress data from stream chunk-wise """
decompressor = zlib.decompressobj(wbits)
n_read = 0
decomp = b''
return_err = None
try:
while n_read < size:
n_new = min(s... | 69,612 |
def loadPeaks(peakFile=None, peakfolder=None, isNF=True, CTFlist=[], skiprows=0):
"""
loads 1 to many peak bedfile into one pandas dataframe.
all og the peaks will be concatenated into one dataframe. this function can
work with jkobject|nfcore/chipseq nextflow pipelines output (isNF)
Args:
-----
peakFile: st... | 69,613 |
def test_that_using_empty_service_and_port_raises(manager):
""" unit test for PortForwardManager::open_service """
with pytest.raises(ValueError):
route = ('localhost', 22, 'example.com', None)
manager.open_service(None, route) | 69,614 |
def compute_dimension(bounds, pixel_resolution: tuple):
"""
:param bounds:
:param pixel_resolution: width and height of pixels in the units of its coordinate reference system extracted from
transformation of image
:return:
"""
output_width = int(math.ceil((bounds[2] - bounds[0]) / pixel_res... | 69,615 |
def conv_block(x, growth_rate, name):
"""A building block for a dense block.
# Arguments
x: input tensor.
growth_rate: float, growth rate at dense layers.
name: string, block label.
# Returns
Output tensor for the block.
"""
# assuming channels last
bn_axis = 3... | 69,616 |
def get_all_permission(only_value=True):
"""
่ฟๅๅฝๅๆๆๆๆๆ้
@param only_value ๅช่ฟๅvalue,ๆ่
ๆฌ่บซ
"""
num = get_permission_num() # ๆๆ(่ฝๅ็บง็)็ๆๆๆ้
# noinspection PyBroadException
try:
# print(timeit.timeit('UserOnline.query.order_by(UserOnline.online_user_num.desc(),
... | 69,617 |
def poly_legendre(l, m):
"""
polynomial coefficients of legendre
y = sqrt(1 - z^2)
"""
z, y = symbols('z y', real=True)
return Poly(sympy_legendre(l, m), domain='R', gens=(z, y)).as_dict() | 69,618 |
def synctree_entry(ctx, test, template, read, write):
""" entry point """
ctx.obj = CLIObject(test)
ctx.obj.template = template
if ctx.obj.test or template is None:
pass #template = "dss.templates.DefaultTemplate"
else:
pass #template = "ssis_dss.templates.templates.{}".format(templ... | 69,619 |
def tab_focus(*, info):
"""A model to complete on open tabs in the current window."""
model = _tabs(win_id_filter=lambda win_id: win_id == info.win_id,
add_win_id=False)
special = [
("last", "Focus the last-focused tab"),
("stack-next", "Go forward through a stack of focus... | 69,620 |
def _load_records(filename):
"""Read file and return a dataset of tf.Examples."""
return tf.data.TFRecordDataset(filename, buffer_size=_READ_RECORD_BUFFER) | 69,621 |
def get_location(t):
"""
get location of list of token.
"""
def get_loc(t, idx):
if isinstance(t, list):
return get_loc(t[idx], idx)
elif isinstance(t, Token):
return t.loc
else:
raise TypeError(f'{type(t)}')
if isinstance(t, Token):
... | 69,622 |
def get_rounds(number):
"""Create a list containing the current and next two round numbers.
:param number: int - current round number.
:return: list - current round and the two that follow.
"""
return [number, number + 1, number + 2] | 69,623 |
def test_linkage_1(base_settings):
"""No. 1 tests collection for Linkage.
Test File: linkage-example.json
"""
filename = base_settings["unittest_data_dir"] / "linkage-example.json"
inst = linkage.Linkage.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert... | 69,624 |
def get_num_adain_params(model):
"""
input:
- model: nn.module
output:
- num_adain_params: int
"""
# return the number of AdaIN parameters needed by the model
num_adain_params = 0
for m in model.modules():
if m.__class__.__name__ == "AdaptiveInstanceNorm1d":
num_... | 69,625 |
def configure_dhcpv6_guard_policy(device, policy_name, device_role):
""" Configure DHCPv6 Guard Policy
Args:
device ('obj'): device to use
policy_name ('str'): name of the policy to be configured
device_role ('str'): role of the device
Returns:
None
... | 69,626 |
def gzip_and_name(fname, gzip_file=True) -> str:
"""
Gzip file if requested.
Parameters
----------
fname: str
path to file
gzip_file: bool, optional
whether to gzip the file
Returns
-------
str
up to date filename
"""
if gzip_file:
with open(... | 69,627 |
def matmul(lhs, rhs, transa=False, transb=False):
"""Create an extern op that compute matrix mult of A and rhs with rocBLAS
Parameters
----------
lhs : Tensor
The left matrix operand
rhs : Tensor
The right matrix operand
transa : bool
Whether transpose lhs
transb : b... | 69,628 |
def test_context_for_user(settings, mocker, test_user, extra_context):
"""Tests that context_for_user returns the expected values"""
user_ctx = {"user": test_user} if test_user else {}
mock_get_resource_page_urls = mocker.patch("mail.v2.api.get_resource_page_urls")
assert context_for_user(user=test_user... | 69,629 |
def draw_text(x, y, text, tag):
"""..."""
# โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
global im_gc
wash(tag)
try:
im_gc.pop(tag)
except KeyError:
pass
txt_im = Image.fromarray(nsfont.draw_text(text))
im_gc[tag] = ImageTk.PhotoImage(txt_im)
... | 69,630 |
def call(func: typing.Callable[..., typing.Any],
args: typing.Optional[typing.Sequence[str]] = None,
prog: typing.Optional[str] = None,
doc_parser: DocParserType = google_doc_parser,
param_parser: ParamParserType = basic_param_parser) -> typing.Any:
"""Call function using Google ... | 69,631 |
def start(context, python_ver=PYTHON_VER):
"""Start Nautobot and its dependencies in detached mode.
Args:
context (obj): Used to run specific commands
python_ver (str): Will use the Python version docker image to build from
"""
print("Starting Nautobot in detached mode.. ")
context.... | 69,632 |
def clone(clone_specs: Iterable[CloneSpec]) -> List[CloneSpec]:
"""Clone all repos asynchronously.
Args:
clone_specs: Clone specifications for repos to clone.
cwd: Working directory. Defaults to the current directory.
Returns:
Specs for which the cloning failed.
"""
return ... | 69,633 |
def corrAFM(s):
""" Compute the correlator for this pattern:
โ โ
โ โ
and symmetry-equivalent patterns
"""
res = 0.0
L = s.shape[-1]
for i in range(L-1):
for j in range(L-1):
res += s[0, i, j] * s[1, i+1, j] * s[1, i, j+1] * s[0, i+1, j+1]
... | 69,634 |
def RPL_SERVLISTEND(sender, receipient, message):
""" Reply Code 235 """
return "<" + sender + ">: " + message | 69,635 |
def fix_missing_locations2(node):
"""
When you compile a node tree with compile(), the compiler expects lineno and
col_offset attributes for every node that supports them. This is rather
tedious to fill in for generated nodes, so this helper adds these attributes
recursively where not already set, ... | 69,636 |
def test_ifcfg_static_wep_ask(monkeypatch):
"""
Report if there's a static WEP sysconfig without stored key.
"""
STATIC_WEP_ASK_KEY_SYSCONFIG = textwrap.dedent("""
TYPE=Wireless
ESSID=wep1
NAME=wep1
MODE=Managed
WEP_KEY_FLAGS=ask
SECURITYMODE=open
... | 69,637 |
def downsample(scan, is_mask=False, ori_space=None, trgt_space=None, ori_sz=None, trgt_sz=None, order=1, labels=None):
"""
:param labels: used for advanced downsample when order = 1 for is_mask
:param is_mask: mask have smooth upsampling
:param scan: shape(z,y,x,chn)
:param ori_space: shape(z,y,x)
... | 69,638 |
def calc_limits_sorted(data, crop, extend=False, interpolate=False):
"""
Crops given data by applying specified range to first data and
optionally extends data by adding adjacent points and finally calculates
minimum and maximum for each data. Note that this method assumes the first
data item to be ... | 69,639 |
def GetSweepParamList(core):
"""
ในใคใผใใใฉใกใผใฟๅคใชในใใฎ็ๆ
[in] core PDIใณใขใใผใฟ
ๆปใๅค -> ในใคใผใใใฉใกใผใฟๅคใชในใ
"""
if not core or not core.pd:
return None
spl = []
for p in core.pd.plist:
if not p.disable and p.calcCaseNum() > 1:
spl.append(p)
continue # end of for(p)
... | 69,640 |
def get_repository_action_counts(repo, start_date):
""" Returns the daily aggregated action counts for the given repository, starting at the given
start date.
"""
return RepositoryActionCount.select().where(
RepositoryActionCount.repository == repo, RepositoryActionCount.date >= start_date
) | 69,641 |
def generate_object_example(properties, definitions):
"""
Generates an object example from the properties and definitions obtained from the JSON schema.
:param properties: A `dict` that defines the properties of the object.
:param definitions: A `dict` that defined the schema of certain properties in-c... | 69,642 |
def attention_block(input_features, context_features, bottleneck_dimension,
output_dimension, attention_temperature, valid_mask,
is_training):
"""Generic attention block.
Args:
input_features: A float Tensor of shape [batch_size, input_size,
num_input_features].
... | 69,643 |
def get_tag_counts():
"""return counts of all tags"""
query = DB.session.query(Tag.name,
DB.func.count(Resource.identifier)).join(
Resource.tags).group_by(Tag.id)
return dict(query) | 69,644 |
def rolling_window(a: np.ndarray, window: int) -> np.ndarray:
"""Create a rolling window over the provided array.
Args:
a: array on which to perform the rolling window
window: the size of the rolling window
Returns:
An array of the rolling window.
"""
shape = a.shape[:-1] +... | 69,645 |
def start_export(df, json_dir, topic_num='all', save_path=None):
"""Check the topic_num configuration and then start the export."""
if isinstance(topic_num, str):
if topic_num.isdigit():
topic_num = int(topic_num)
else:
topic_num = topic_num.lower()
if isinstance(topi... | 69,646 |
def test_create_batch_change_without_owner_group_id_succeeds(shared_zone_test_context):
"""
Test successfully creating a batch change without owner group ID specified
"""
client = shared_zone_test_context.ok_vinyldns_client
ok_zone = shared_zone_test_context.ok_zone
test_record_name = generate_r... | 69,647 |
def map_range(x, in_min, in_max, out_min, out_max):
"""re-maps a number from one range to another."""
mapped = (x-in_min) * (out_max - out_min) / (in_max-in_min) + out_min
if out_min <= out_max:
return max(min(mapped, out_max), out_min)
return min(max(mapped, out_max), out_min) | 69,648 |
def aerospike_start():
"""Starts aerospike on servers"""
with settings(warn_only=True):
run('/etc/init.d/citrusleaf start') | 69,649 |
def format_file_path(filepath):
"""Formats a path as absolute and with the correct platform separator."""
try:
filepath = os.path.realpath(os.path.abspath(filepath))
filepath = re.sub(r'[/\\]', os.path.sep, filepath)
except: # pragma: nocover
pass
return filepath | 69,650 |
def test_find_filters_ensembl(df_filters_ensembl_hsapiens_gene):
"""Test the available filters returned by find_filters() for the
hsapiens_gene_ensembl dataset."""
expect = (df_filters_ensembl_hsapiens_gene
.sort_values(by="Filter_ID", axis=0)
.reset_index(drop=True))
result ... | 69,651 |
def test_length_25(valid_data):
"""Test whether length beyond packet size raises exception"""
valid_data["length"] = 25
with pytest.raises(IOError):
Packet(bitstring.pack(PACKET_FORMAT, **valid_data), "127.0.0.1") | 69,652 |
def extract_faces_from_image(image_array, face_boxes, required_size=(160, 160), convert_2_numpy=True):
"""
Extract face region from image array
Args:
image_array (array): Image pixels in numpy format
face_boxes (list): list of face bounding boxes
required_size (tuple, optional):... | 69,653 |
def plot_histo_label_lim(dataset, column, cats, max_len):
"""
Plot histogram of token length of used data depending on categorie levels when constraining to a maximal token length
:param dataset: dataset to plot
:param column: column of the dataset to plot
:param cats: categories to analyse
:param ma... | 69,654 |
def activity_stream(context, stream_type, *args, **kwargs):
"""
Renders an activity stream as a list into the template's context.
Streams loaded by stream_type can be the default ones (eg user, actor, etc.) or a user defined stream.
Extra args/kwargs are passed into the stream call.
::
{% ... | 69,655 |
def dilated_residual_2d(inputs, filters, kernel_size=3, rate_mult=2,
dropout=0, repeat=1, symmetric=True, **kwargs):
"""Construct a residual dilated convolution block.
"""
# flow through variable current
current = inputs
# initialize dilation rate
dilation_rate = 1.0
for ri in range(repeat):
re... | 69,656 |
def map_to_exports(map):
"""Prints the map as eval-able set of environment variables. Keys
will be cleaned of all non-word letters and values will be escaped so
that they will be exported as literal values."""
ret = ""
keys = []
for key, val in list(map.items()):
if isinstance(val, six.s... | 69,657 |
def deep_model(model: str = 'vggvox-v2', quantized: bool = False, **kwargs):
"""
Load Speaker2Vec model.
Parameters
----------
model : str, optional (default='speakernet')
Model architecture supported. Allowed values:
* ``'vggvox-v1'`` - VGGVox V1, embedding size 1024, exported fro... | 69,658 |
def main(target, label):
"""
Semver tag triggered deployment helper
"""
check_environment(target, label)
click.secho('Fetching tags from the upstream ...')
handler = TagHandler(git.list_tags())
print_information(handler, label)
tag = handler.yield_tag(target, label)
confirm(tag) | 69,659 |
def run(include_private=True, include_lowercase=False):
"""Initialise builtin fuzzing engines."""
if include_private:
engines = fuzzing.ENGINES
else:
engines = fuzzing.PUBLIC_ENGINES
for engine_name in engines:
mod = importlib.import_module(
f'clusterfuzz._internal.bot.fuzzers.{engine_name}... | 69,660 |
def conv3x3(in_planes, out_planes, stride=1,pad=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=pad, bias=False) | 69,661 |
def arcs_kt_schema(name, src, out = None):
"""Generates a Kotlin file for the given .arcs schema file."""
_run_schema2pkg(
name = name,
src = src,
out = out,
language_name = "Kotlin",
language_flag = "--kotlin",
file_extension = ".kt",
) | 69,662 |
def translateShortcutToOSNames(shortcut):
"""
Translate Qt names to OS names (e.g. Ctrl -> cmd symbol for Mac,
Meta -> Windows for windows
"""
if sys.platform == "darwin":
replace = (
("Ctrl+", "\u2318"),
("Shift+", "\u21E7"),
("Alt+", "\u2325"),
... | 69,663 |
def EDA_classify_and_return_cols_by_type(df1, nlp_char_limit=20):
"""
EDA stands for Exploratory data analysis. This function performs EDA - hence the name
########################################################################################
This handy function classifies your columns into differ... | 69,664 |
def getNewAccountPass(player, data):
"""
Gets a new account password if the player is creating a new accont.
"""
if not data.isalnum():
player.writePlain('Passwords must contain only letters or numbers!')
player.writePlain('Choose a password: ')
return
player.writePlain(... | 69,665 |
def log_error(err_code):
""" Take an error code from the tracker and log an error for the user. """
error = constants.Errors(err_code)
if error != constants.Errors.SUCCESS and error != constants.Errors.NO_ERROR:
logger.error(f'ERROR: {error}')
return True
return False | 69,666 |
def rodrigues(theta):
"""Convert axis-angle representation to rotation matrix.
Args:
theta: size = [B, 3]
Returns:
Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
"""
l1norm = torch.norm(theta + 1e-8, p = 2, dim = 1)
angle = torch.unsqueeze(l1norm, -1)
nor... | 69,667 |
def hairball_plot(
g,
color_list=None,
display=False,
node_size=1,
text_color="black",
node_sizes=None, # for custom sizes
layout_parameters=None,
legend=None,
scale_by_size=True,
layout_algorithm="force",
edge_width=0.01,
... | 69,668 |
def p_boolean_sliding_window(texts, segmented_topics, dictionary, window_size, processes=1):
"""Perform the boolean sliding window probability estimation.
Parameters
----------
texts : iterable of iterable of str
Input text
segmented_topics: list of (int, int)
Each tuple (word_id_se... | 69,669 |
def get_relme() -> Iterable[models.TRelMe]:
"""Get all relme records"""
return models.TRelMe.objects.all() | 69,670 |
def allow_client(client_type):
"""Allows another type to act as client type. Intended for using with mock clients."""
global ok_types
ok_types += (client_type,) | 69,671 |
def rand_index(l):
"""
Return an index of the list with the probability given in the list.
Example: prob_index([0.5,0.25,0.25]) should return 0 50% of the time, 1 25%
of the time and 2 25% of the time.
"""
r = numpy.random.uniform(0., sum(l))
s = l[0]
for i,p in enumerate(l):
... | 69,672 |
def install(service, config):
"""Install service configuration"""
print('Setting up service [{}] for config [{}]...'.format(service, config))
settings, error = load_settings(service, config)
if error is not None:
print('ERROR:', error, file=sys.stderr)
sys.exit(1)
try:
if ser... | 69,673 |
def Table_Convert(url, contents={}, table=0):
"""
Open a web page which a table and pull out the contents of that table
into a list of dictionaries with your own custom keys.
CODE: Table_Convert(url, contents, table)
AVAILABLE PARAMS:
url - The url you want to open and pull data from
contents - Se... | 69,674 |
def _var_to_series(s):
"""return a pandas Series from a list of lists (arranged vertically)"""
if not isinstance(s, (list, tuple)):
raise TypeError("Expected a list of lists")
keys, values = [], []
for row in s:
if not isinstance(row, (list, tuple)):
raise TypeError("Expecte... | 69,675 |
def process_line(line: str) -> str or None:
"""
Pre-processes a line by removing comments and whitespaces.
Return a line as an array.
If a line does not have valid instructions, it will return None.
"""
# Remove comments
if '#' in line:
cut: int = line.find('#')
line: str = l... | 69,676 |
def test_script_scraping():
"""Test that the scripts in a document are collected properly."""
err = ErrorBundle()
parser = markuptester.MarkupParser(err, debug=True)
parser.process("foo.xul", """
<doc>
<!-- One to be ignored -->
<script type="text/javascript">
eval("asdf");
</script... | 69,677 |
def get_known_corrects(pos: str, wordform: str, input_word: str):
"""
Get list of known correct outputs of `input_word` with given `pos`,
converted to `wordform`.
"""
try:
lemma = agid[pos]["to_lemma"][input_word]
except KeyError:
return []
# Check if we are converting to t... | 69,678 |
def smartypants(text):
"""
Transforms sequences of characters into HTML entities.
=================================== ===================== =========
Markdown HTML Result
=================================== ===================== =========
``'s``... | 69,679 |
def transform_gcp_subnets(subnet_res):
"""
Add additional fields to the subnet object to make it easier to process in `load_gcp_subnets()`.
:param subnet_res: The response object returned from compute.subnetworks.list()
:return: A transformed subnet_res
"""
# The `id` in the response object has ... | 69,680 |
def get_chessboard_lines (corners, image):
"""
Function: get_chessboard_lines
------------------------------
given a list of corners represented as tuples, this returns
(horizontal_lines, vertical_lines) represented as (a, b, c)
pairs
"""
#=====[ Step 1: get lines via Hough transform on corners ]=====
c... | 69,681 |
def _dg_is_sink_source( dg, v ):
"""
Returns True iff the digraph dg has a sink or a source at vertex v.
INPUT:
- ``dg`` -- a digraph
- ``v`` -- a vertex of dg
EXAMPLES::
sage: from sage.combinat.cluster_algebra_quiver.mutation_class import _dg_is_sink_source
sage: from sage.... | 69,682 |
def get_uvs_fingerprinting_algo_desc():
""" Return a string mentioning the current fingerprinting algorithm in use by the system. """
log.cmv("get_uvs_fingerprinting_algo_desc() called. ")
if sdef.REPO_HASH_CHOICE == sdef.HashAlgo.SHA512:
return "SHA512_HMAC"
if sdef.REPO_HASH_CHOICE == sdef... | 69,683 |
def add_parser_output_options(parser):
"""Populate a CL base parser with output options"""
parser.add_argument('-o', '--html-output-file',
help='generate a html file with per-segment scores and highlighting')
parser.add_argument('-p', '--plain-output-file',
he... | 69,684 |
def get_smaller_channel(channel, channel_range):
"""
get channels which is smaller than inputs
:param channel:input channel
:param channel_range:list,channel range
:return:list,channels which is larger than inputs
"""
return list(filter(lambda x: x < channel, channel_range)) | 69,685 |
def poch(a,n):
""" Returns the Pochhammer symbol (a)_n. """
# First, check if 'a' is a real number (this is currently only working for reals).
assert type(a) is not type(1+1j), "a must be real: %r" % a
isInteger(n)
# Compute the Pochhammer symbol.
if n == 0:
return 1.0
else... | 69,686 |
def test_atomic_integer_min_inclusive_nistxml_sv_iv_atomic_integer_min_inclusive_1_1(mode, save_output, output_format):
"""
Type atomic/integer is restricted by facet minInclusive with value
-999999999999999999.
"""
assert_bindings(
schema="nistData/atomic/integer/Schema+Instance/NISTSchema-... | 69,687 |
def flatten(game_data):
"""Flatten the game data into a vector.
Parameters
----------
game_data : ndarray
An ndarray of shape (# games, 2, 11, 52). 2 teams, 10 players + 1 team aggregate
statistic, and 52 features.
Returns
-------
flattened_data : ndarray
An ndarray... | 69,688 |
def to_base36(number):
"""Converts an integer to a base36 string."""
alphabet = digits + uppercase
base36 = ''
sign = ''
if number < 0:
sign = '-'
number = -number
if 0 <= number < len(alphabet):
return sign + alphabet[number]
while number != 0:
number, i = ... | 69,689 |
def mean_filter(
data,
nb_neighbours,
mask=None,
target_val=0,
extent=1,
min_count=3,
interpolate="mask_isolated",
debugging=False,
):
"""
Mask or apply a mean filter to data.
The procedure is applied only if the empty pixel is surrounded by nb_neighbours or
more pixels ... | 69,690 |
def smart_decoder(raw_content, default_encoding_list=("utf-8", "gb18030")):
"""
ๅฐๅญ็ฌฆไธฒ่งฃ็ ๆunicode
:type default_encoding_list: list of str
:rtype: str
:type raw_content: bytes
"""
import chardet
encoding = chardet.detect(raw_content).get("encoding", "utf-8")
try:
return raw_con... | 69,691 |
def sample_sequence(personality, history, tokenizer, model, args, current_output=None):
"""A function to sample the network. Taken from `interact.py`"""
special_tokens_ids = tokenizer.convert_tokens_to_ids(SPECIAL_TOKENS)
if current_output is None:
current_output = []
for i in range(args["max_l... | 69,692 |
def show_line(line, sev, msg):
"""Output a log line in gcc error format"""
# Only report each individual line once.
log = "{}:{}:1: {}: {} '{}'".format(line.filename,
line.lineno,
sev,
m... | 69,693 |
def clique_merge(contigsof, threshold=0.5):
"""Merges all maximal cliques of clusters.
Inputs:
contigsof: A {clustername: set(contignames)} dict
threshold [0.5]: Minimum fraction of overlapping contigs to create edge
Output: A {clustername: set(contignames)} dict
"""
# Calculate a... | 69,694 |
def get_annotmatch_rowids_from_aid(
ibs, aid_list, eager=True, nInput=None, force_method=None
):
"""
Undirected version
Returns a list of the aids that were reviewed as candidate matches to the input aid
aid_list = ibs.get_valid_aids()
CommandLine:
python -m wbia.annotmatch_funcs --exec... | 69,695 |
def Standard_ErrorHandler_IsInTryBlock(*args):
"""
* Test if the code is currently running in a try block
:rtype: bool
"""
return _Standard.Standard_ErrorHandler_IsInTryBlock(*args) | 69,696 |
def quantity(name):
""" """
quantity = None
if name.lower() not in quants:
for k, v in quants.items():
if v['name'].lower() == name.lower():
quantity = v
break
else:
quantity = quants[name]
return quantity | 69,697 |
def copy_directory_to_worker(host_directory, worker_directory, replace=False):
"""Recursively copy a directory to the worker. Directories are created as
needed. Unless |replace| is True, files already in |worker_path| will remain
after this call."""
if replace:
remove_directory(worker_directory, recreate=Tr... | 69,698 |
def test_insert_largest_right(test_bsts):
"""Test insert the largest to the right."""
test_bsts[1].insert(7)
assert test_bsts[1].root.right.val > test_bsts[1].root.val | 69,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.