content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def privileges_granted_directly(self, node=None):
"""Check that a user is able to execute `SHOW USERS` with privileges are granted directly.
"""
user_name = f"user_{getuid()}"
if node is None:
node = self.context.node
with user(node, f"{user_name}"):
Suite(run=check_privilege, fl... | 50,300 |
def compose_left(*funcs):
"""Compose sync and async functions to operate in series.
Returns a function that applies other functions in sequence. The returned
function will be an async function iff at least one of the functions in the
sequence is async.
Functions are applied from left to right so t... | 50,301 |
def squarefree_part(x, timeout_duration=20, use_ecm=True):
"""return the squarefree part of x or 'NO DATA (timed out)'"""
F = squarefree_and_factorization(
x=x, timeout_duration=timeout_duration, use_ecm=use_ecm
)
if isinstance(F, str):
return F
else:
return F[0] | 50,302 |
def plotMemeById(meme_id):
"""
Plots a meme given its ID.
- **parameters**::
:param meme_id: ID of the meme
Examples:
>>> plotMemeById("02568")
"""
# Plot the meme as well as its label
ext = memo[memo["id"]==int(meme_id)]['img'].values[0].split('.')[1]
meme_id = int(me... | 50,303 |
def test_beam2_graph_search():
"""
like test_beam2_tree_search, but eliminates duplicate nodes
"""
for goal in range(1, 10):
p = AnnotatedProblem(EasyProblem(0, goal))
sol = next(beam_search(p, beam_width=2, graph=True))
assert sol.state_node.state == goal
assert p.nodes_... | 50,304 |
def unix_time_to_id(unix_time):
"""
Converts the given unix time to id.
Parameters
----------
unix_time : `int`, `float`
The unix time to convert to id.
Returns
-------
id_ : `int`
"""
return (floor(unix_time*1000.)-DISCORD_EPOCH)<<22 | 50,305 |
def method_withBadName_with_bad_params_on_single_line(myBadlyNamedParam, my_other_Bad_name):
"""Provide parameters with bad names on single line."""
return myBadlyNamedParam + my_other_Bad_name | 50,306 |
def test_create_subresource_icontrol_4XX_exception(bigip, response):
"""Test create can handle HTTP client exception."""
data = resource_data()
subres = SubResource(name=data['name'], partition=data['partition'])
response.status_code = 400
bigip.tm.ltm.subresources.subresource.create.side_effect = ... | 50,307 |
async def async_setup_platform(
hass, config, async_add_devices, discovery_info: object = {}
):
"""Set up Loxone Sensor from yaml"""
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is not None:
value_template.hass = hass
# Devices from yaml
if config != {}:
# ... | 50,308 |
def build_cal_args(args):
"""Determine the year/month. Return list [year] or [year, month]"""
t = datetime.date.today()
m, y = t.month, t.year
x = None
if len(args) == 0:
# no args - print default calendar
x = [y, m]
elif len(args) == 1:
# cal + ==> next month
i... | 50,309 |
def reorder_cube_coord(
cube, indices, new_coord_points=None, *, promote=True, **coord_kwargs
):
"""Use indices and the corresponding axis to reorder a cube's data along that axis.
Args:
cube (iris.cube.Cube): Cube to be modified.
indices (1-D iterable): Indices used to select new ordering ... | 50,310 |
def per_sample_sequences(iter_, max_seqs, min_seqs=1, random_buf_size=100000):
"""Get a max random subset of per sample sequences
Parameters
----------
iter_ : skbio.parse.sequences.SequenceIterator
The sequences to walk over
max_seqs : unsigned int
The maximum number of sequences p... | 50,311 |
def file_parts(file_path):
"""
Lists a files parts such as base_path, file name and extension
Example
base, name, ext = file_parts('path/to/file/dog.jpg')
print(base, name, ext) --> ('path/to/file/', 'dog', '.jpg')
"""
base_path, tail = os.path.split(file_path)
name, ext = os.p... | 50,312 |
def verify(ctx, config):
"""
:param PxContext ctx:
:param pxConfig config:
:return bool: is request verified
"""
logger = config.logger
logger.debug('Evaluating Risk API request, call reason: {}'.format(ctx.s2s_call_reason))
try:
start = time.time()
response = send_risk_... | 50,313 |
def mon_generateur():
"""Notre premier générateur. Il va simplement renvoyer 1, 2 et 3"""
yield 1
yield 2
yield 3 | 50,314 |
def get_or_train_cav(concepts,
bottleneck,
acts,
cav_dir=None,
cav_hparams=None,
overwrite=False):
"""Gets, creating and training if necessary, the specified CAV.
Assumes the activations already exists.
Args... | 50,315 |
def print_k_mer_composition(dna, k):
"""
Prints the k-mer composition of DNA string.
Args:
dna {str}: DNA string
k {int}: length of substring
Returns:
None
"""
for substring in cartesian_product("ACGT", k):
print(len(re.findall(f'(?={substring})', dna)), end=' '... | 50,316 |
def provision_update(obj, pretty_print, beep,
headers,
payload,
active_validation):
"""Updates wireless provisioning.
"""
spinner = init_spinner(beep=beep)
start_spinner(spinner)
try:
if headers is not None:
headers =... | 50,317 |
def _dice(array):
"""Given an array containing true/false positive/negative columns for the
'shadow' class, calculates the dice coefficient."""
v = {'TP': 0, 'TN': 0, 'FP': 0, 'FN': 0}
for val in v:
v[val] = float(np.sum(array['Shadow ' + val]))
dice = v['TP'] / ((v['FP'] + v['TP']) + (v[... | 50,318 |
def euclidian_dist(p1, p2):
""" p1 and p2 must both be of len 2 where p1 = (x1,y1); p2 = (x2,y2)"""
return math.sqrt((p1[0] - p2[0])**2 + (p1[1] - p2[1])**2) | 50,319 |
def test_run_cmd():
"""
try to start a job
"""
# wait a bit for the service to come up
time.sleep(1)
r = requests.post(
urljoin(MANAGER_URL, "job/0bc72a99-390e-4929-a23f-d8e91b85dd34/start"),
json=job_data_with_run,
headers=pytest.headers,
)
assert r.json().get("... | 50,320 |
def colorify_by_name(image, cmap_name, flip_map=False, rescale_type='min_max', limits=None, num_colors=256):
"""
Return 2D image as 3D RGB stack colored with a given colormap.
Parameters
----------
image: 2d array
image to convert to RGB
cmap_name: str
Matplotlib colormap or... | 50,321 |
def lazy_matrix_mul(m_a, m_b):
"""
multiply 2 matrix that is given
Args:
m_a: input first matrix
m_b: input second matrix
Returns:
return m_a * m_b
"""
return numpy.matmul(m_a, m_b) | 50,322 |
def denormalize_tags(df: pd.DataFrame) -> pd.DataFrame:
""" For a DataFrame with a column 'tags' that contains comma-space-separated
tags, denormalize the 'tags' column. """
if df.empty:
return add_missing_columns(df, required_columns=['tag'])
df = df.copy()
df['tags'] = df['tags'].str.spli... | 50,323 |
def main():
"""Set up command line interface and process input to call the corresponding functions."""
if not os.path.isdir(DATA):
os.mkdir(DATA)
if len(sys.argv) == 1:
print("Welcome to the messenger. Type 'quit' to exit and 'help' for more information about the usage.")
try:
op... | 50,324 |
def read_consanguineous_samples(path, cutoff=0.05):
"""
Read inbreeding coefficients from a TSV file at the specified path.
Second column is sample id, 6th column is F coefficient. From PLINK:
FID, IID, O(HOM), E(HOM), N(NM), F
Additional columns may be present but will be ignored.
"""
consa... | 50,325 |
def write_results_to_csv(results: OutputResult, output_path: str):
"""
Writes the result of processing to the output path as a csv file. If omitted values are present, for output_path of
/dir/file.csv, the omitted will be written to /dir/file-omitted.csv.
Args:
results: The results to be writ... | 50,326 |
def component(graph: Graph[T], node: T) -> Graph[T]:
"""Returns the connected component that contains the given vertex, as a new Graph object.
A vertex with no incident edges is itself a component.
A graph that is itself connected has exactly one component, consisting of the whole graph.
"""
re... | 50,327 |
def _deserialize(data, klass):
"""Deserializes dict, list, str into an object.
:param data: dict, list or str.
:param klass: class literal, or string of class name.
:return: object.
"""
if data is None:
return None
if klass in six.integer_types or klass in (float, str, bool):
... | 50,328 |
def view_entries(entries, width, count, parsable):
"""Print a filtered set of entries
Args:
entries (dict): entries to be viewed
width (int): width of the column
count (bool): prints total amount of entries
parsable: (bool): prints the result in a parsable format
"""
if p... | 50,329 |
def smooth(data, fwhm, mask = 0):
""" smooth
Parameters
---------------------
data an object of class field
fwhm
mask a numpy.nd array,
with the same dimensions as the data
Returns
---------------------
An object of class field with
Examples
... | 50,330 |
def get_xy_coords(xda):
"""Return the dimension name for x and y coordinates
e.g. XC or XG
Parameters
----------
xda : xarray DataArray
with all grid information
Returns
-------
x,y : str
with e.g. 'XC' or 'YC'
"""
x = 'XC' if 'XC' in xda.coords else 'X... | 50,331 |
def make_klass(spec):
"""
Create a data class given a spec.
Parameters
----------
spec :
TODO
"""
if spec is None:
return None
fields = spec.fields
if fields:
newfields = dict()
for item in fields:
if len(item) == 2:
if is... | 50,332 |
def get_init_cell(batch_size, rnn_size):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
# TODO: Implement Function
lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
cell = tf.contrib.r... | 50,333 |
def receiver(data):
"""Receives data from Lambda
"""
# Handlers
update_types = {
'message': _message,
'edited_message': _edited_message,
'channel_post': _channel_post,
'edited_channel_post': _edited_channel_post,
'inline_query': _inline_query,
'chosen_inl... | 50,334 |
def remote_docker(client_ip, docker_host, *args):
"""
Run ``docker`` on ``client_ip``.
:param bytes docker_host: The DOCKER_HOST environment variable to set
before running ``docker``.
:param args: Other command line arguments to supply to ``docker``.
:returns: A ``Deferred`` when the comman... | 50,335 |
def make_parser():
"""Makes the argument parser"""
p = argparse.ArgumentParser("conda-suggest")
subcmd = p.add_subparsers(dest="subcmd", help="subcommand to execute")
# Generate commands
gen = subcmd.add_parser("generate", help="create map files for a channel")
gen.add_argument("channel", help="... | 50,336 |
def aggregate_f(loc_fscore, length_acc, vessel_fscore, fishing_fscore, loc_fscore_shore):
"""
Compute aggregate metric for xView3 scoring
Args:
loc_fscore (float): F1 score for overall maritime object detection
length_acc (float): Aggregate percent error for vessel length estimation
... | 50,337 |
def index(request):
"""
Index view: shows a form with a list of ticket that one can buy
"""
ticket_types = TicketType.objects.all()
form = TicketsForm(ticket_types,[], request.POST)
if form.is_valid():
data = form.cleaned_data
p = TicketPurchase()
print data
if da... | 50,338 |
def _on_vertex(
easting: Union[int, float], northing: Union[int, float], resolution: int
) -> bool:
"""Test if point lies on vertex."""
return (
True
if (int(easting) % resolution == 0) and (int(northing) % resolution == 0)
else False
) | 50,339 |
def add_jitter(df, jitter):
"""
Adds jitter to a data set based on a random normal
distribution.
Requirements: numpy, pandas
"""
return abs(df + np.random.normal(df, jitter, size=len(df))) | 50,340 |
def viz_obb(pc, label, mask, angle_classes, angle_residuals,
size_classes, size_residuals):
""" Visualize oriented bounding box ground truth
pc: (N,3)
label: (K,3) K == MAX_NUM_OBJ
mask: (K,)
angle_classes: (K,)
angle_residuals: (K,)
size_classes: (K,)
size_residuals: (K,3)
"""
... | 50,341 |
def collate_fn(batch):
"""Creates mini-batch tensors from the list of tuples (query, positive, negatives).
Args:
data: list of tuple (query, positive, negatives).
- query: torch tensor of shape (3, h, w).
- positive: torch tensor of shape (3, h, w).
- negative: torch ... | 50,342 |
def _test_same_files(base_list_path, directory_path):
"""Assert expected files are in the `directory_path`.
Parameters:
base_list_path (string): a path to a file that has one relative
file path per line.
directory_path (string): a path to a directory whose contents will
... | 50,343 |
def complete_graph(number_of_vertices, name="Complet graph", directed=False):
"""
Construction of a complete graph.
The number of edges is exactly n*(n-1)/2 (where n is the number of vertices)
:param number_of_vertices:
:param name:
:param directed: False for undirected graph
:return: the ... | 50,344 |
def print_aspects(jdate):
"""Function to format and print aspects between the bodies for a date"""
print('\n')
print('------------- Bodies Aspects -------------')
for aspect in get_aspects(jdate):
body1, body2, i_asp, orb = aspect
degs, mins, secs = dd_to_dms(orb)
print(f"{body_n... | 50,345 |
def main(train_path, valid_path, save_path, save_img):
"""Problem: Logistic regression with Newton's Method.
Args:
train_path: Path to CSV file containing dataset for training.
valid_path: Path to CSV file containing dataset for validation.
save_path: Path to save predicted probabilitie... | 50,346 |
def obv(df, price, volume, obv):
"""
The On Balance Volume (OBV) is a cumulative total of the up and down volume.
When the close is higher than the previous close, the volume is added to
the running total, and when the close is lower than the previous close,
the volume is subtracted from the running... | 50,347 |
def is_data(line):
"""
Function utilized by itertool's groupby method in determining
the delimiter between our blocks of data.
"""
return True if line.strip() else False | 50,348 |
def update_license(license_id, **kwargs):
"""
Replace the License with given ID with a new License
"""
updated_license = licenses_api.get_specific(id=license_id).content
for key, value in iteritems(kwargs):
if value:
setattr(updated_license, key, value)
response = utils.che... | 50,349 |
def _browse_device(device_id: MediaId, device: Device) -> BrowseMediaSource:
"""Return details for the specified device."""
device_info = NestDeviceInfo(device)
return BrowseMediaSource(
domain=DOMAIN,
identifier=device_id.identifier,
media_class=MEDIA_CLASS_DIRECTORY,
media_... | 50,350 |
def get_organization_suggestions(config, donl_type):
"""
Get organization suggestions for a given type
:param dict[str, Any] config: The configuration to use for selecting DONL
organizations
:param str donl_type: The DONL type to get suggestions for
:rtype: list of... | 50,351 |
def get_lines(model_name):
"""
Import data from a data file to the db model
Args:
file_name: (string) file's name
model_name: (string) db model's name.
"""
# get model
model_obj = apps.get_model(settings.WORLD_DATA_APP, model_name)
fields = model_obj._meta.fields
yield [... | 50,352 |
def range_end_at_current():
"""set playback range end to current frame"""
current_frame = pm.currentTime(q=True)
pm.playbackOptions(min=current_frame) | 50,353 |
def test_invalid_period():
"""Test the invalid period."""
null_per = _period(5, 1)
assert not null_per.is_before(_datetime(7))
assert not null_per.is_after(_datetime(7))
assert not null_per.is_before(_datetime(-5))
assert not null_per.is_after(_datetime(-5))
assert null_per.is_null()
a... | 50,354 |
def make_func_entry(func, name=None, description=None, params=None):
"""
Create a function docstring entry for a swig interface file.
func - a doxyxml object from which documentation will be extracted.
name - the name of the C object (defaults to func.name())
description - if this optional variable is ... | 50,355 |
def test_scale_video_cuda():
"""
测试视频缩放
:return:
"""
print('')
h264_obj = H264Video(constval.VIDEO, constval.OUTPUT_DIR, aio=False)
assert not hasattr(h264_obj, 'cmd_do_aio')
print('current work dir', os.path.abspath(os.getcwd()))
home_dir = os.path.abspath(os.getenv('HOME'))
sca... | 50,356 |
def test_lists_with_newline(mocker):
"""Test list rendering with a newline between a new nested list and the
previous list item
"""
import lookatme.widgets.table
mocker.patch.object(lookatme.config, "LOG")
fake_config = mocker.patch.object(lookatme.render.markdown_block, "config")
mocker.pa... | 50,357 |
def instance_update(context, instance_uuid, values, session=None):
"""Updates an existing VM instance in the Database"""
values = copy.deepcopy(values)
power_specs = values.pop('power_specs', None)
#Merge in the existing MetaData if they asked for Partial Updates
_instance_merge_metadata(context, in... | 50,358 |
def _cmd_7zip_list(src) -> bytes:
"""获取列表"""
p = subprocess.run(["7z", "l", "-ba", src, "-p"], capture_output=True, timeout=1)
return p.stdout or p.stderr | 50,359 |
def xkcdt():
"""
Return the title of the
most recent xkcd, taken from
the wesite's source code.
"""
page=BeautifulSoup(urllib2.urlopen('https://xkcd.com'),'lxml')
return page.title.string | 50,360 |
def test_rate_limiters_api_config(test_microvm_with_api):
"""
Test the IO rate limiter API config.
@type: functional
"""
test_microvm = test_microvm_with_api
test_microvm.spawn()
# Test the DRIVE rate limiting API.
# Test drive with bw rate-limiting.
fs1 = drive_tools.FilesystemFi... | 50,361 |
def ticks_cpu() -> Any:
"""
Similar to `ticks_ms()` and `ticks_us()`, but with the highest possible resolution
in the system. This is usually CPU clocks, and that's why the function is named that
way. But it doesn't have to be a CPU clock, some other timing source available in a
system (e.g. high-re... | 50,362 |
def log_cpm_hvg(adata: ad.AnnData, n_genes: int = 1000) -> ad.AnnData:
"""Normalize logCPM HVG
Normalize data to log counts per million and select n_genes highly
variable genes
"""
adata = log_cpm(adata)
if adata.n_vars < n_genes:
warnings.warn(
f"Less than {n_genes} genes... | 50,363 |
def test_dirname(arg, kw, exp):
"""
Test tbx.dirname()
"""
pytest.dbgfunc()
assert tbx.dirname(*arg, **kw) == exp | 50,364 |
def c_string_arguments(encoding='UTF-8', *strings):
""" Convenience function intended to be passed to in_format which allows
easy arguments which are lists of null-terminated strings.
"""
payload = b""
# Add each string, followed by a null character.
for string in strings:
payload ... | 50,365 |
async def create_mirror(request):
"""
Create a debian aptly mirror.
---
description: Create a debian aptly mirror.
tags:
- Mirrors
consumes:
- application/x-www-form-urlencoded
parameters:
- name: name
in: query
required: true
type: stri... | 50,366 |
def dict_to_fields(embed: Embed,
fields: Dict[str, str],
inline: bool = False) -> None:
"""
Iterates through dict keys and appends them to the embed fields
Args:
embed: Embed instance
fields (dict): each key, value pair will be set as an independent fiel... | 50,367 |
def anneal(c_max, step, iteration_threshold):
"""Anneal function for anneal_vae (https://arxiv.org/abs/1804.03599).
Args:
c_max: Maximum capacity.
step: Current step.
iteration_threshold: How many iterations to reach c_max.
Returns:
Capacity annealed linearly until c_max.
"""
... | 50,368 |
def test_compose_crane(env):
"""Create a new type crane, based on existing components"""
Crane = type("Crane", (core.Identifiable, core.HasContainer), {})
Crane(name="my crane", env=env, capacity=3) | 50,369 |
def update_timer_interval(acq_state, chart_data_json_str, chart_info_json_str,
active_channels, samples_to_display):
"""
A callback function to update the timer interval. The timer is temporarily
disabled while processing data by setting the interval to 1 day and then
re-enabl... | 50,370 |
def constant_change_luminance(img):
"""
luminance noise added to image
:param img: image: numpy input image
:return: blurred image
"""
# constant [-25, 25]
constant = np.random.randint(-25, 25, size=(img.shape[0], img.shape[1], 1))
new_img = np.clip(img.astype(np.float32) - constant, 0.0... | 50,371 |
def test_overlapping_affirm_denied_fail(plus, minus):
""" Test overlapping affirm and denied flags raise error """
with pytest.raises(ContextsConflict):
MessageTrustContext(plus, minus) | 50,372 |
def rectify(x):
"""Rectify activation function :math:`\\varphi(x) = \\max(0, x)`
Parameters
----------
x : float32
The activation (the summed, weighted input of a neuron).
Returns
-------
float32
The output of the rectify function applied to the activation.
"""
# Th... | 50,373 |
def main():
"""Read input and print output"""
while True:
try:
text = input()
except EOFError:
break
platin = []
for word in text.split():
if word[0] in 'aeiouy':
platin.append(word + 'yay')
else:
i... | 50,374 |
def p_SubNode(p):
"""
SubNode : ModNode
| ModNode RelationDisj
| '(' SubNode ')'
| '(' SubNode ')' RelationDisj
"""
if len(p) == 2:
p[0] = p[1]
elif len(p) == 3:
conj_patterns = []
for relation_conj in p[2][1]:
conj_patterns.ap... | 50,375 |
async def test_flow_unknown_abort(opp):
"""Test flow with unknown error abortion."""
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["step_id"] == "user"
with patch(
"open... | 50,376 |
def _prev_mpl(cmap, cmap_name):
"""Preview a colourmap using matplotlib.
Args:
cmap (list): The colour map you want to preview. This must be
a Python list of rgb/rgba/hex values.
cmap_name (str): The name of the matplotlib colour map.
For example: (Blues, OrRd, winter, ... | 50,377 |
def login_form():
"""Show login form."""
return render_template("login_form.html", loggingin=True) | 50,378 |
def create_backup_options(logsync, dbs, logger):
"""
Creates the backup options string to be used in restore.sh script for source backup
Args:
logsync (string) : Are we enabling replication?
dbs (string): Which databases are we backing up?
Returns:
backup_options (string): Compl... | 50,379 |
def truncate_batches(*xl: Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]) \
-> Sequence[Union[dy.Expression, Batch, Mask, recurrent.UniLSTMState]]:
"""
Truncate a list of batched items so that all items have the batch size of the input with the smallest batch size.
Inputs can be of various typ... | 50,380 |
def get_loss_f(**kwargs_parse):
"""Return the loss function given the argparse arguments."""
return Loss(lamL1attr=kwargs_parse["lamL1attr"]) | 50,381 |
def _add_cromwell_status_args(parser: argparse.ArgumentParser):
"""Add cli args for checking status of Cromwell workflow"""
parser.add_argument('workflow_id')
parser.add_argument('--json-output', help='Output metadata to this path')
_add_generic_cromwell_visualiser_args(parser)
return parser | 50,382 |
def input_reading_mod(input_dir, input):
"""This helper convert input"""
with open('%s/%s' %(input_dir, input), 'r') as input_fid:
pred = input_fid.readlines()
det = [x.strip('\n') for x in pred]
return det | 50,383 |
def test_hand_made_graph():
# Graph
"""
2 5
/ \ / \
1 4 7
\ / \ /
3 6
"""
# Generate the graph with its capacities
# Note the below graph doesn't follow the rule used in mvdp.py for making v_in and v_out
g = ig.Graph(
14,
[(101, 1... | 50,384 |
async def connect(config, loop, protocol=None, session=None):
"""Connect and logins to an Apple TV."""
if config.identifier is None:
raise exceptions.DeviceIdMissingError("no device identifier")
service = config.main_service(protocol=protocol)
supported_implementations = {
const.PROTOC... | 50,385 |
def buildTranscriptomeIndex(inputs, outputs):
"""
Build index for Bowtie2 from reference files
"""
genomeRef, geneRef = inputs
index, flagFile = outputs
tmp_dir = "%s/tmp" % output_dir
if not os.path.exists(tmp_dir):
mkDir(tmp_dir)
transcriptome_index = "%s/known" % transcriptome... | 50,386 |
def _is_none(s: str) -> bool:
"""Check if a value is a text None."""
if s == 'None':
return True
return False | 50,387 |
def get_C_and_Ic(Cin_est, Icin_est, f01, f02on2):
"""Get the capacitance and critical current for a transmon of a certain
frequency and anharmonicity.
Args:
Cin_est (float): Initial guess for capacitance (in fF)
Icin_est (float): Initial guess for critical current (in nA)
f01 (float... | 50,388 |
def read_positionfixes_postgis(sql, con, geom_col="geom", **kwargs):
"""Reads positionfixes from a PostGIS database.
Parameters
----------
sql : str
SQL query e.g. "SELECT * FROM positionfixes"
con : str, sqlalchemy.engine.Connection or sqlalchemy.engine.Engine
Connection string or... | 50,389 |
def comp_pattern_generator(iterable):
""" Converts a list of MIDI notes to (length, notes) tuples in a jazzy pattern. """
for chord in iterable:
yield (600, chord)
yield (300, chord[0:1])
yield (300, chord)
yield (600, chord[0:1])
yield (300, chord)
yield ... | 50,390 |
def get_model(letters, max_length):
"""Create a LSTM model."""
logging.info("Create model")
input_dim = len(letters)
logging.info("input_dim=%i", input_dim)
model = Sequential()
model.add(LSTM(8,
return_sequences=True,
input_shape=(max_length, len(letters)))... | 50,391 |
def attempt(task): # pragma: no cover
"""Offer the user a single task to perform."""
ui = UI()
clock = time
t = Task(task)
wantToAttempt = ui.offerTask(task)
if not wantToAttempt:
# TODO: Do something with `reason`.
reason = ui.requestReasonForDeferral(task)
return t.de... | 50,392 |
def to_json(mystr):
"""
Translate a string representation of a Bloomberg Open API Request/Response
into a JSON string
Parameters
----------
mystr: str
A string representation of one or more blpapi.request.Request or
blp.message.Message, these should be '\\n' seperated
"""
... | 50,393 |
def _group_auto_update_helper(auto_update):
"""Helper that prepares the given group auto update for JSON
serialization.
:param GroupAutoUpdate auto_update: the auto update to serialize
:return: dictionary suitable for JSON serialization
:rtype: dict
"""
fields = {
'to': auto_upda... | 50,394 |
def test_start_line_second(sample_log_lines):
"""Test incremented time in second start line."""
line1 = sample_log_lines.start_line()
line2 = sample_log_lines.start_line()
assert line2 == "2019-03-04 06:01:53,454 - INFO - meetup2xibo - Start meetup2xibo 2.0.1" | 50,395 |
def test_get_head_with_new_puzzle_returns_head():
"""Verifies that `get_head` on a completely unsolved puzzle returns a head."""
grid = Grid(((3, -1, -1), (-1, 2, -1), (0, -1, -1)))
assert has_head(grid)
assert get_head(grid).location == (0, 0) | 50,396 |
def define_service_to_ingress_relationships(resource_cache: Dict, ingress_controller: Text) -> None:
"""
Defines the upstream ext.relationship from a Service to the ingress kind supported by the ingress controller.
:param resource_cache: The dictionary of resources gathered from the k8s deployment.
:pa... | 50,397 |
def make_diag_scale(loc, scale_diag, scale_identity_multiplier,
validate_args, assert_positive, name=None):
"""Creates a LinOp from `scale_diag`, `scale_identity_multiplier` kwargs."""
def _convert_to_tensor(x, name):
return None if x is None else ops.convert_to_tensor(x, name=name)
def _... | 50,398 |
def emd(hist1, hist2, cost_matrix='sift'):
"""
earth mover's distance by robjects(lpSovle::lp.transport)
require: lpsolve55-5.5.0.9.win32-py2.7.exe
CommandLine:
python -m vtool.distance --test-emd
Example:
>>> # DISABLE_DOCTEST
>>> from vtool.distance import * # NOQA
... | 50,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.