content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def _velocity_factor(velocity_units_in: str, velocity_units_out: str) -> float:
"""helper method for convert_velocity"""
factor = 1.0
if velocity_units_in == 'm/s':
factor /= 0.3048
elif velocity_units_in == 'ft/s':
pass
elif velocity_units_in == 'in/s':
factor /= 12.
eli... | 6f2acab5bf14c61f44ac4c2a260d9d367462a5a1 | 49,852 |
def submit_notable(service, notable, num_enrichment_events):
""" Submits fetched notable to Splunk for an Enrichment. Three enrichments possible: Drilldown, Asset & Identity.
If all enrichment type executions were unsuccessful, creates a regular incident, Otherwise updates the
integration context for the ... | 50b76cdb23949d91726ef1c40a17c45f8e8acd22 | 49,853 |
def avoid_my_body(my_body, possible_moves):
"""
my_body: List of dictionaries of x/y coordinates for every segment of a Battlesnake.
e.g. [ {"x": 0, "y": 0}, {"x": 1, "y": 0}, {"x": 2, "y": 0} ]
possible_moves: List of strings. Moves to pick from.
e.g. ["up", "down", "left", "right"]... | cbb7b41b32d8acb84262ab346c19d5f736e4d8a6 | 49,854 |
import torch
def image_grid(img, row, col):
"""
img: N,h,w,x
collage: 1,.., x
"""
bs,h,w,c=img.shape
device = img.device
collage = torch.zeros(h*row, w*col, c).to(device)
for i in range(row):
for j in range(col):
collage[i*h:(i+1)*h,j*w:(j+1)*w] = img[i*col+j]
... | 3a5ee47ca5bbc652e3882be2d3c54fc572d670eb | 49,855 |
def sautMini(group1, group2):
"""Critère du saut minimal"""
mini = float("inf")
for e in group1:
for t in group2:
dist = distanceEucl(e,t)
if dist < mini:
mini = dist
return mini | 9a3e5f03c09a707f7e82f40388d39c5988fa5761 | 49,856 |
import time
def main():
"""Main program entry."""
"""Maybe add two minute delay before code starts to allow Alchol sensor to heat up to adequate temperature"""
# add a heading to each data entry into API
with open("data.csv", "w") as fp:
# adds a set heading
fp.write("alcohol concent... | 28f055e083859c28756e3e8d35158f4fc94864da | 49,857 |
import logging
def get_optimal_threshold(y_true,
y_prob,
grid_spacing=0.01,
verbose=False):
"""For probabilities, find optimal threshold according to f1 score.
For a set of groud truth labels and predicted probabilities of these la... | 561ddfbf9ad0f5213b1f258a2701fc1efbaf8ec7 | 49,858 |
import logging
def contour_dem(dem_fp, raster_band=1, min_val=None, max_val=None, method='basic', contour_interval=None,
n_contours=None, contour_list=None, bbox=None, output_format='features', logger=None):
"""Contour the DEM using one of two approaches, export geojson.
:param dem_fp: the fi... | f838e42125e4a856d632672658f79b13ce32fc4e | 49,859 |
def apply_style_transfer(content_uri:str, style_uri:str) -> str:
"""
Applies the style transfer effect to provided images.
Returns base64 image representation.
"""
content_image = decode_image(content_uri)
content_image = process_image(content_image)
style_image = decode_image(style_uri)
... | 162a485ec367a110d920f0291432e41d0892094f | 49,860 |
from typing import Optional
def get_metadata(order_id: str) -> Optional[dict]:
"""
Retrieve metadata for an order
"""
res = table.get_item(Key={
"orderId": order_id,
"productId": METADATA_KEY
})
return res.get("Item", None) | 5470ed460cb7e586ae6d8e0c6d4ac7f9da2a58d6 | 49,861 |
def SearchFetchable(session=None, **kwargs):
"""Search okcupid.com with the given parameters. Parameters are
registered to this function through
:meth:`~okcupyd.filter.Filters.register_filter_builder` of
:data:`~okcupyd.json_search.search_filters`.
:returns: A :class:`~okcupyd.util.fetchable.Fetcha... | 6f9e1eb8f703b651c7a64958feef5249e58b55e9 | 49,862 |
def getChildrenByName(rootNode, name):
"""Returns all child nodes of a specified name.
"""
return [e for e in rootNode.childNodes if e.localName == name] | 77b1f7c7c4760cd940c39d30a2d4850b2ca3c147 | 49,863 |
import ipaddress
def tcp_traceflow(packet):
"""Trace packet flow for TCP.
Args:
packet (pyshark.packet.packet.Packet): Scapy packet.
Returns:
Tuple[bool, Dict[str, Any]]: A tuple of data for TCP reassembly.
* If the ``packet`` can be used for TCP flow tracing. A packet can be re... | 4923ca7019de16a1dd2d1717b0e42abaf708ddd8 | 49,864 |
def protocols_with_string(string):
"""Return a list of protocols matching given string."""
# Normalize string
while "//" in string:
string = string.replace("//", "/")
string = string.strip("/")
if not string:
return []
ret = []
for name in string.split("/"):
ret.appe... | 307eff482819ac287accf80f964f0b4593eee63b | 49,866 |
def percentage(value, precision=2):
"""Convert `float` to #.##% notation as `str`.
A value of 1 = `"100.00%"`; 0.5 = `"50.00%"`"""
return f"{value:.{precision}%}" | 7abd3fafa8fc6f8323ca448ff5022faa0f83aa60 | 49,867 |
import re
def simbadnames(query):
"""Given a source name, or other SIMBAD query, generates a list of identifier matches
See http://simbad.u-strasbg.fr/simbad/sim-fscript
"""
u = urlopen(
"""http://simbad.u-strasbg.fr/simbad/sim-script?submit=submit+script&script=format+object+%%22+%%25IDLIS... | ef9500c8e5e07638482570644e350c3799fb0927 | 49,868 |
import inspect
import functools
def decorator(func):
"""
Glossy Decorator
This decorator can be used to make your decorators glossy.
It simplifies the creation of decorators by flattening their
structure and reducing the number of wrapper functions required.
It also adds some additional attri... | e2bce4f8fd07aaa51b8dc8b7ad1182ecc861a26d | 49,869 |
import math
def compute_cohen(participant_ids):
"""
"""
k_tot = []
for co in combinations(participant_ids, 2):
k = cohen_kappa_score(df_feedback.iloc[co[0]],
df_feedback.iloc[co[1]])
if math.isnan(k):
k=1
k_tot.append(k)
c_k = np.... | 4552f359536a5e965b355e76bf017954bedbfea5 | 49,870 |
import re
def findAlphanumeric(line):
"""Parse string to extract all non-numeric strings"""
return re.findall(r'^\w+', line) | 7ac210f35d347532ff9e68b4fd6f6f978b0c61ea | 49,871 |
import urllib
import aiohttp
async def _get_username_password(registry_name: str) -> UsernamePassword:
"""
Gets the UsernamePassword for logging into the meadowrun-managed Azure container
registry. Can be passed to functions in docker_controller.py
"""
# https://github.com/Azure/azure-cli/blob/28... | 3fb4285dadf2d4b169a649ae5af703b009e14896 | 49,874 |
def rep(data):
"""Checks if all labels are represented
in the dataset `data`."""
labels = [0, 1]
# Iteratively check if all labels are represented
for i in range(len(data) - 1):
row = data[i]
label = row["label"]
contains = label in labels
if contains and labels:
... | 803c561c48fec10c44154138e83e95405054dad5 | 49,875 |
import logging
def main(global_config, **settings):
""" This function returns a Pyramid WSGI application.
"""
# support logging in python3
logging.config.fileConfig(
settings['logging.config'],
disable_existing_loggers=False
)
config = Configurator(settings=settings)
conf... | 594f75fe6dfb361fa82f20a670a3cacfb7992f0a | 49,876 |
import re
def quota_size(value):
"""
Covnert a human readable quota size into a number of bytes.
"""
_UNITS_RE = re.compile('^\s*(?P<value>\d+(\.(\d*)?)?)\s*(?P<scale>[kMGTP]i?)?B?$')
_UNITS_SCALES = {None: 1,
'k' : 1000, 'ki': 1024,
'M' : 1000**2,... | fa464aa6a87fa36ed32ca9506d0a5fa4c6474d6d | 49,878 |
def register_project():
"""Register a project at Conductor service if not done already.
The function checks all projects in the users config file and if
a project does not have an id already it will try register it
at the specified Conductor Service.
"""
registration_id = request.json["id"]
... | 0ba3c216a2b9181007f6d1c101166fee69caa15d | 49,879 |
import logging
def snow_and_ndsi_locations(src_info, no_data_value):
"""Generate Landsat snow locations and NDSI nodata locations
Args:
src_info <SourceInfo>: Information about the source data
no_data_value <int>: No data (fill) value to use
Returns:
list(<int>): Locations where ... | d4a86cb2361d3ccca95e9317567b3fe98408aa3f | 49,880 |
def compute_cov(tensor, tensor_right=None, normalizer=None):
"""Compute the empirical second moment of the rows of a 2D Tensor.
This function is meant to be applied to random matrices for which the true row
mean is zero, so that the true second moment equals the true covariance.
Args:
tensor: A 2D Tensor.... | d86464a0bfb9c064f075f799586967ee56aae08f | 49,881 |
from typing import Optional
from typing import Any
def parametrize_filebased(abspath: Optional[str], filename: str, relpath: Optional[str]) -> Any:
"""
Converts a target json file as a source of parameters for pytest.
:param abspath: Absolute path of the json file
:param filename: Name of the json fil... | 2503c5bcd590114f23b09e4884b1dc8947f4ac94 | 49,882 |
from typing import Optional
def hexbin_viz(
df: pd.DataFrame,
x: str,
y: str,
plot_width: int,
plot_height: int,
tile_size: Optional[float] = None,
) -> Panel:
"""
Render a hexbin plot
"""
# pylint: disable=too-many-arguments,too-many-locals
xmin, xmax = df[x].min(), df[x].... | 1e97d2f482806e09a09f43289297a2c696a1cc36 | 49,883 |
def _func_if(args, is_differentscenario, line, pos):
"""args[0]がTrueであればargs[1]を、そうでなければargs[2]を返す。"""
_chk_argscount(args, 3, "IF", line, pos)
a = args[0]
_chk_boolean(a, "IF", 0)
t = args[1]
f = args[2]
return t if a.value else f | abeefa1707dfda41b438eb1b42c0be65932e8a02 | 49,884 |
def profiler(output_file=None, sort_by='cumulative', lines_to_print=None, strip_dirs=False):
"""
A time profiler decorator
:param str output_file: Path of the output file. If only name of the file is given,
it's saved in the current directory. If it's None, the name
... | 7b4314569e03ad1b929cfd0f72534dcf90598730 | 49,885 |
def find_overlapping_annotations(m, annotations):
"""Takes a markup object and a df of annotations from the same report"""
def overlaps(m_span, a_span):
m_span = [int(n) for n in m_span]
a_span = [int(n) for n in a_span]
#print(m_span, a_span)
overlap = ((a_span[0] <= m_span[0] <... | 7cc95cd8ecf7403c84a800f502364384ed208199 | 49,886 |
import math
def _is_prime_bruteforce(prime):
"""Check if a number is prime using brute force and some caching.
Our brute force method is a little smarter than the standard method,
as we rule some factors out due to the following principles:
1) We already have a list of cached primes. If our supposed ... | 60abdadb0b846deb3a1f4c861193d2b6ed42461d | 49,887 |
from typing import Union
def encode(data: Union[bytes, dict, int, list]) -> bytes:
"""Convert the given Python object to a bencoded string.
Raises:
ValueError: If the provided object type is not supported
Returns:
A bencoded string
"""
if isinstance(data, bytes):
return _... | b3aadafa9d9bb00283a5f5e6fa00378c3026def3 | 49,888 |
import torch
def match_grasp_view_and_label(end_points):
""" Slice grasp labels according to predicted views. """
top_view_inds = end_points['grasp_top_view_inds'] # (B, Ns)
template_views_rot = end_points['batch_grasp_view_rot'] # (B, Ns, V, 3, 3)
grasp_labels = end_points['batch_grasp_label'] # (B, ... | ca26ba32bca1c196b43a6197ad13cd5c5ffb2a71 | 49,889 |
def execute_blueprint(cli, blueprint, repo_info, logger=None):
"""
Execute a blueprint
"""
if logger is None:
logger = j.logger.logging
errors = []
logger.info('Executing blueprint [{}]'.format(blueprint))
try:
res, ok = check_status_code(cli.executeBlueprint(data={}, bluep... | 596a64e1c71d9b4411610cdba1aaa9fb8c6ab444 | 49,890 |
def convert_meshio(
mesh,
ignore_unknown=False,
import_dim=(1, 2, 3),
element_id_name="element_id",
material_id_name="material_id",
):
"""
Convert points and cells from meshio to ogs format.
Parameters
----------
mesh : meshio mesh class
The given mesh by meshio
igno... | a77bc912776ca0c9dbf1194c22de43b4ffcd6121 | 49,891 |
def get_data(path_imgs,path_masks,axis=0,
batch=50,buffer_size=300,
size_crop=160,random_crop=False,
augmentation=False,repeat=1,
pixels=0,cache=True,
):
""" Returns dataset already preprocessed
"""
data = tf.data.Dataset.from_generator(gener... | 5e0c976d240783e0477e6cda649f75a77d4d332e | 49,892 |
import numbers
def torch_item(x):
"""
Like ``x.item()`` for a :class:`~torch.Tensor`, but also works with numbers.
"""
return x if isinstance(x, numbers.Number) else x.item() | dae9881c21a305b42e5c488723a88beb117bf90f | 49,893 |
def small_world_random(G):
""" Compute the average clustering coefficient and average shortest path
length of a random network with the same number of nodes and edges as G
Parameters
----------
G: Network X undirected graph
Returns
-------
C: float
the random network cluste... | 3e118e5da58492c1ac7b968802c4cbb79cd73270 | 49,894 |
def count(grid, c):
"""
Count the occurrences
of an object "c" in
the 2D list "grid".
"""
acc = 0
for row in grid:
for elem in row:
acc += c == elem
return acc | 6a497b5d052ce8e1d2619f2278010ecd41126a42 | 49,895 |
def strictly_upper_triangle(m):
"""
Returns a matrix containing the strictly upper triangle of m and zeros elsewhere.
"""
l = _np.shape(m)[0]
out = m.copy()
for i in range(0, l):
for j in range(0, i + 1):
out[i, j] = 0
return out | 5f8f0a5d9f81fa5fc202f4541a2948cad6892cd3 | 49,896 |
def config_retry_strategy(retry):
"""Generate retry strategy."""
if not isinstance(retry, int):
raise ValueError("Parameter retry should be a number")
return {"limit": retry, "retryPolicy": "Always"} | cb436261391e57e845ac5019c7906a56edc2db64 | 49,897 |
def isomap_transform(data_scaled, labels) :
"""Compute the Isomap transform from a scaled data.
Parameters
----------
data_scaled : numpy.ndarray
A matrix with the scaled data to transform
labels : numpy.ndarray
Labels to assign to the transformed data (0 for real and 1 for sy... | 2caae82611bbab244376d7cea0b4f5181b516691 | 49,898 |
def call_solver(matvec, matvec_args, hI, params, x0, tol):
"""
Code used by both solve_for_RH and solve_for_LH to call the
sparse solver. Solves matvec(*matvec_args, x) = hI for x.
PARAMETERS
----------
matvec (jax.tree_util.Partial): A function implementing the linear
... | 4b0a701b127335c9fcccd350a5b1f37e07661d0d | 49,899 |
def vertex_score(timeseries):
"""
A timeseries is anomalous if vertex score in hypergraph is greater than average score of observed anomalous vertex.
:return: True or False
"""
if vertex_centers.shape[0] <= 1:
update_vertex_param()
timeseries = np.array(timeseries)
test_data = timese... | 34995fe774dafd1b830875234b60680d5148bcdb | 49,900 |
def emergency_contact_list(request):
""" Renders emergency contact info page """
brothers = Brother.objects.exclude(brother_status='2').order_by("last_name")
context = {
'brothers': brothers,
}
return render(request, 'emergency-contact-list.html', context) | d9388ff409b61ab4bf9ba97b9221680e6e59be43 | 49,901 |
def create_user_records_bp(app):
"""Create user records blueprint."""
ext = app.extensions["invenio-rdm-records"]
return ext.user_records_resource.as_blueprint(
"bibliographic_user_records_resource"
) | 433f1d3681f8dc4dda36d38259085b59a3ab7b1b | 49,903 |
from typing import Any
import ctypes
def make_create_dataframe(
col_names: Any,
K: RuntimeTypeDescriptor = None
) -> Transformation:
"""Make a Transformation that constructs a dataframe from a Vec<Vec<String>>.
:param col_names: Column names for each record entry.
:type col_names: Any
:pa... | c885d984d98188489a25ba9a261b9d9aab946386 | 49,904 |
def filter_entropy(np_img, neighborhood=9, threshold=5, output_type="uint8"):
"""
Filter image based on entropy (complexity).
Args:
np_img: Image as a NumPy array.
neighborhood: Neighborhood size (defines height and width of 2D array of 1's).
threshold: Threshold value.
output_type:... | 5a067530172f0c7bec49f5d84d58ecf764e01e43 | 49,907 |
def getTechniqueData(technique=None):
"""
Returns injection data for technique specified
"""
return kb.injection.data.get(technique) | 99978be6985e49b69f4b4d2cd0376c6987f287ac | 49,909 |
import json
from datetime import datetime
def _deserialize_video(json_text):
""" Parses JSON and deserializes it into a list of YouTubeResult objects. """
results = []
parsed_json = json.loads(json_text)
items = parsed_json["items"]
for item in items:
result = YouTubeResult()
... | ba1f4d3d0afb7edca0d52a472f54be6b4db2c2ba | 49,910 |
def interval(lower_, upper_):
"""Build an interval."""
if lower_ <= upper_:
return lower_, upper_
return None | 3dd1b0c04c9cad8e5f8a69e5c348f07a7542fe7b | 49,911 |
import logging
def _parse_amiga_props(amiga_props, offset_x):
"""Convert AmigaFont properties into yaff properties."""
if amiga_props.tf_Style & _FSF_COLORFONT:
raise ValueError('Amiga ColorFont not supported')
props = {}
# preserve tags stored in name field after \0
name, *tags = amiga_pr... | d279f2525f1b0eb75d04dc1cdbc09db472cf71c2 | 49,913 |
import torch
import copy
def flow_to_trafo_PnP(*args, **kwargs):
"""
input:
real_br: torch.tensor torch.Size([2])
real_tl: torch.tensor torch.Size([2])
ren_br: torch.tensor torch.Size([2])
ren_tl: torch.tensor torch.Size([2])
flow_mask: torch.Size([480, 640])
u_map: torch.S... | 245e396b4c9096340e29394a31357cc8e5aa7727 | 49,914 |
def Ha_plot(ax):
"""Plot the Ha line and bandpass."""
ax.axvspan(Ha - 0.678, Ha + 0.678, color='tab:blue', alpha=.5)
ax.axvspan(6545.495, 6556.245, color='tab:blue', alpha=.5)
ax.axvspan(6575.934, 6584.684, color='tab:blue', alpha=.5)
ax.axvline(Ha, color='red', ls='dashed')
ax.set_xlim(6544.49... | 8c29b093c4c1b101fe0fc720a936a4b9f9b80882 | 49,915 |
def ikev2scan(ip, **kwargs):
"""Send a IKEv2 SA to an IP and wait for answers."""
return sr(IP(dst=ip) / UDP() / IKEv2(init_SPI=RandString(8),
exch_type=34) / IKEv2_payload_SA(prop=IKEv2_payload_Proposal()), **kwargs) | 30a999d0da7ea62e10e333e4bfceea28447f19f4 | 49,916 |
def usb_get_strings(*args):
"""
usb_get_strings(context, device) -> (return_code, manufacturer, description, serial)
Return device ID strings from the usb device.
The parameters manufacturer, description and serial may be NULL or
pointer to buffers to store the fetched strings.
Use this fun... | 515844cc5651d5121ab09b3adee53f2f03b586be | 49,917 |
def set_avatar_url():
"""
设置用户头像信息
1. 获取参数,avatar, user_id,request.filter.get('avatar')
2. 检验参数存在
3. 读取图片数据,data= avatar.read()
4. 调用七牛云接口,上传用户头像
5. 保存用户头像信息到数据库
6. 拼接用户头像图片的完整路径,七牛云外链域名+图片文件名
7. 返回结果
:return:
"""
# 获取参数
user_id = g.user_id
avatar = request.files... | 8523bcbcaef28368fed14c84a3a4705d654eb4cb | 49,918 |
def fetch_links(html):
"""
Fetch all links on a given page and return their hrefs in a list
"""
elements = html.cssselect('a')
return [e.get('href') for e in elements if e.get('href') is not None] | f97f610e5baeb3e3b304c3093a5e27fc0b8de551 | 49,920 |
def isolines_style(value=RANGE_LABEL_KEY, top=11, cat=None, palette='pinkyl', size=None, opacity=0.8,
stroke_color='rgba(150,150,150,0.4)', stroke_width=None):
"""Helper function for quickly creating an isolines style.
Based on the color category style.
Args:
value (str, optional... | 889ed4543152ea197448a301c8be49d04ebc2ecf | 49,921 |
import requests
def nlp_answer(question: str = "人工智能") -> str:
"""
智能问答
https://ownthink.com/robot.html
:param question: word in chinese
:type question: str
:return: indicator data
:rtype: list or dict or pandas.DataFrame
"""
url = 'https://api.ownthink.com/bot'
params = {
... | 4947917c54862dd0bf38706c8091573e177c8b7c | 49,923 |
def load_eia861_state_total_sales(
pudl_out: pudl.output.pudltabl.PudlTabl
) -> pd.DataFrame:
"""
Read and format EIA 861 sales by state and year.
Args:
pudl_out: Used to access
:meth:`pudl.output.pudltabl.PudlTabl.sales_eia861`.
Returns:
Dataframe with columns `state_id_... | 5e40bfafcda31285583e50e5f4c66006635d1f8b | 49,924 |
def echo_handler(ex, *args, **kwargs):
"""
Example error handler which echoes the exception and the arguments.
"""
argstring = ','.join(['%s' % arg for arg in args])
return '%s/%s/%s' % (ex.message, argstring, kwargs) | 29ca4f7663e9c3bf1893bf3f4ab84c8744827ec3 | 49,925 |
def find_media(args, src_api, dest_api, dest_project):
""" Finds existing media in destination project. Returns media that need to be created and ID
mapping between source and destination medias.
"""
media = []
media_mapping = {}
if args.skip_media:
logger.info(f"Skipping media due t... | 5289fbda897de9812b07fda38fce8f958f14634b | 49,927 |
def list_host_deployment_info(package_name, environment, version=None,
revision=None, apptypes=None):
"""Give all deployment information for a given package
deployed to hosts for given (or all) application types
and in given environment
"""
dep_info = (Session.qu... | 6f6a1b1800ac2aebf0ec8cce201f1e967fe9c524 | 49,928 |
def _predict(group, model):
"""internal use """
# generate arrays and interpolate components onto the unknown x array
xdat, ydat = get_arrays(group, model.arrayname)
if xdat is None or ydat is None:
raise ValueError("cannot get arrays for arrayname='%s'" % arrayname)
spectra = interp(xdat, ... | 71b5c1d43f2c6d0d9ae3d420b9eb8cf7e4c0f904 | 49,929 |
def computer_quals(predictions, n_alleles):
"""Computes GQ and QUAL values from a set of prediction probabilities."""
## GQ is prob(GQ) / prob(all genotypes)
## GQ is rounded to the nearest integer to comply with the VCF spec
index, gt = get_max_index(predictions, n_alleles)
gq = int(np.around(ptrue... | 25156e145a48e39d5d397bf3b1c415bf1188a557 | 49,930 |
from typing import OrderedDict
def parse_surveyvars_spss(spss_file, lgr=logger):
"""Extracts dat metadata from CDC YRBS SPSS files
Extracts the survey questions and responses from the
CDC YRBS SPSS file.
Args:
spss_file: SPSS file path
Returns:
survey_vars: an OrderedDict with s... | 0615f44121e7e04e78741cd8e6a7d95a96317568 | 49,931 |
from typing import Type
def false_only(t: Type) -> ProperType:
"""
Restricted version of t with only False-ish values
"""
t = get_proper_type(t)
if not t.can_be_false:
if state.strict_optional:
# All values of t are True-ish, so there are no false values in it
retu... | e04510724636db35c347d817fbadef01dfd8da70 | 49,932 |
def make_timevect(num, step, start=0.0, dtype=None):
"""
Return a linearly spaced time vector.
Remark: using this method is preferable to ``numpy.arange(start, start + num * step, step``
which may yield an incorrect number of samples due to numerical inaccuracy.
Parameters
----------
num :... | bc417bb09323f1b8a70c4a8665cab5cc79fda799 | 49,933 |
import uuid
def repr_tree(tree, viz, current_node, rec_depth, color_map, parameters):
"""
Represent a subtree on the GraphViz object
Parameters
-----------
tree
Current subtree
viz
GraphViz object
current_node
Father node of the current subtree
rec_depth
... | 02bfa986d85fe3fb2cccc90b7c8c34ce190949b0 | 49,934 |
import typing
def get_object_versions(object_id: int) -> typing.List[Object]:
"""
Returns all versions of an object, sorted from oldest to newest.
:param object_id: the ID of the existing object
:return: the object versions
:raise errors.ObjectDoesNotExistError: when no object with the given
... | dd1a71f8de9cc075238a52d1f2f473870f66add7 | 49,935 |
def _transform_xml(xml, xslt_path):
"""
Converts the xml document from one metadata schema to another
"""
xslt_file = open('{0}/../misc/tools/{1}'.format(ROOT_PATH, xslt_path))
xslt_root = etree.parse(xslt_file)
transform = etree.XSLT(xslt_root)
return transform(xml) | 20562e5e93c49925c00e669a49d40990252113fd | 49,936 |
def load_parser(d):
"""
For loadclass = 'POINTLOAD', 'LINELOAD' or 'AREALOAD'
LINELOAD "B2141" "5F" TYPE "POINTF" DIR "GRAV" LC "LL_0.5" FVAL 15 RDIST 0.4
LINELOAD "B2109" "6F" TYPE "UNIFF" DIR "GRAV" LC "DL" FVAL 0.7
LINELOAD "C7" "GF" TYPE "TEMP" LC "THN" T -10
AREALO... | 0562dad9dbf82d4b791eed280546a977b07fbad8 | 49,937 |
def neuron_create(num_inputs, activation, bias, layer_id, neuron_id):
"""
Create a neuron.
:param num_inputs: input dimension
:param activation: activation function.
:param bias: bias for this activation.
:param layer_id:
:param neuron_id:
:return:
"""
return {'weights': np.zeros... | de88130876fae85fd60fa167e5f4945d6906e3a7 | 49,938 |
import json
def load_config(config_name):
"""
Loads a json config file and returns a config dictionary.
:param config_name: the path to the config json
"""
with open(config_name) as config_file:
config = json.load(config_file)
return config | 5920d21c67133d2d106863910fdd8db95efc94e6 | 49,939 |
def test_bitext(input_path1, input_path2, output_path1, output_path2):
"""
Test the reconstruction of a bilingual corpus passing it through Tokenizer/Multitext pipeline.
Example:
text.test_bitext('data/en-fr/test.en-fr.en', 'data/en-fr/test.en-fr.fr', 'data/en-fr/test.en-fr.en-bi', 'data/en... | 4210fdd025cfb6fb7db687c32ea7896e1dd6a7ef | 49,941 |
def apply_pca(X, n_pc):
"""
Applying PCA
"""
U, S, V = pca(X)
Z = project_data(X, U, n_pc)
# attempt to recover the original structure (and later render it again):
X_recovered = recover_data(Z, U, n_pc)
return X_recovered | 8934fbb9185d286c21e638ceed592a2df8022c59 | 49,942 |
import json
import urllib3
def get_wordlist():
"""Returns default HarSanitizer wordlist."""
hs = HarSanitizer()
try:
if WORDLIST_PATH[:4] == "http":
wordlist_json = json.loads(urllib3.urlopen(WORDLIST_PATH).read())
wordlist = hs.load_wordlist(wordlist=wordlist_json)
else:
wordlist = h... | 0d46bd460e43b44fa34fae5946611530ea9149e2 | 49,944 |
def load_fraud(n_rows=None, verbose=True):
"""Load credit card fraud dataset.
The fraud dataset can be used for binary classification problems.
Arguments:
n_rows (int): Number of rows from the dataset to return
verbose (bool): Whether to print information about features and labels
... | 6e1bdd3aa2b7f4885e2d1108ce733a7b9140d9a6 | 49,945 |
def args_to_int(args: list) -> tuple:
""" Convert augs to int or return empty """
try:
return tuple([int(i) for i in args])
except ValueError:
return () | 1585e4c80f9637d5b1773e04c92b2f477092dd7a | 49,946 |
from typing import Dict
def update_variables_with_types(*, variables: Dict[VarName, VarDecl], types: Dict[VarName, VarType]) -> Dict[VarName, VarDecl]:
"""
:raises TypingError:
"""
updated: Dict[VarName, VarDecl] = {}
for name, decl in variables.items():
if decl.type is None:
... | d804c83e1c03b8a013655866d8e524925d6efcbc | 49,947 |
import unittest
def suite():
"""A testsuite that has all the Flask tests. You can use this
function to integrate the Flask tests into your own testsuite
in case you want to test that monkeypatches to Flask do not
break it.
"""
setup_path()
suite = unittest.TestSuite()
for other_suite ... | c9a0715cfa580b30e849ee730eb30a7b6c195406 | 49,948 |
def get_tidy_invocation(f, clang_tidy_binary, checks, tmpdir, build_path,
header_filter, extra_arg, extra_arg_before, quiet,
config):
"""Gets a command line for clang-tidy."""
start = [clang_tidy_binary]
if header_filter is not None:
start.append('-hea... | 227664a3045111e4c0c944710e88910dfcf78d13 | 49,949 |
def natsort_key(s, number_type=int, signed=False, exp=False):
"""\
Key to sort strings and numbers naturally, not lexicographically.
It also has basic support for version numbers.
For use in passing to the :py:func:`sorted` builtin or
:py:meth:`sort` attribute of lists.
Use natsort_key just lik... | a07c55d1fcb45dba9a44c00895ee536674b1c1d7 | 49,950 |
import numbers
def _check_sample_weight(sample_weight, X, dtype=None):
"""Validate sample weights.
Note that passing sample_weight=None will output an array of ones.
Therefore, in some cases, you may want to protect the call with:
if sample_weight is not None:
sample_weight = _check_sample_we... | 56de0d9cc91fe1c46f38294ac58d0108c18486ff | 49,951 |
def get_by_name(opname, operators):
"""Return operator class instance by name.
Parameters
----------
opname: str
Name of the sklearn class that belongs to a TPOT operator
operators: list
List of operator classes from operator library
Returns
-------
ret_op_class: class
... | 29692c00ae034c391582ab7dd40a1d728406e73f | 49,952 |
import math
def snrm2(x, dims, mnl = 0):
"""
Returns the norm of a vector in S
"""
return math.sqrt(sdot(x, x, dims, mnl)) | c3ef4e3d23233637fb6969aace06a6db5480e8b8 | 49,953 |
import time
import json
def get_tweets(count = 800, output_file=None,verbose=True):
"""
Pulls Tweets from Authenticated Twitter User
Twitter API maxes out at 800 or input count number
"""
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_TOKEN, ACCESS_TOKE... | 97f23c3c6611f9103caeb0c3b65fd0699116ca88 | 49,954 |
def import_pkg_operation():
"""This function imports the primary package and returns ``True`` when successful."""
return True | e78efc086d7060fd95f1d1da76585c2dbbfcee76 | 49,955 |
def extract():
""" extract data from MongoDB """
# connect mongodb container of the same composer from python
client = pymongo.MongoClient("mongodb")
# get database
db = client.tweets_stream_db
# get collection
collection = db.tweet_stream_json
return collection | 7c3a85ac3238d5eb2f943d1f2112765541b4e760 | 49,956 |
def run_cmd(command, **kwargs):
""" Runs a command and returns an array of its results
:param command: String of a command to run within a shell
:returns: Dictionary with keys relating to the execution's success
"""
cwd = kwargs.get('cwd', None)
try:
ret = check_call(command, shell=Tru... | 21ba41a7fe2a1e889122ee7928350b61e880e330 | 49,957 |
def generate_group_expected_result(group_config) -> dict:
"""Generate expected result for groups"""
expected_result = {
'group_visible': not group_config['ui_options']['invisible'],
'editable': not group_config['read_only'],
"content": group_config['default'],
}
if group_config['... | c48c60f36ff4e370b7da6484e823ebff2d957217 | 49,958 |
def get_sub_text_from_xml_node( xmlnode, _text=None ):
"""
Concatenates the content at and under the given ElementTree node, such as
text = get_sub_text_from_xml_node( xmlnode )
"""
if _text == None:
_text = []
if xmlnode.text:
_text.append( xmlnode.text )
for nd in xm... | 620200d5ba782f5696c720ba4da722204783bd17 | 49,960 |
def group_dates(dates):
"""
Groups list of given days day by day.
:param dates: List of dates to group.
:type dates: list
:return:
"""
days = []
times = []
for elem in dates:
if elem.date() not in days:
days.append(elem.date())
times.append([elem.ti... | 35ff8c2da3e4a27eb065afe630814e29eb06df7d | 49,962 |
def sum_normalization(X, types):
"""
Normalize decision matrix using sum normalization method.
Parameters
----------
X : ndarray
Decision matrix with m alternatives in rows and n criteria in columns
types : ndarray
Criteria types. Profit criteria are represented ... | 7a70e44962e5f15e71d286c971a5b0e3540da23a | 49,963 |
def make_colormap(seq):
"""Return a LinearSegmentedColormap with colors defined as the sequence.
The sequence red to blue can be defined as:
`make_colormap(['red', 'blue'])`
or equivalently
`make_colormap([(1,0,0), 'blue'])`
For more control over color transitions, floats can be included after... | 290315a670b1df6addfa2f04f95bb605d5c4f2ca | 49,964 |
def do_magick_identify(input_file):
"""The different informations of an image.
:param input_file: The input file.
:type input_file: jfscripts._utils.FilePath
:return: A directory with the keys `width`, `height` and `colors`.
:rtype: dict
"""
def _get_by_format(input_file, format):
... | ef982e7c20f5023d0d90bf1dbc51fd82791aaa58 | 49,965 |
def is_asciidoc(path):
"""Returns true if the given path is an Asciidoc file."""
# NOTE: Only checking the extension for now.
if path.endswith(".txt"):
return True
return False | be7fd1994e21b3e540f7bdb6cc7da74753491644 | 49,966 |
def svn_client_args_to_target_array2(*args):
"""
svn_client_args_to_target_array2(apr_getopt_t os, apr_array_header_t known_targets,
svn_client_ctx_t ctx, svn_boolean_t keep_last_origpath_on_truepath_collision,
apr_pool_t pool) -> svn_error_t
"""
return _client.svn_client_args_to_target_ar... | a591462fd26ccd249726d187d6264428883a6383 | 49,967 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.