content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def main():
"""
This file creates a csv file by going through each directory in java_files, placing a specific label for it (1 or 0)
and then writing it to a csv file
"""
current_dir = os.getcwd()
cat_directory = os.path.join(current_dir, 'java_files')
os.chdir(cat_directory)
values = []... | 5,348,700 |
def main():
"""Tools to create, manage and convert M3U and XSPF playlists""" | 5,348,701 |
def assert_almost_equal(
actual: Tuple[numpy.float64, numpy.float64, float, float],
desired: Tuple[numpy.float64, numpy.float64, float, float],
decimal: int,
):
"""
usage.statsmodels: 1
"""
... | 5,348,702 |
def statistical_features(ds, exclude_col_names: list = [],
feature_names=['mean', 'median', 'stddev', 'variance', 'max', 'min', 'skew',
'kurt', 'sqr']):
"""
Compute statistical features.
Args:
ds (DataStream): Windowed/grouped DataStr... | 5,348,703 |
def second_order_difference(t, y):
""" Calculate the second order difference.
Args:
t: ndarray, the list of the three independent variables
y: ndarray, three values of the function at every t
Returns:
double: the second order difference of given points
"""
# claculate the f... | 5,348,704 |
def timeDelay( gpsTime, rightAscension, declination, unit, det1, det2 ):
"""
timeDelay( gpsTime, rightAscension, declination, unit, det1, det2 )
Calculates the time delay in seconds between the detectors
'det1' and 'det2' (e.g. 'H1') for a sky location at (rightAscension
and declination) which must be give... | 5,348,705 |
def RngBinStr(n):
"""
Takes a int which represents the length of the final binary number.
Returns a string which represents a number in binary where each char was randomly generated and has lenght n.
"""
num = ""
for i in range(n):
if rng.random() < 0.5:
num += "0"
el... | 5,348,706 |
def get_bdbox_from_heatmap(heatmap, threshold=0.2, smooth_radius=20):
"""
Function to extract bounding boxes of objects in heatmap
Input :
Heatmap : matrix extracted with GradCAM.
threshold : value defining the values we consider , increasing it increases the size of bounding boxes.
... | 5,348,707 |
def _checkSequenceError(string, start, expected):
"""
Checks that the string starts with the expected sequence number.
Args:
string: write your description
start: write your description
expected: write your description
"""
if not string.startswith(start):
raise Excep... | 5,348,708 |
def get_request(request_id, to_json=False, session=None):
"""
Get a request or raise a NoObject exception.
:param request_id: The id of the request.
:param to_json: return json format.
:param session: The database session in use.
:raises NoObject: If no request is founded.
:returns: Requ... | 5,348,709 |
def gen_multi_correlated(N, n, c_mat, p_arr, use_zscc=False, verify=False, test_sat=False, pack_output=True, print_stat=False):
"""Generate a set of bitstreams that are correlated according to the supplied correlation matrix"""
#Test if the desired parameters are satisfiable
sat_result = corr_sat(N, n, c_m... | 5,348,710 |
def rxzero_traj_eval_grad(parms, t_idx):
"""
Analytical gradient for evaluated trajectory with respect to the log-normal parameters
It is expected to boost the optimization performance when the parameters are high-dimensional...
"""
v_amp_array = np.array([rxzero_vel_amp_eval(parm, t_idx) for parm i... | 5,348,711 |
def exec_geoprocessing_model():
"""算法模型试运行测试
根据算法模型的guid标识,算法模型的输入参数,运行算法模型
---
tags:
- system_manage_api/geoprocessing_model
parameters:
- in: string
name: guid
type: string
required: true
description: 流程模型的guid
- in: array
name... | 5,348,712 |
def perform_extra_url_query(url):
"""Performs a request to the URL supplied
Arguments:
url {string} -- A URL directing to another page of results from the NASA API
Returns:
Response object -- The response received from the NASA API
"""
response = requests.request("GET", url)
c... | 5,348,713 |
def problem_fact_property(fact_type: Type) -> Callable[[Callable[[], List]],
Callable[[], List]]:
"""Specifies that a property on a @planning_solution class is a problem fact.
A problem fact must not change during solving (except through a ProblemFactChang... | 5,348,714 |
def _load_method_arguments(name, argtypes, args):
"""Preload argument values to avoid freeing any intermediate data."""
if not argtypes:
return args
if len(args) != len(argtypes):
raise ValueError(f"{name}: Arguments length does not match argtypes length")
return [
arg if hasattr... | 5,348,715 |
def crash_document_add(key=None):
"""
POST: api/vX/crash/<application_key>
add a crash document by web service
"""
if 'Content-Type' not in request.headers or request.headers['Content-Type'].find('multipart/form-data') < 0:
return jsonify({ 'success': False, 'message': 'input error' })
r... | 5,348,716 |
def log_data(model, action, before, after, instance):
"""Logs mutation signals for Favourite and Category models
Args:
model(str): the target class of the audit-log: favourite or category
action(str): the type of mutation to be logged: create, update, delete
before(dict): the previous v... | 5,348,717 |
def do_train(args):
"""
Train the model using the provided arguments.
"""
# Assumption: it is cheap to store all the data in text form in
# memory (it's only about 144mb)
_, X, y = load_data_raw(args.input)
X_train, y_train, X_val, y_val = split_data(X, y, args.dev_split)
# Assumption:... | 5,348,718 |
def download(url, local_filename, chunk_size=1024 * 10):
"""Download `url` into `local_filename'.
:param url: The URL to download from.
:type url: str
:param local_filename: The local filename to save into.
:type local_filename: str
:param chunk_size: The size to download chunks in bytes (10Kb ... | 5,348,719 |
def local_action_StillOnGroup(arg=None):
"""{"group": "Playback - Group", "schema": {"type": "object", "title": "Args", "properties": {
"group": {"type": "number", "order": 2, "title": "Group"}}}}"""
query = 'G%sST\r' % arg['group']
queue.request(lambda: udp.send(query),
lambda resp: hand... | 5,348,720 |
def main(args=None):
"""Command line interface.
:param list args: command line options (defaults to sys.argv)
:returns: exit code
:rtype: int
"""
parser = ArgumentParser(
prog='baseline',
description='Overwrite script with baseline update.')
parser.add_argument(
'p... | 5,348,721 |
def tokenize(data, tok="space", lang="en"):
"""Tokenize text data.
There are 5 tokenizers supported:
- "space": split along whitespaces
- "char": split in characters
- "13a": Official WMT tokenization
- "zh": Chinese tokenization (See ``sacrebleu`` doc)
- "moses": Moses tokenizer (you can ... | 5,348,722 |
def ift2(x, dim=(-2, -1)):
"""
Process the inverse 2D fast fourier transform and swaps the axis to get correct results using ftAxis
Parameters
----------
x: (ndarray) the array on which the FFT should be done
dim: the axis (or a tuple of axes) over which is done the FFT (default is the last of t... | 5,348,723 |
def print_eval_info(train_losses, train_metrics, eval_losses, eval_metrics):
"""Pretty prints model evaluation results
"""
if not isinstance(train_losses, dict) \
and isinstance(train_metrics, dict) \
and isinstance(eval_losses, dict) \
and isinstance(eval_metrics, dict):... | 5,348,724 |
def chi2_test_independence(prediction_files: list, confidence_level: float):
"""Given a list of prediction files and a required confidence level,
return whether the sentiment probability is independent on which prediction
file it comes from.
Returns True if the sentiment probability is independent of s... | 5,348,725 |
def fetch_all_device_paths():
"""
Return all device paths inside worker nodes
Returns:
list : List containing all device paths
"""
path = os.path.join(constants.EXTERNAL_DIR, "device-by-id-ocp")
clone_repo(constants.OCP_QE_DEVICEPATH_REPO, path)
os.chdir(path)
logger.info("Runn... | 5,348,726 |
def test_roles__2(zcmlS):
"""The calendar visitor role is registered as an visitor role."""
assert has_visitor_role(['icemac.ab.calendar.Visitor']) | 5,348,727 |
def align(fastq_file, pair_file, index_dir, names, align_dir, data):
"""Perform piped alignment of fastq input files, generating sorted, deduplicated BAM.
"""
umi_ext = "-cumi" if "umi_bam" in data else ""
out_file = os.path.join(align_dir, "{0}-sort{1}.bam".format(dd.get_sample_name(data), umi_ext))
... | 5,348,728 |
async def insert(cls:"PhaazeDatabase", WebRequest:Request, DBReq:DBRequest) -> Response:
""" Used to insert a new entry into a existing container """
# prepare request for a valid insert
try:
DBInsertRequest:InsertRequest = InsertRequest(DBReq)
return await performInsert(cls, DBInsertRequest)
except (MissingI... | 5,348,729 |
def eulerAngleXYZ(t123, unit=np.pi/180., dtype=np.float32):
"""
::
In [14]: eulerAngleXYZ([45,0,0])
Out[14]:
array([[ 1. , 0. , 0. , 0. ],
[-0. , 0.7071, 0.7071, 0. ],
[ 0. , -0.7071, 0.7071, 0. ],
[ 0. , ... | 5,348,730 |
def is_on_cooldown(data):
""" Checks to see if user is on cooldown. Based on Castorr91's Gamble"""
# check if command is on cooldown
cooldown = Parent.IsOnCooldown(ScriptName, CGSettings.Command)
user_cool_down = Parent.IsOnUserCooldown(ScriptName, CGSettings.Command, data.User)
caster = Parent.HasP... | 5,348,731 |
def human_readable_size(num):
"""
To show size as 100K, 100M, 10G instead of
showing in bytes.
"""
for s in reversed(SYMBOLS):
power = SYMBOLS.index(s)+1
if num >= 1024**power:
value = float(num) / (1024**power)
return '%.1f%s' % (value, s)
# if size less... | 5,348,732 |
def sum_2_level_dict(two_level_dict):
"""Sum all entries in a two level dict
Parameters
----------
two_level_dict : dict
Nested dict
Returns
-------
tot_sum : float
Number of all entries in nested dict
"""
'''tot_sum = 0
for i in two_level_dict:
for j in... | 5,348,733 |
def file_ref(name):
"""Helper function for getting paths to testing spectra."""
file = os.path.join(os.path.dirname(test_analyzer.__file__),
"test_analyzer", name)
return file | 5,348,734 |
def q_values_from_q_func(q_func, num_grid_cells, state_bounds, action_n):
"""Computes q value tensor from a q value function
Args:
q_func (funct): function from state to q value
num_grid_cells (int): number of grid_cells for resulting q value tensor
state_bounds (list of tuples): state bounds for... | 5,348,735 |
def list_keypairs(k5token, project_id, region):
"""Summary - list K5 project keypairs
Args:
k5token (TYPE): valid regional domain scoped token
project_id (TYPE): Description
region (TYPE): K5 region
Returns:
TYPE: http response object
Deleted Parameters:
useri... | 5,348,736 |
def check_ip(ip):
"""
Check whether the IP is valid or not.
Args:
IP (str): IP to check
Raises:
None
Returns:
bool: True if valid, else False
"""
ip = ip.strip()
if re.match(r'^(?:(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])'
'(\.(?!$)|$))... | 5,348,737 |
def _stream_lines(blob: bytes) -> Iterator[bytes]:
"""
Split bytes into lines (newline (\\n) character) on demand.
>>> iter = _stream_lines(b"foo\\nbar\\n")
>>> next(iter)
b'foo'
>>> next(iter)
b'bar'
>>> next(iter)
Traceback (most recent call last):
...
StopIteration
... | 5,348,738 |
async def fetch_all_organizations(session: ClientSession) -> Dict:
"""Fetch all organizations from organization-catalog."""
url = f"{Config.org_cat_uri()}/organizations"
org_list = await fetch_json_data(url, None, session)
return {org["organizationId"]: org for org in org_list} if org_list else dict() | 5,348,739 |
def create_splits_random(df: pd.DataFrame, val_frac: float,
test_frac: float = 0.,
test_split: Optional[set[tuple[str, str]]] = None,
) -> dict[str, list[tuple[str, str]]]:
"""
Args:
df: pd.DataFrame, contains columns ['dataset',... | 5,348,740 |
def ha_close(close,high,low,open, n=2, fillna=False):
"""Relative Strength Index (RSI)
Compares the magnitude of recent gains and losses over a specified time
period to measure speed and change of price movements of a security. It is
primarily used to attempt to identify overbought or oversold condit... | 5,348,741 |
def PLUGIN_ENTRY():
"""
Required plugin entry point for IDAPython Plugins.
"""
return funcref_t() | 5,348,742 |
def chao1_var_no_doubletons(singles, chao1):
"""Calculates chao1 variance in absence of doubletons.
From EstimateS manual, equation 7.
chao1 is the estimate of the mean of Chao1 from the same dataset.
"""
s = float(singles)
return s*(s-1)/2 + s*(2*s-1)**2/4 - s**4/(4*chao1) | 5,348,743 |
def test_join_query_forward_by_series(columns, dtstart, delta, N):
"""Read data in forward direction"""
begin = dtstart
end = dtstart + delta*(N + 1)
timedelta = end - begin
query_params = {
"output": { "format": "csv" },
"order-by": "series"
}
query = att.make_join_query(c... | 5,348,744 |
def inBarrel(chain, index):
"""
Establish if the outer hit of a muon is in the barrel region.
"""
if abs(chain.muon_outerPositionz[index]) < 108:
return True | 5,348,745 |
def test_image_display(argv):
"""Test image display on client machine.
Usage: python client_service_test.py [host:port] [image file path]
host: IP address of client machine.
port: gRPC service port. (see _CLIENT_SERVICE_GRPC_PORT in main.py)
image file path: a local path to an image file.
"""
targ... | 5,348,746 |
def load_pretrained_embeddings(pretrained_fname: str) -> np.array:
"""
Load float matrix from one file
"""
logging.log(logging.INFO, "Loading pre-trained embedding file: %s" % pretrained_fname)
# TODO: np.loadtxt refuses to work for some reason
# pretrained_embeddings = np.loadtxt(self.args.word_embedding_... | 5,348,747 |
def text(message: Text,
default: Text = "",
validate: Union[Validator,
Callable[[Text], bool],
None] = None, # noqa
qmark: Text = DEFAULT_QUESTION_PREFIX,
style: Optional[Style] = None,
path_autocomplete=False,
exec... | 5,348,748 |
def nav_bar(context):
"""
Define an active tab for the navigation bar
"""
home_active = ''
about_active = ''
detail_active = ''
list_active = ''
logout_active = ''
signup_active = ''
login_active = ''
friends_active = ''
snippets_active = ''
request = context['reque... | 5,348,749 |
def setup_models(basedir, name, lc=True):
"""
Setup model container for simulation
Parameters
----------
basedir : string
Base directory
name : string
Name of source component
Returns
-------
models : `~gammalib.GModels()`
Model container
"""
# Initi... | 5,348,750 |
def create_csm(image):
"""
Given an image file create a Community Sensor Model.
Parameters
----------
image : str
The image filename to create a CSM for
Returns
-------
model : object
A CSM sensor model (or None if no associated model is available.)
"""
... | 5,348,751 |
def walk(obj, path='', skiphidden=True):
"""Returns a recursive iterator over all Nodes starting from
findnode(obj, path).
If skiphidden is True (the default) then structure branches starting with
an underscore will be ignored.
"""
node = findnode(obj, path)
return walknode(node, s... | 5,348,752 |
def setThermalMode(host, args, session):
"""
Set thermal control mode
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used for setting the thermal
control mode
@param session: the active session to use
@para... | 5,348,753 |
def odl():
"""操作数据层"""
pass | 5,348,754 |
def to_string(class_name):
"""
Magic method that is used by the Metaclass created for Itop object.
"""
string = "%s : { " % type(class_name)
for attribute, value in class_name.__dict__.iteritems():
string += "%s : %s, " % (attribute, value)
string += "}"
return string | 5,348,755 |
def mnist_10K_cluster(dataset_dir: Path) -> bool:
"""
Abstract:
The MNIST database of handwritten digits with 784 features.
It can be split in a training set of the first 60,000 examples,
and a test set of 10,000 examples
Source:
Yann LeCun, Corinna Cortes, Christopher J.C. Burges
http:/... | 5,348,756 |
def molefraction_2_pptv(n):
"""Convert mixing ratio units from mole fraction to parts per
thousand by volume (pptv)
INPUTS
n: mole fraction (moles per mole air)
OUTPUTS
q: mixing ratio in parts per trillion by volume (pptv)
"""
# - start with COS mixing ratio n as mole fraction:
# ... | 5,348,757 |
def is_valid_y(y, warning=False, throw=False, name=None):
"""
"""
y = np.asarray(y, order='c')
valid = True
try:
if len(y.shape) != 1:
if name:
raise ValueError(('Condensed distance matrix \'%s\' must '
'have shape=1 (i.e. be one-... | 5,348,758 |
def yaml_parse(yamlstr):
"""Parse a yaml string"""
try:
# PyYAML doesn't support json as well as it should, so if the input
# is actually just json it is better to parse it with the standard
# json parser.
return json.loads(yamlstr)
except ValueError:
yaml.SafeLoader.... | 5,348,759 |
def csl_item_from_pubmed_article(article):
"""
article is a PubmedArticle xml element tree
https://github.com/citation-style-language/schema/blob/master/csl-data.json
"""
csl_item = collections.OrderedDict()
if not article.find("MedlineCitation/Article"):
raise NotImplementedError("Uns... | 5,348,760 |
def image(resource: celtypes.MapType) -> celtypes.Value:
"""
Reach into C7N to get the image details for this EC2 or ASG resource.
Minimally, the creation date is transformed into a CEL timestamp.
We may want to slightly generalize this to json_to_cell() the entire Image object.
The following may ... | 5,348,761 |
def unphase_uvw(ra, dec, uvw):
"""
Calculate unphased uvws/positions from phased ones in an icrs or gcrs frame.
This code expects phased uvws or positions in the same frame that ra/dec
are in (e.g. icrs or gcrs) and returns unphased ones in the same frame.
Parameters
----------
ra : float
... | 5,348,762 |
def sender_msg_to_array(msg):
"""
Parse a list argument as returned by L{array_to_msg} function of this
module, and returns the numpy array contained in the message body.
@param msg: a list as returned by L{array_to_msg} function
@rtype: numpy.ndarray
@return: The numpy array contained in the me... | 5,348,763 |
def find_shortest_path(node):
"""Finds shortest path from node to it's neighbors"""
next_node,next_min_cost=node.get_min_cost_neighbor()
if str(next_node)!=str(node):
return find_shortest_path(next_node)
else:
return node | 5,348,764 |
def cast_array_to_feature(array: pa.Array, feature: "FeatureType", allow_number_to_str=True):
"""Cast an array to the arrow type that corresponds to the requested feature type.
For custom features like Audio or Image, it takes into account the "cast_storage" methods
they defined to enable casting from other... | 5,348,765 |
def check_key_match(config_name):
"""
Check key matches
@param config_name: Name of WG interface
@type config_name: str
@return: Return dictionary with status
"""
data = request.get_json()
private_key = data['private_key']
public_key = data['public_key']
return jsonify(f_check_k... | 5,348,766 |
def main(argv=None):
"""Command line interface."""
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description='Converts Jupyter Notebooks to Atlassian Confluence pages using nbconvert',
epilog="Collects credentials from the following locations:\n"
... | 5,348,767 |
def delete_user_group(request, group_id, *args, **kwargs):
"""This one is not really deleting the group object, rather setting the active status
to False (delete) which can be later restored (undelete) )"""
try:
hydroshare.set_group_active_status(request.user, group_id, False)
messages.succe... | 5,348,768 |
def _generate_room_square(dungen: DungeonGenerator, room_data: RoomConceptData) -> RoomConcept:
"""
Generate a square-shaped room.
"""
map_width = dungen.map_data.width
map_height = dungen.map_data.height
# ensure not bigger than the map
room_width = min(dungen.rng.randint(room_data.min_wid... | 5,348,769 |
def query(request):
"""
响应前端返回的数据并进行相应的推荐
:param request:
:return:
"""
content = {}
if request.method=='POST':
datatype = json.loads(request.body.decode('utf-8')) #得到前端返回的数据
province_all = datatype['all']
current_loc = datatype['currentLocation'] # 得到当前的省份,以这份省份为基准点算... | 5,348,770 |
def str_is_float(value):
"""Test if a string can be parsed into a float.
:returns: True or False
"""
try:
_ = float(value)
return True
except ValueError:
return False | 5,348,771 |
def get_from_cache(url, cache_dir=None, force_download=False, proxies=None, etag_timeout=10, resume_download=False):
#for bert-based-uncased, url is https://s3.amazonaws.com/models.huggingface.co/bert/bert-base-uncased-config.json
#also, cache_dir is the following: /Users/msanatkar/.cache/torch/transformers
... | 5,348,772 |
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Ruckus Unleashed from a config entry."""
try:
ruckus = await hass.async_add_executor_job(
Ruckus,
entry.data[CONF_HOST],
entry.data[CONF_USERNAME],
entry.data[CONF_PASS... | 5,348,773 |
def get_user_plugins_grouped(get_allowed_plugin_uids_func,
get_registered_plugins_grouped_func,
registry,
user,
sort_items=True):
"""Get user plugins grouped.
:param callable get_allowed_plugin_u... | 5,348,774 |
def show_frames(frames, freq = 12):
""" This function receives a list of frames and plays them back at the given
frequency.
"""
for frame in frames:
cv2.imshow('frame',frame)
cv2.waitKey(round(1000/freq)) | 5,348,775 |
def setup_container_system_config(basedir, mountdir, dir_modes):
"""Create a minimal system configuration for use in a container.
@param basedir: The directory where the configuration files should be placed (bytes)
@param mountdir: The base directory of the mount hierarchy in the container (bytes).
@par... | 5,348,776 |
def calc_randnm7(reg_dict, mlx75027):
"""
Calculate the RANDMN7 register value
Parameters
----------
reg_dict : dict
The dictionary that contains all the register information
mlx75027 : bool
Set to True if using the MLX75027 sensor, False
if using the MLX75026 sensor.... | 5,348,777 |
def get_orientation(pose, ori):
"""Generate an orientation vector from yaw/pitch/roll angles in radians."""
yaw, pitch, roll = pose
c1 = np.cos(-yaw)
s1 = np.sin(-yaw)
c2 = np.cos(-pitch)
s2 = np.sin(-pitch)
c3 = np.cos(-roll)
s3 = np.sin(-roll)
Ryaw = np.array([[c1, s1, 0], [-s1, c1... | 5,348,778 |
def draw_deformation(source_image, grid, grid_size = 12):
"""
source_image: PIL image object
sample_grid: the sampling grid
grid_size: the size of drawing grid
"""
im = copy.deepcopy(source_image)
d = ImageDraw.Draw(im)
H,W = source_image.size
dist =int(H/grid_size)
for i in rang... | 5,348,779 |
def dial_socket(host='localhost', port):
"""
Connect to the socket created by the
server instance on specified host and port
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
return sock | 5,348,780 |
def test_tamper_mutate_compress(logger):
"""
Tests that compress is handled right if its enabled
"""
backup = copy.deepcopy(actions.tamper.ACTIVATED_PRIMITIVES)
actions.tamper.ACTIVATED_PRIMITIVES = ["compress"]
try:
tamper = actions.tamper.TamperAction(None)
assert tamper.parse(... | 5,348,781 |
def analyseClassificationCoefficients(X: pd.DataFrame,
y: pd.Series,
D_learning_results: pd.DataFrame,
outputPath: str) -> dict:
"""
This function evaluates the importance coefficients of the input ... | 5,348,782 |
def centerfreq_to_bandnum(center_freq, norm_freq, nth_oct):
"""Returns band number from given center frequency."""
return nth_oct * np.log2(center_freq / norm_freq) | 5,348,783 |
def crossval_model(
estimator: BaseEstimator,
X: pd.DataFrame,
y: Union[pd.Series, pd.DataFrame],
evaluators: Sequence[Evaluator],
cv: Optional[
Union[int, BaseCrossValidator]
] = None, # defaults to KFold(n_splits=5)
random_state: Optional[Union[int, np.random.RandomState]] = None,... | 5,348,784 |
def download_json(name, url, root_path):
"""abstract function to download a json file"""
download_path = os.path.join(root_path, name + '.json')
if not os.path.exists(download_path):
download = requests.get(url)
content = download.json()
with open(download_path, 'w') as output:
... | 5,348,785 |
def measure_dist(positions,weights,v_ref,side = False):
"""
Will plot the mouse and allow me to click and measure with two clicks
side is false (so top view)
but can be True, then it's cut though the major axis of hte mouse (determined by v_reference)
"""
# simplest trick is to just rotate all p... | 5,348,786 |
def _get_draft_comments(request, issue, preview=False):
"""Helper to return objects to put() and a list of draft comments.
If preview is True, the list of objects to put() is empty to avoid changes
to the datastore.
Args:
request: Django Request object.
issue: Issue instance.
preview: Preview flag... | 5,348,787 |
def activate_model(cfg):
"""Activate the dynamic parts."""
cfg["fake"] = cfg["fake"]()
return cfg | 5,348,788 |
def generate_tsv_gen(rows, le='\n'):
"""
Generate tab-separated value output from a list of dicts.
The keys of the dict will be used as column headings, and
are assumed to be identical for all rows.
"""
header_string = None
for row in rows:
headers = []
fields = []
for header, value in row.items():
... | 5,348,789 |
def assert_allclose(
actual: numpy.ndarray, desired: numpy.ndarray, err_msg: Literal["boxcar, 10, 9"]
):
"""
usage.scipy: 2
"""
... | 5,348,790 |
def convert_to_number(string):
"""
Tries to cast input into an integer number, returning the
number if successful and returning False otherwise.
"""
try:
number = int(string)
return number
except:
return False | 5,348,791 |
def _ts_value(position, counts, exposure, background, kernel, norm, flux_estimator):
"""Compute TS value at a given pixel position.
Uses approach described in Stewart (2009).
Parameters
----------
position : tuple (i, j)
Pixel position.
counts : `~numpy.ndarray`
Counts image
... | 5,348,792 |
def mean(nums: List) -> float:
"""
Find mean of a list of numbers.
Wiki: https://en.wikipedia.org/wiki/Mean
>>> mean([3, 6, 9, 12, 15, 18, 21])
12.0
>>> mean([5, 10, 15, 20, 25, 30, 35])
20.0
>>> mean([1, 2, 3, 4, 5, 6, 7, 8])
4.5
>>> mean([])
Traceback (most recent call las... | 5,348,793 |
def test_MergeFang_ZeroOffTime():
"""Merger detects the off time gap and creates separate molecules.
"""
merger = proc.Merge(mergeRadius = 25,
tOff = 1,
statsComputer = proc.MergeFang())
pathToTestData = testDataRoot... | 5,348,794 |
def test_fetch_returns_lst():
"""
GIVEN fetch()
WHEN is called
THEN should return list
"""
return_lst = fetch()
assert type(return_lst) == list | 5,348,795 |
def post_3d(post_paths, labels, colours, linestyles, contour_levels_sig, x_label=None, y_label=None, z_label=None,
x_lims=None, y_lims=None, z_lims=None, smooth_xy=None, smooth_xz=None, smooth_yz=None, smooth_x=None,
smooth_y=None, smooth_z=None, print_areas=False, save_path=None):
"""
P... | 5,348,796 |
def det(m1: ndarray) -> float:
"""
Compute the determinant of a double precision 3x3 matrix.
https://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/det_c.html
:param m1: Matrix whose determinant is to be found.
:return: The determinant of the matrix.
"""
m1 = stypes.to_double_matrix(m1)
... | 5,348,797 |
def path_to_xy(path: PointList) -> XYList:
"""Convert PointList to XYList"""
return [p.xy() for p in path] | 5,348,798 |
def apply_taint(state, addr, taint_id='', bits=PAGE_SIZE, var=None):
"""
Apply taint to a memory location
:param state: angr state
:param addr: memory address
:param taint_id: taint id
:param bits: number of bits
:param var: symbolic variable to store
:return:
"""
if var is Non... | 5,348,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.