content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def guess_initializer(var, graph=None):
"""Helper function to guess the initializer of a variable.
The function looks at the operations in the initializer name space for the
variable (e.g. my_scope/my_var_name/Initializer/*). The TF core initializers
have characteristic sets of operations that can be used to d... | 5,347,000 |
def init_colors():
"""Initialize the color definition for all pair identifiers"""
# This allows the use of `-1` in `init_pair()` for accessing the
# default foreground and background terminal colors. It also enables
# transparency.
curses.use_default_colors()
# Default colors from terminal pref... | 5,347,001 |
def get_all(ptype=vendor):
""" returns a dict of all partners """
if ptype == vendor:
d = get_dict_from_json_file( VENDORS_JSON_FILE ) # will create file if not exist
if ptype == customer:
d = get_dict_from_json_file( CUSTOMERS_JSON_FILE )
return d | 5,347,002 |
def validate_read_parameters(file_path, output_path, encryption_key, scrypt_n, scrypt_r, scrypt_p,
block_height_override, block_width_override, max_cpu_cores, save_statistics,
bad_frame_strikes, stop_at_metadata_load, auto_unpackage_stream,
... | 5,347,003 |
def test_RNNCell():
"""
Test the RNNCell module to ensure that it produces the exact same
output as the primary torch implementation, in the same order.
"""
# Disable mkldnn to avoid rounding errors due to difference in implementation
mkldnn_enabled_init = torch._C._get_mkldnn_enabled()
tor... | 5,347,004 |
def tsplot_data(cfg, mmodel, region, observations='PHC'):
"""Extract data for TS plots from one specific model.
Parameters
----------
mmodel: str
model name
max_level: int
maximum level (depth) of TS data to be used
region: str
region as defined in `hofm_regions`
ob... | 5,347,005 |
def FindCatkinResource(package, relative_path):
"""
Find a Catkin resource in the share directory or
the package source directory. Raises IOError
if resource is not found.
@param relative_path Path relative to share or package source directory
@param package The package to search in
@return... | 5,347,006 |
def plot_xfs_feature_frequency(
freq,
figsize=None,
freq_pct=True,
color=None,
marker=None,
markersize=None,
markeredgecolor=None,
markerfacecolor=None,
markeredgewidth=None,
fontsize=None,
save_path=None,
):
"""Function to plot selected features frequency.
This funct... | 5,347,007 |
def copy_all(
network_filename="socialNetwork.json",
source_image_json="sourceImageFilenames.json",
entity_image_json="entityImageFilenames.json",
images_filename="images.json"
):
""" Copy all exported files to their correct paths within the Javascript src
directory
Args:
... | 5,347,008 |
def clear_errors() -> None:
"""
""" | 5,347,009 |
def send_udf_call(
api_func: Callable[..., urllib3.HTTPResponse],
api_kwargs: Dict[str, Any],
decoder: decoders.AbstractDecoder,
id_callback: Optional[IDCallback] = None,
*,
results_stored: bool,
) -> "results.RemoteResult[_T]":
"""Synchronously sends a request to the given API.
This ha... | 5,347,010 |
def migration_area_baidu(area="乌鲁木齐市", indicator="move_in", date="20200201"):
"""
百度地图慧眼-百度迁徙-XXX迁入地详情
百度地图慧眼-百度迁徙-XXX迁出地详情
以上展示 top100 结果,如不够 100 则展示全部
迁入来源地比例: 从 xx 地迁入到当前区域的人数与当前区域迁入总人口的比值
迁出目的地比例: 从当前区域迁出到 xx 的人口与从当前区域迁出总人口的比值
https://qianxi.baidu.com/?from=shoubai#city=0
:param area... | 5,347,011 |
def ranges(locdata: LocData, loc_properties=None, special=None, epsilon=1):
"""
Provide data ranges for locdata.data property.
If LocData is empty None is returned.
If LocData carries a single value, the range will be (value, value + `epsilon`).
Parameters
----------
locdata : LocData
... | 5,347,012 |
def subnet_create(request, network_id, **kwargs):
"""Create a subnet on a specified network.
:param request: request context
:param network_id: network id a subnet is created on
:param cidr: (optional) subnet IP address range
:param ip_version: (optional) IP version (4 or 6)
:param gateway_ip: ... | 5,347,013 |
def evaluate_available(item, type_name, predicate):
"""
Run the check_available predicate and cache the result.
If there is already a cached result, use that and don't
run the predicate command.
:param str item: name of the item to check the type for. i.e. 'server_types
:param str type_name: nam... | 5,347,014 |
def dB_transform(R, metadata=None, threshold=None, zerovalue=None, inverse=False):
"""Methods to transform precipitation intensities to/from dB units.
Parameters
----------
R: array-like
Array of any shape to be (back-)transformed.
metadata: dict, optional
Metadata dictionar... | 5,347,015 |
def setup() -> None:
"""
Sets up the Partial FC backbone such that the model may be fetched using
`get()`. Primarily, the setup involves the download of pretrained weights
from `PARTIAL_FC_BACKBONE_PRETRAIN_URL`.
"""
# Download pretrained model
_file_jar.store_file(
PARTIAL_FC_BACKBO... | 5,347,016 |
def set_geocentric_zero_from_oxy_ha(target_data, geo_results = None,
velocity_column = None,
data_column = None,
variance_column = None,
new_velocity_column = ... | 5,347,017 |
def cut(
video: typing.Union[str, VideoObject],
output_path: str = None,
threshold: float = 0.95,
frame_count: int = 5,
compress_rate: float = 0.2,
target_size: typing.Tuple[int, int] = None,
offset: int = 3,
limit: int = None,
) -> typing.Tuple[VideoCutResult, str]:
"""
cut the ... | 5,347,018 |
def re_evaluate_did(scope, name, rule_evaluation_action, session=None):
"""
Re-Evaluates a did.
:param scope: The scope of the did to be re-evaluated.
:param name: The name of the did to be re-evaluated.
:param rule_evaluation_action: The Rule evaluation action... | 5,347,019 |
def parse_args():
"""
Parses command line arguments
"""
parser = ArgumentParser(description="A multi-threaded gemini server")
parser.add_argument("-b", "--host", default=DEFAULT_HOST, help="Host to bind to")
parser.add_argument("-p", "--port", default=DEFAULT_PORT, help="Port to bind to")
pa... | 5,347,020 |
def insert_deleted_entries(deleted_entries, data_type):
""" Inserts every entry in deleted_entries dict into inbound_queue table.
Args:
deleted_entries: An array containing the remote_ids/distinguished names
of the users/groups that were deleted.
data_type: A string with the value o... | 5,347,021 |
def get_mapping_rules():
""" Get mappings rules as defined in business_object.js
Special cases:
Aduit has direct mapping to Program with program_id
Request has a direct mapping to Audit with audit_id
Response has a direct mapping to Request with request_id
DocumentationResponse has a direct mapping... | 5,347,022 |
def get_src_hash(sls_config, path):
"""Get hash(es) of serverless source."""
funcs = sls_config['functions']
if sls_config.get('package', {}).get('individually'):
hashes = {key: get_hash_of_files(os.path.join(path,
os.path.dirname(funcs[key].get... | 5,347,023 |
def gsma_not_found(ctx, config, statsd, logger, run_id, conn, metadata_conn, command, metrics_root, metrics_run_root,
force_refresh, disable_retention_check, disable_data_check, debug_query_performance,
month, year, output_dir):
"""Generate report of all GSMA not found IMEIs.""... | 5,347,024 |
def extract_zip(zip_path, ret_extracted_path=False):
"""Extract a zip and delete the .zip file."""
dir_parents = os.path.dirname(zip_path)
dir_name = Path(zip_path).stem
extracted_path = os.path.join(dir_parents, dir_name, '')
if ret_extracted_path:
return extracted_path
with zipfile.Zi... | 5,347,025 |
async def get_pipeline(request: web.Request, organization, pipeline) -> web.Response:
"""get_pipeline
Retrieve pipeline details for an organization
:param organization: Name of the organization
:type organization: str
:param pipeline: Name of the pipeline
:type pipeline: str
"""
retur... | 5,347,026 |
def chunk_queue(dir_in="../audio/chunk_queue",
dir_out="../audio/wav_chunked",
chunk_len=5,
sr=22050,
log=True
):
"""
Feeds each song in queue directory to the chunk_song() function.
---
IN
dir_in: path of audio queue dir... | 5,347,027 |
def add_attachment(manager, issue, file):
"""
Replace jira's method 'add_attachment' while don't well fixed this issue
https://github.com/shazow/urllib3/issues/303
And we need to set filename limit equaled 252 chars.
:param manager: [jira.JIRA instance]
:param issue: [jira.JIRA.resources.Issue i... | 5,347,028 |
def app_start(page_name):
"""
device start at init
"""
page_value = gr.get_flow_behave_value(page_name, None)
cur_platform = g_context.platform
if cur_platform.strip().lower() == "web":
log.info('[app_start] cur_platform is web, run web_start.')
web_start(page_value)
retu... | 5,347,029 |
def plot_experiment3_1():
"""Figure 3 (a) of the paper."""
lat128 = np.load('./results/experiment3/experiment3_full_anomal-rec_ae_lat128_best_aps.npy')
lat32 = np.load('./results/experiment3/experiment3_full_anomal-rec_ae_lat32_best_aps.npy')
spatial1 = np.load('./results/experiment3/experiment3_full_an... | 5,347,030 |
def _ols_iter(inv_design, sig, min_diffusivity):
""" Helper function used by ols_fit_dki - Applies OLS fit of the diffusion
kurtosis model to single voxel signals.
Parameters
----------
inv_design : array (g, 22)
Inverse of the design matrix holding the covariants used to solve for
... | 5,347,031 |
def test_collect_rollout_values() -> None:
"""
Test the values of the returned RolloutStorage objects from trainer.collect_rollout().
"""
# Initialize trainer.
settings = dict(DEFAULT_SETTINGS)
settings["env_name"] = "unique-env"
trainer = RLTrainer(settings)
# Run rollout.
_, _ = ... | 5,347,032 |
def unarchive_collector(collector):
"""
This code is copied from `Collector.delete` method
"""
# sort instance collections
for model, instances in collector.data.items():
collector.data[model] = sorted(instances, key=attrgetter("pk"))
# if possible, bring the models in an order suitabl... | 5,347,033 |
def create_dataset_content(datasetName=None):
"""
Creates the content of a data set by applying a "queryAction" (a SQL query) or a "containerAction" (executing a containerized application).
See also: AWS API Documentation
Exceptions
:example: response = client.create_dataset_content(
... | 5,347,034 |
def remove_tag_from_issues(
issues: List[GitHubIssue],
tag: str,
scope: str = "all",
ignore_list: Optional[Union[List[int], List[Dict[str, int]]]] = None,
) -> List[GitHubIssue]:
"""remove_tag_from_issues
Removes all of a tag from the given issues.
If scoped to just issues, we still check t... | 5,347,035 |
def days_remaining_context_processor(request):
"""Context processor. Adds days_remaining to context of every view."""
now = datetime.now()
return {'days_remaining' : (wedding_date - now).days} | 5,347,036 |
def convert_time_range(trange, tz=None):
"""
Converts freeform time range into a tuple of localized
timestamps (start, end).
If `tz` is None, uses settings.TIME_ZONE for localizing
time range.
:param trange: - string representing time-range. The options
are:
* string in format ... | 5,347,037 |
def process_waiting_time(kernel_data, node_id, phase_id, norm_vehs=False):
"""Processes batched waiting time computation"""
cycle_time = 60
def fn(x):
if (x / 13.89) < 0.1:
return 1.0
else:
return 0.0
wait_times = []
for t in kernel_data:
qt = defau... | 5,347,038 |
def setup_group(dpath, mod, ofctl):
"""
Default Group.
"""
_LOG.debug("Setup Group: %d %s %s", dpath.id, mod, ofctl) | 5,347,039 |
def get_version():
""" Do this so we don't have to import lottery_ticket_pruner which requires keras which cannot be counted on
to be installed when this package gets installed.
"""
with open('lottery_ticket_pruner/__init__.py', 'r') as f:
for line in f.readlines():
if line.startswit... | 5,347,040 |
def train_model_regression(X, X_test, y, params, folds, model_type='lgb', eval_metric='mae', columns=None,
plot_feature_importance=False, model=None,
verbose=10000, early_stopping_rounds=200, n_estimators=50000):
"""
A function to train a variety of regr... | 5,347,041 |
def extract(d, keys):
"""
Extract a key from a dict.
:param d: The dict.
:param keys: A list of keys, in order of priority.
:return: The most important key with an value found.
"""
if not d:
return
for key in keys:
tmp = d.get(key)
if tmp:
return tmp | 5,347,042 |
def test_combinations():
"""Tests reading and updating the combinations txt file"""
assert "temp.txt" not in os.listdir(".")
assert not generator.check(filename="temp.txt", combination=OUTPUT)
generator.update(filename="temp.txt", combination=OUTPUT)
assert generator.check(filename="temp.txt", combi... | 5,347,043 |
def create_file_list(files, suffices, file_type, logger, root_path=None):
###############################################################################
"""Create and return a master list of files from <files>.
<files> is either a comma-separated string of pathnames or a list.
If a pathname is a director... | 5,347,044 |
def register_urls(app):
"""
Register hapapi URLs
"""
RootView.register(app)
ProxyView.register(app)
BackendView.register(app) | 5,347,045 |
def get_raster(layer, bbox, path=None, update_cache=False,
check_modified=False, mosaic=False):
"""downloads National Elevation Dataset raster tiles that cover the given bounding box
for the specified data layer.
Parameters
----------
layer : str
dataset layer name. (see get_... | 5,347,046 |
def edit_distance(y, y_hat):
"""Edit distance between two sequences.
Parameters
----------
y : str
The groundtruth.
y_hat : str
The recognition candidate.
the minimum number of symbol edits (i.e. insertions,
deletions or substitutions) required to change one
word into th... | 5,347,047 |
def sort_predictions(classes, predictions, bboxes):
""" Sorts predictions from most probable to least, generate extra metadata about them. """
results = []
for idx, pred in enumerate(predictions):
results.append({
"class_idx": np.argmax(pred),
"class": classes[np.argmax(pred)... | 5,347,048 |
def task_bootstrap_for_adming():
"""
"""
return {'actions': [(clushUtils.exec_script, [targetNode, "bootstrap_for_adming.py"],
{
'dependsFiles': [".passwords", f"{homeDir}/.ssh/id_rsa.pub"],
'user':"root",
... | 5,347,049 |
def reassign_clustered(
knn: List[Tuple[npt.NDArray, npt.NDArray]],
clusters: List[Tuple[str, int]],
min_sim_threshold: float = 0.6,
n_iter: int = 20,
epsilon: float = 0.05,
) -> List[Tuple[str, int]]:
"""Reassigns companies to new clusters based on the average similarity to
nearest neighbou... | 5,347,050 |
def boys(n,t):
"""Boys function for the calculation of coulombic integrals.
Parameters
----------
n : int
Order of boys function
t : float
Varible for boys function.
Raises
------
TypeError
If boys function order is not an integer.
ValueError
If bo... | 5,347,051 |
def show_next_action_with_min_prio(context):
"""Check that the next actions have the minimum priority."""
for line in context.next_action().strip().split("\n"):
assert_in("(A)", line) | 5,347,052 |
def get_diameter_by_sigma(sigma, proba):
""" Get diameter of nodule given sigma of normal distribution and probability of diameter coverage area.
Transforms sigma parameter of normal distribution corresponding to cancerous nodule
to its diameter using probability of diameter coverage area.
Parameters
... | 5,347,053 |
def serve(environment):
"""Run Marian application based on FLASK_ENV configuration."""
if environment == 'production':
os.system('sh ./serve.sh')
else:
os.system('flask run') | 5,347,054 |
def run_benchmark(mode: str) -> None:
"""
Run the given model on a benchmark and save the prediction.
:param mode: "repos_direct" for using direct embeddings of repos.
"repos_by_libraries" for using embeddings of repos as average of libraries.
"jaccard" for using Jaccard si... | 5,347,055 |
def _colorize(val, color):
"""Colorize a string using termcolor or colorama.
If any of them are available.
"""
if termcolor is not None:
val = termcolor.colored(val, color)
elif colorama is not None:
val = "{}{}{}".format(TERMCOLOR2COLORAMA[color], val, colorama.Style.RESET_ALL)
... | 5,347,056 |
def get_output_filename(output_folder: str, repository_type: str,
repository_name: str, filename: str) -> Path:
"""Returns the output filename for the file fetched from a repository."""
return (
Path(output_folder) / Path(repository_type.lower())
/ Path(Path(repository_na... | 5,347,057 |
def get_data(cpe):
"""collect data from ser_dev
single value of z-accel"""
cpe.reset_input_buffer()
next = cpe.readline()
light = (float(next.decode("ascii"))) # TODO wrap in TRY?
return light | 5,347,058 |
def wave_exist_2d_full_v2(b=.8):
"""
plot zeros of -nu1 + G(nu1,nu2) and -nu2 + G(nu2,nu1)
as a function of g
use accurate fourier series
"""
# get data
# nc1 bifurcation values
bif = np.loadtxt('twod_wave_exist_br1.dat')
#bif2 = np.loadtxt('twod_wave_exist_br2.d... | 5,347,059 |
def _parse_variables(vars_list):
"""Transform the list of vars stored in module definition in dictionnary"""
vars = {}
for var in vars_list:
key = var['name']
value = None
for var_type in ATTRIBUTE_TYPE:
if var_type in var:
value = var[var_type]
... | 5,347,060 |
def get_vertical_axes(nc_file):
"""
Scan input netCDF file and return a list of vertical axis variables, requiring specific
axis names
"""
vertical_axes = []
for var_name, var in nc_file.variables.items():
if var_name in ('full_levels', 'half_levels'):
vertical_axes.append(v... | 5,347,061 |
def update_workload_volumes(workload,config,spec_config):
"""
Return True if some env is updated;otherwise return False
"""
volumemount_configs = get_property(spec_config,("containers",0,"volumeMounts"))
if not volumemount_configs:
del_objs = models.WorkloadVolume.objects.filter(workload=wor... | 5,347,062 |
def b_2_d(x):
"""
Convert byte list to decimal
:param x: byte list
:return: decimal
"""
s = 0
for i in range(0, len(x)):
s += x[i]*2**i
return s | 5,347,063 |
def test_subscript_imports_exports():
"""
If we look at an element of an object such as a dataframe(e.g. x[0]), that dataframe needs to be
defined so should be an import.
If the element is an assignment target it should also be an export.
"""
code = "df.x[0] = 3\n"
frames = ["df"]
testda... | 5,347,064 |
def get(s, delimiter='', format="diacritical"):
"""Return pinyin of string, the string must be unicode
"""
return delimiter.join(_pinyin_generator(u(s), format=format)) | 5,347,065 |
def test_multiple_insert(client, auth_header: dict, random_depots: List[dict]):
"""Test with multiple objects in array"""
input_data: dict = {"stack_id": 1, "depots": random_depots}
logging.debug(f"Number of depots : {len(random_depots)}")
logging.debug(f"Input data: {input_data}")
HEADERS: dict =... | 5,347,066 |
def deposit(**kwargs):
"""
Deposit CifData object
"""
from aiida.orm.data.cif import CifData
node = kwargs.pop('node')
deposition_type = kwargs.pop('deposition_type')
parameter_data = kwargs.pop('parameter_data')
# if kwargs['database'] is None:
# echo.echo_critical("Default databa... | 5,347,067 |
def top_dist(g1, g2, name='weight', topology_type=0):
"""
:param g1: graph 1
:param g2: graph 2
:param name: compared edge attribute
:param topology_type: topology distance normalization method
:return: topology distance
"""
max_v = max_edge(g1, name, max_edge(g2, name, 0)) # find max ... | 5,347,068 |
async def async_setup_entry(
hass: HomeAssistant,
entry: ConfigEntry,
async_add_entities: Callable[[list], None],
) -> bool:
"""Set up the ISY994 sensor platform."""
hass_isy_data = hass.data[ISY994_DOMAIN][entry.entry_id]
devices = []
for node in hass_isy_data[ISY994_NODES][SENSOR]:
... | 5,347,069 |
def analyze(options, args=None):
"""This function runs analysis on simulation data. What analysis and what to
output is specified in the options object.
"""
run_analysis(options) | 5,347,070 |
def refresh_track():
"""
For now the interface isn't refreshed
:return:
"""
try:
url = request.form["url"]
except KeyError:
return "nok"
with app.database_lock:
Track.refresh_by_url(app.config["DATABASE_PATH"], url)
return "ok" | 5,347,071 |
def test_user_mention_with_dictionary():
"""This function tests creating a user mention with all required dictionary key value pairs provided.
.. versionadded:: 2.4.0
:returns: None
"""
user_id, login = get_user_test_data()
user_info = {'id': user_id, 'login': login}
response = messages.fo... | 5,347,072 |
def get_weights():
""" Loads uni-modal text and image CNN model weights.
Returns:
tuple: text and image weights.
"""
text_weight_file = open("models/unimodal_text_CNN_weights.pickle", "rb")
text_weights = pickle.load(text_weight_file)
text_weight_file.close()
image_weight_file = o... | 5,347,073 |
def get_data(start_runno, start_fileno, hall, fields): # pylint: disable=too-many-locals,too-many-branches
"""Pull the data requested, starting from first VALID run/file after/including
the specified one"""
val_dict = lambda: {'values': []}
ad_dict = lambda: {f'AD{det}': val_dict()
... | 5,347,074 |
def timelength_label_to_seconds(
timelength_label: spec.TimelengthLabel,
) -> spec.TimelengthSeconds:
"""convert TimelengthLabel to seconds"""
number = int(timelength_label[:-1])
letter = timelength_label[-1]
base_units = timelength_units.get_base_units()
base_seconds = base_units['1' + letter]
... | 5,347,075 |
def _save_node_ip_address(task_id, node):
"""Helper function for saving IP address and creating DNS records of a new compute node"""
assert node.address
try:
ip_address = node.create_ip_address()
except IPAddress.DoesNotExist as exc:
logger.warning('Could not save node %s IP address "%s... | 5,347,076 |
def test_directory_new(tmp_path):
"""
Test file.directory when the directory does not exist
Should just return "New Dir"
"""
path = os.path.join(tmp_path, "test")
ret = file.directory(
name=path,
makedirs=True,
win_perms={"Administrators": {"perms": "full_control"}},
... | 5,347,077 |
def check(src, perm, dest, cmds, comp, verbose=False):
"""
Report if src and dest are different.
Arguments
src: Location of the source file.
perm: Permissions of the destination file (ignored).
dest: Location of the destination file.
cmds: Post-install commands (ignored).
... | 5,347,078 |
def getUrlsAlias()->List[str]:
"""获取所有urls.py的别名"""
obj = getEnvXmlObj()
return obj.get_childnode_lists('alias/file[name=urls]') | 5,347,079 |
def upload_model():
"""
Upload the model that is serialized to disk to the server.
This method does NOT communicate with Excel at all.
@return:
"""
model = PersistenceHandler(os.path.dirname(__file__)).load_model()
uploader = UploadHandler()
uploader.upload_database(model)
... | 5,347,080 |
def project_xarray(run: BlueskyRun, *args, projection=None, projection_name=None):
"""Produces an xarray Dataset by projecting the provided run.
EXPERIMENTAL: projection code is experimental and could change in the near future.
Projections come with multiple types: linked, and caclulated. Calculated field... | 5,347,081 |
def collect_users():
"""Collect a list of all Santas from the user"""
list_of_santas = []
while 1:
item = input("Enter a name\n")
if not item:
break
list_of_santas.append(item)
return list_of_santas | 5,347,082 |
def check_role_exists(role_name, access_key, secret_key):
"""
Check wheter the given IAM role already exists in the AWS Account
Args:
role_name (str): Role name
access_key (str): AWS Access Key
secret_key (str): AWS Secret Key
Returns:
Boolean: True if env exists else F... | 5,347,083 |
def group_delay(group_key, flights):
"""
Group the arrival delay flights based on keys.
:param group_key: Group key to use for categorization.
:param flights: List of flights matching from an origin airport.
:return: Dictionary containing the list of flights grouped.
"""
dict_of_group_flight... | 5,347,084 |
def create_matrix(
score_same_brackets, score_other_brackets, score_reverse_brackets,
score_brackets_dots, score_two_dots, add_score_for_seq_match,
mode='simple'):
"""
Function that create matrix that can be used for further analysis,
please take note, that mode must be the same in c... | 5,347,085 |
def view_inv(inventory_list):
"""list -> None
empty string that adds Rental attributes
"""
inventory_string = ''
for item in inventory_list:
inventory_string += ('\nRental: ' + str(item[0])+ '\nQuantity: '+ str(item[1])+
'\nDeposit: '+"$"+ str(item[2])+"\nPr... | 5,347,086 |
def generate_smb_proto_payload(*protos):
"""Generate SMB Protocol. Pakcet protos in order.
"""
hexdata = []
for proto in protos:
hexdata.extend(proto)
return "".join(hexdata) | 5,347,087 |
def FeatureGrad_LogDet(grad_feature):
"""Part of the RegTerm inside the integral
It calculates the logarithm of the determinant of the matrix [N_y x N_y] given by the scalar product of the gradients along the N_x axis.
Args:
grad_feature (array_like): [N_samples, N_y, N_x], where N_x is the input s... | 5,347,088 |
def get_every_second_indexes(ser: pd.Series,
even_index=True) -> pd.core.series.Series:
"""Return all rows where the index is either even or odd.
If even_index is True return every index where idx % 2 == 0
If even_index is False return every index where idx % 2 != 0
Assume d... | 5,347,089 |
def EVLAApplyCal(uv, err, SNver=0, CLin=0, CLout=0, maxInter=240.0, \
doSelf=False,
logfile=None, check=False, debug=False):
"""
Applies an SN table to a CL table and writes another
Returns task error code, 0=OK, else failed
* uv = UV data object to clear
... | 5,347,090 |
def parse_imports_from_import_statement(
statement: Statement, strict: bool = False
) -> typing.Iterable[ImportStatement]:
"""
Parse import statements
"""
# import statement standalone_comments are the only possible possible
standalone_comments = statement.standalone_comments
# import state... | 5,347,091 |
def set_exports(pub, cg):
"""In file pub, mark the include for cg with IWYU pragma: export"""
lines = []
for line in open(pub).read().splitlines():
if line.startswith('#include %s' % to_inc(cg)):
lines.append('#include %s // IWYU pragma: export' % to_inc(cg))
else:
l... | 5,347,092 |
def preprocess_input(text):
"""
정제된 텍스트를 토큰화합니다
:param text: 정제된 텍스트
:return: 문장과 단어로 토큰화하여 분석에 투입할 준비를 마친 텍스트
"""
sentences = nltk.sent_tokenize(text)
tokens = [nltk.word_tokenize(sentence) for sentence in sentences]
return tokens | 5,347,093 |
def create_count_dictionaries_for_letter_placements(all_words_list):
"""Returns a tuple of dictionaries where the index of the tuple is the counts for that index of each word
>>> create_count_dictionaries_for_letter_placements(all_words_list)
(dictPosition0, dictPosition1, dictPosition2, dictPosition3, dic... | 5,347,094 |
def parse_known(key, val) -> str:
"""
maps string from html to to function for parsing
Args:
key: string from html
val: associated value in html
Returns:
str
"""
key_to_func = {}
key_to_func["left"] = parse_number
key_to_func["top"] = parse_number
... | 5,347,095 |
def getRecordsPagination(page, filterRecords=''):
""" get all the records created by users to list them in the backend welcome page """
newpage = int(page)-1
offset = str(0) if int(page) == 1 \
else str(( int(conf.pagination) *newpage))
queryRecordsPagination = """
PREFIX prov: <http://www.w3.org/ns/prov#>
PR... | 5,347,096 |
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Perform the setup for Gardena sensor devices."""
entities = []
for sensor in hass.data[DOMAIN][GARDENA_LOCATION].find_device_by_type("SENSOR"):
for sensor_type in SENSOR_TYPES:
entities.append(GardenaSensor(sensor, s... | 5,347,097 |
def g16_vs_cnn():
""" Examine the DLAs in G16 against those in CNNo
Returns
-------
"""
# Load
cnn_dlas, dr12_dla, g16_abs, g16_dlas = load_dr12()
# DLA coords
dr12_dla_coord = SkyCoord(ra=dr12_dla['RA'], dec=dr12_dla['DEC'], unit='deg')
g16_coord = SkyCoord(ra=g16_dlas['RAdeg'], ... | 5,347,098 |
def integrate_intensity(data_sets, id, nθ, iN, NCO2, color1, color2):
"""Integrate intensity ove angle theta
Arguments:
data_sets {[type]} -- [description]
id {[type]} -- [description]
nθ {[type]} -- [description]
iN {[type]} -- [description]
NCO2 {[type]} -- [descri... | 5,347,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.