content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def log2_graph(x):
"""Log2'nin Uygulanması. TF'nin yerel bir uygulaması yoktur."""
return tf.log(x) / tf.log(2.0) | 5,304,100 |
def train_cnn():
"""Step 0: load sentences, labels, and training parameters"""
create_test = params["create_test"]
# load train, cat and and other path configurations from parameter file
train_file = params['train_file']
# cat_file = params['cat_file']
test_set_dir = params['test_set_dir']
... | 5,304,101 |
def readUniformElementTopologyFromXdmf(elementTopologyName,Topology,hdf5,topologyid2name,topology2nodes):
"""
Read xmdf element topology information when there are uniform elements in the mesh
Type of element given by elementTopologyName
Heavy data stored in hdf5
topologyid2name -- lookup for number... | 5,304,102 |
def ranknode(
data, out_path, entry_point, node_num, topk_path=60, prob_thres=0.4, num_sel_node=1
):
"""Rank node according to pearson correlation
"""
# region select X nodes from path
path_node_count = defaultdict(int)
# select only first topk paths with prob >= threshold
for i in o... | 5,304,103 |
def on_pod_create(body: Body, logger: Logger, **kwargs):
"""
Handle MySQL server Pod creation, which can happen when:
- cluster is being first created
- cluster is being scaled up (more members added)
"""
# TODO ensure that the pod is owned by us
pod = MySQLPod.from_json(body)
# check ... | 5,304,104 |
def fib(id):
"""
id: index (zero-based)
returns: Fibonacci number for the given index
id: 0 1 2 3 4 5 6 7
Fib: 0 1 1 2 3 5 8 13
"""
if id < 0:
return 0
if id == 0:
return 0
if id == 1:
return 1
first = 0
second = 1
counter = 2
fib_num = 0... | 5,304,105 |
def dso_nexus_search_user(url, login_username, login_password, verbose,
username):
"""Search for users by username on the Nexus instance specified by URL"""
with nexus.Nexus(
url, login_username, login_password, verbosity=verbose
) as api:
pprint(api.search_users(us... | 5,304,106 |
def montecarlo_coupled(model,T,func,delta,voxel,ode_method,sample_rate,
min_samples,max_samples,output_file):
""" Obtains statistics of model using a coupled monte carlo esimator. """
M0 = 10
Mmax = 10e5
samples = np.zeros((Mmax,model.dimension))
event_count = 0.
standdev = np.zeros(Mmax... | 5,304,107 |
def write_pb_types(xml_arch, arch_pb_types, tile_types, nsmap):
"""
Generates the "complexblocklist" section.
"""
# Complexblocklist
xml_cplx = xml_arch.find("complexblocklist")
if xml_cplx is None:
xml_cplx = ET.SubElement(xml_arch, "complexblocklist")
# Add pb_types
for pb_ty... | 5,304,108 |
def plot_trajectory_by_hour(
move_data,
start_hour,
end_hour,
id_=None,
legend=True,
n_rows=None,
lat_origin=None,
lon_origin=None,
zoom_start=12,
base_map=None,
tile=TILES[0],
save_as_html=False,
color="black",
filename="plot_trajectory_by_hour.html",
):
"""
... | 5,304,109 |
def adaptive_approximate_multi_index_sparse_grid(fun, variable, options):
"""
A light weight wrapper for building multi-index approximations.
Some checks are made to ensure certain required options have been provided.
See :func:`pyapprox.approximate.adaptive_approximate_sparse_grid` for more
detail... | 5,304,110 |
async def help_test_entity_debug_info_update_entity_id(
hass, mqtt_mock_entry_no_yaml_config, domain, config
):
"""Test debug_info.
This is a test helper for MQTT debug_info.
"""
await mqtt_mock_entry_no_yaml_config()
# Add device settings to config
config = copy.deepcopy(config[domain])
... | 5,304,111 |
def conv_from_weights(x, weights, bias=None, padding=True, name=""):
""" weights is a numpy array """
k = C.parameter(shape=weights.shape, init=weights)
y = C.convolution(k, x, auto_padding=[False, padding, padding])
if bias:
b = C.parameter(shape=bias.shape, init=bias)
y = y + bias
... | 5,304,112 |
def GenerateOutputList(context, resource_list):
"""Returns list of outputs generated by this module."""
vm_res = resource_list[0]
outputs = [{
'name': 'internalIP',
'value': '$(ref.%s.networkInterfaces[0].networkIP)' % vm_res['name'],
}]
external_ips = context.properties.get(EXTERNAL_IPS, [])
if... | 5,304,113 |
def execute_job(request):
"""
执行磁盘容量查询作业
"""
biz_id = request.POST.get('biz_id')
ip = request.POST.get('ip')
job_id = request.POST.get('job_id')
# 调用作业平台API,或者作业执行实例ID
client = get_client_by_request(request)
# client.set_bk_api_ver('v2')
result, job_instance_id = get_job_instan... | 5,304,114 |
def stt_mapper(result):
"""Returns the corrected text"""
best = result
variations = filter_stopwords(get_substrings(result))
n_grams = generate_n_grams(variations)
changed = []
for substring in n_grams:
no_change = False
for phrase in changed: #checks if a particular phrase has ... | 5,304,115 |
def delete():
""" Object delete handler """
app = get_app()
filename = '/'.join(request.args)
sender = request.vars.sender
if isinstance(sender, list): # ## fix a problem with Vista
sender = sender[0]
dialog = FORM.confirm(T('Delete'),
{T('Cancel'): URL(sende... | 5,304,116 |
def create_neutron_subnet(shade_client, network_name_or_id, cidr=None,
ip_version=4, enable_dhcp=False, subnet_name=None,
tenant_id=None, allocation_pools=None,
gateway_ip=None, disable_gateway_ip=False,
dns_nameserv... | 5,304,117 |
def test_validate_environment(env_def, strict, expected, expected_logs,
caplog, runway_context):
"""Test validate_environment."""
mock_module = MutableMap(name='test_module')
caplog.set_level(logging.DEBUG, logger='runway')
assert validate_environment(runway_context, mock_m... | 5,304,118 |
def compare(
expected_dir, actual_dir, file_pattern=None,
actual_extra=False, scrubs=None,
):
"""Compare files matching `file_pattern` in `expected_dir` and `actual_dir`.
A version-specific subdirectory of `expected_dir` will be used if
it exists.
`actual_extra` true means `act... | 5,304,119 |
def test_name_schema():
"""Start with a blank database."""
name_json = {"name": "my good company", "state": "NE", "conflict1": "conflict1", "conflict2": "conflict2", "conflict3": "conflict3", "consumptionDate": None, "designation": "LLC", "conflict1_num": "NR 0000001", "decision_text": "my descision", "conflic... | 5,304,120 |
def configure_logging(project_name: str = None):
"""
A general method to load the overall config of the system, specifically it modifies the root handler to output
to stdout and sets the default log levels and format. This is expected to be called once at the start of a
application.
"""
global _... | 5,304,121 |
def relu():
"""y = max(0, x)"""
pass | 5,304,122 |
def batch_get_data(lookup_ids: str, func: Callable[[object, List[str], str], Dict]):
"""Retrieve details for the list of AIDs provided.
Arguments
---------
lookup_ids: str
List of IDs to retrieve data for.
func: Python function, object
Method to call by each created thread.
Ret... | 5,304,123 |
def test_too_big_gap():
"""
Multiple BL raises. Act block is pointed to.
"""
line_markers = LineMarkers(8 * [''], 5)
line_markers.types[0] = LineType.func_def
line_markers.types[1] = LineType.arrange # x = 1
line_markers.types[2] = LineType.blank_line
line_markers.types[3] = LineType.bl... | 5,304,124 |
def regenerate_file(*t_args):
"""
(re)-generates the images for a given file
"""
if len(t_args)>0:
args=t_args[0]
if len(args)==0:
print "Missing id_source"
return
id_source = args[0]
#Add new source to the queue if not present ... | 5,304,125 |
def search_parameters_in_collection_value(item_id, item, attr_path=""):
""" Return the Parameter content of a single object in a collection.
This can be used to search for the parameter content of a list, dict,
tuple, series, dataframe and anything that can contain complex values and
have a unique iden... | 5,304,126 |
async def test_flow_no_devices_found(opp):
"""Test we get the form."""
await setup.async_setup_component(opp, "persistent_notification", {})
result = await opp.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert ... | 5,304,127 |
def genRegFunctionData(w, n):
"""
Saves 1 training and 3 testing data sets (each with n data points)
corresponding to the regDem function, sampled from different hypercubes
centered on the origin, a procedure described [1]
training_predictors, interpolation_predictors: [-w, w]^2
extrapolation_n... | 5,304,128 |
def test_plot3d_varying_transparency():
"""
Plot the data using z as transparency using 3-D column symbols.
"""
x = np.arange(1, 10)
y = np.arange(1, 10)
z = np.arange(1, 10) * 10
fig_ref, fig_test = Figure(), Figure()
# Use single-character arguments for the reference image
with GM... | 5,304,129 |
def set_trace_file_desc(*args):
"""
set_trace_file_desc(filename, description) -> bool
Change the description of the specified trace file.
@param filename (C++: const char *)
@param description (C++: const char *)
"""
return _ida_dbg.set_trace_file_desc(*args) | 5,304,130 |
def _get_group_on_off(state):
""" Determine the group on/off states based on a state. """
for states in _GROUP_TYPES:
if state in states:
return states
return None, None | 5,304,131 |
def compatibility_scores(h1, h2, dataset, device="cpu"):
"""
Args:
h1: Reference Pytorch model.
h2: The model being compared to h1.
dataset: Data in the form of a list of batches of input/target pairs.
device: A string with values either "cpu" or "cuda" to indicate the
... | 5,304,132 |
def reflect_image(w):
"""Reflects the image of the Evans function across the imaginary axis,
returning a numpy array that contains both the old points and the
reflected points.
"""
return np.concatenate((w,np.flipud(np.conj(w)))) | 5,304,133 |
def resumo(preco=0, taxaa=1, taxar=1):
"""
O uso do \t é para fazer a tabulação
"""
print('-+-'* 15)
print('RESUMO DO VALOR'.center(40))
print('-+-'* 15)
print(f'Preço analisado: \t{moeda(preco)}')
print(f'Dobro do preço: \t{dobro(preco, True)}')
print(f'Metade do preço: \t{metade(pr... | 5,304,134 |
def select_targets(infiles, numproc=4, cmxdir=None):
"""Process input files in parallel to select commissioning (cmx) targets
Parameters
----------
infiles : :class:`list` or `str`
A list of input filenames (tractor or sweep files) OR a single filename.
numproc : :class:`int`, optional, def... | 5,304,135 |
def get_pipeline(slug: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetPipelineResult:
"""
## # Data Source: pipeline
Use this data source to look up properties on a specific pipeline. This is
particularly useful for looking up the webhook URL for each... | 5,304,136 |
def connection_delete(context, name):
"""
Delete a WBEM connection definition.
Delete a named connection definition from the connections file. If the NAME
argument is omitted, a list of all connection definitions is displayed on
the terminal and a prompt for selecting one of these connections.
... | 5,304,137 |
def flatten_list(unflattened_list):
"""
Take list of iterables/non-iterables and outputs a list of non-iterables.
"""
flattened_list = []
for item in unflattened_list:
if hasattr(item, '__iter__') and not isinstance(item, str):
flattened_list.extend(item)
else:
... | 5,304,138 |
def CDLGRAVESTONEDOJI(equity, start=None, end=None):
"""Gravestone Doji
:return:
"""
opn = np.array(equity.hp.loc[start:end, 'open'], dtype='f8')
high = np.array(equity.hp.loc[start:end, 'high'], dtype='f8')
low = np.array(equity.hp.loc[start:end, 'low'], dtype='f8')
close = np.array(equity... | 5,304,139 |
def threshold_count(da, op, thresh, freq):
"""Count number of days above or below threshold.
Parameters
----------
da : xarray.DataArray
Input data.
op : {>, <, >=, <=, gt, lt, ge, le }
Logical operator, e.g. arr > thresh.
thresh : float
Threshold value.
freq : str
R... | 5,304,140 |
def _kill(app_id, scale, host):
"""
:param app_id: the id of the application
:type app_id: str
:param: scale: Scale the app down
:type: scale: bool
:param: host: Kill only those tasks running on host specified
:type: string
:returns: process return code
:rtype: int
"""
client... | 5,304,141 |
def publish_github_async(store, dataset, snapshot, github_remote):
"""Actual Github remote push. Can run on another queue, so it's its own task."""
ds = store.get_dataset(dataset)
publish_target(ds, github_remote, snapshot) | 5,304,142 |
def plot_all_loss(path='results.npy', save=False, figname='loss.pdf',
y_scale='linear', **kwargs):
"""
Plot the total loss of the discriminator and generator
:param save: bool, To save a picture. Default is False
:param figname: string, Figurename to save with extension
:param y_s... | 5,304,143 |
def depth_per_node(tree):
"""
calculcates depth per node in binary tree
Arguments:
----------
tree :
tree object with the same structure as
`sklearn.ensemble.DecisionTreeClassifier`
Returns:
--------
depth_vec : int array
vector of depth for each node
"""
... | 5,304,144 |
def right_click_func():
"""
Function to perform right click triggered by blinking
"""
global click_type
global TOTAL
mouse.click(button='right')
click_type = 'Right Click'
TOTAL = 0 | 5,304,145 |
def makeChain(name, sourceDir, cacheDir):
"""Parse the source text to generate new Markov chains."""
sourceFile = sourceDir + name + ".txt"
fwd = Markov.MarkovChain(cacheDir + name + "-fwd", 1, True)
try:
for line in open(sourceFile):
words = line.split()
if len(words) ... | 5,304,146 |
def test_load_ui_baseinstance():
"""Tests to see if the baseinstance loading loads a QWidget on properly"""
import sys
from Qt import QtWidgets, QtCompat
app = QtWidgets.QApplication(sys.argv)
win = QtWidgets.QWidget()
QtCompat.loadUi(self.ui_qwidget, win)
assert hasattr(win, 'lineEdit'), "l... | 5,304,147 |
def client(**kwargs):
"""Interface for building a client instance"""
return WoopraTracker(**kwargs) | 5,304,148 |
def common_meta(**kwargs):
"""Common meta setter
"""
caller = os.path.basename(inspect.stack()[2][1])
caller = caller[:caller.rfind(".")]
line_no = inspect.stack()[2][2]
kwargs['extra'] = {'_module': caller, '_lineno': line_no}
return logging.getLogger(GLOBAL_LOGGER_NAME), kwargs | 5,304,149 |
def read_ptn(
partition_filename: str
) -> Tuple[tuple, int, list, list, list]:
"""
Read partition file (.ptn) and extract information.
Parameters
----------
partition_filename : str
The filename of the .ptn partition file.
Returns
-------
valence_protons_neutrons :... | 5,304,150 |
def get_load_dir(dataset_lvl_dir, obj_type):
"""
Get load directory.
:param dataset_lvl_dir: dataset level directory
:param obj_type: objective function type
:returns load_dir: loading directory
"""
load_dir_list = glob(os.path.join(dataset_lvl_dir, obj_type, '*'))
return load_dir_list[... | 5,304,151 |
def sector_code_map(industry_code):
"""
国证行业分类映射为部门行业分类
国证一级行业分10类,转换为sector共11组,单列出房地产。
"""
if industry_code[:3] == 'C01':
return 309
if industry_code[:3] == 'C02':
return 101
if industry_code[:3] == 'C03':
return 310
if industry_code[:3] == 'C04':
r... | 5,304,152 |
def gen_normalized_adjs(dataset):
""" returns the normalized adjacency matrix
"""
row, col = dataset.graph['edge_index']
N = dataset.graph['num_nodes']
adj = SparseTensor(row=row, col=col, sparse_sizes=(N, N))
deg = adj.sum(dim=1).to(torch.float)
D_isqrt = deg.pow(-0.5)
D_isqrt[D_isqrt =... | 5,304,153 |
def flatten_deep(array):
"""Flattens a nested array recursively. This is the same as calling
``flatten(array, is_deep=True)``.
Args:
array (list): List to process.
Returns:
list: Flattened list.
Example:
>>> flatten_deep([[1], [2, [3]], [[4]]])
[1, 2, 3, 4]
.... | 5,304,154 |
def aten_transpose(mapper, graph, node):
""" 构造矩阵转置的PaddleLayer。
TorchScript示例:
%715 : Tensor = aten::transpose(%x.21, %704, %705)
参数含义:
%715 (Tensor): 输出,转置后的矩阵。
%x.21 (Tensor): 需要转置的Tensor。
%704 (int): 转置的维度1。
%705 (int): 转置的维度2。
"""
scope_name = mapper... | 5,304,155 |
def prepare_record(record: dict) -> Tuple[dict, dict]:
"""
Convert record data for DynamoDB insertion
record: updated record with json dumps fields for nested record values
original_nested_data: untouched nested key record data
"""
original_nested_data = {} # used for processing the results int... | 5,304,156 |
def frage_passwort():
""" Das Passwort Abfrage programm, verbessert als Funktion"""
SECRET_PASSWORD = "passwort1"
triesLeft = 3
correctPassword = False
while triesLeft > 0 and not correctPassword:
user_input = input("Geben Sie hier ihr Passwort ein:\n")
if(user_input == SECRET_PASS... | 5,304,157 |
def retrieve_by_id(location_id: int,
database_connection: mysql.connector.connect,
pre_validated_id: bool = False) -> Dict:
"""Returns an OrderedDict with location information based on
requested location ID
Arguments:
location_id (int)
database_connecti... | 5,304,158 |
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(description="MongoDB Mock OCSP Responder.")
parser.add_argument('-p', '--port', type=int, default=8080, help="Port to listen on")
parser.add_argument('-b', '--bind_ip', type=str, default=None, help="IP to listen on")
parser.add_a... | 5,304,159 |
def get_syst ( syst , *index ) :
"""Helper function to decode the systematic uncertainties
Systematic could be
- just a string
- an object with index: obj [ibin]
- a kind of function: func (ibin)
"""
if isinstance ( syst , str ) : return syst
elif syst and hasattr ( syst , '... | 5,304,160 |
def extract_doc_from_source(quiet=False):
"""
Write internal (pickled) TeX doc mdoc files and example data in docstrings.
"""
if not quiet:
print(f"Extracting internal doc data for {version_string}")
try:
return load_doc_data(settings.get_doc_tex_data_path(should_be_readable=True))
... | 5,304,161 |
def create_train_net_stats_function() -> TrainReturnFiller:
"""
Note:
Here the _TrainNNStatsElement objects are not process sensitive! Thus their id must
differ based on the process, so package_pos don't merge between processes.
"""
index_cnt: int = 0
last_local: ... | 5,304,162 |
def atomic_add(a: array[Any], i: int32, j: int32, k: int32, value: Any):
"""
Atomically add ``value`` onto the array at location given by indices.
"""
... | 5,304,163 |
def _test_spacetodepth(data, block_size):
"""One iteration of space_to_depth operation with given data and block size"""
with tf.Graph().as_default():
in_data = array_ops.placeholder(shape=data.shape, dtype=data.dtype)
array_ops.space_to_depth(in_data, block_size)
compare_tf_with_tvm(d... | 5,304,164 |
def load_invariants(ws_path):
"""
invariants yaml schema (incomplete):
Reachability: [{Ingress, Egress, DstIp, SrcIp, Protocol, DstPort, SrcPort, MaxFailures}]
"""
iv_path = os.path.join(ws_path, 'traces/invariants/'+trace+'.yml')
with open(iv_path) as f:
iv = yaml.load(f, Loader=yaml.... | 5,304,165 |
def fKzt(r,m,nout=2):
""" Returns Kzt according to yaw article """
fOye = 0.5 * (r + 0.4 * r ** 3 + 0.4 * r ** 5)
vr = r
Kzt = np.zeros(vr.shape)
Kztnum = np.zeros(vr.shape)
if m == 0:
raise Exception('Not intended for m==0')
k2 = ((1 - r) ** 2) / ((1 + r) ** 2)
m1 = (np.sqrt(1 +... | 5,304,166 |
def run_main(i_datastore_json, i_trf_fn, o_svsig_gz_fofn):
"""
i_datastore_json is a datastore json of multiple AlignmentSet or ConsensusAlignmentSet files.
Split each *AlignmentSet file to multiple chunked files, each of which must contain reads from
only one movie. Call `pbsv discover` on each chunk ... | 5,304,167 |
def test_conventional_style_breaking_change():
"""Breaking change (singular) is correctly identified."""
subject = "feat: this is a new breaking feature"
body = ["BREAKING CHANGE: there is a breaking feature in this code"]
commit = Commit(
commit_hash="aaaaaaa", subject=subject, body=body, autho... | 5,304,168 |
def weak_arg(arg):
""" Create a weak reference to arg and wrap the function so that the dereferenced
weakref is passed as the first argument. If arg has been deleted then the
funcion is not called.
"""
# Create the weak reference
weak_arg = weakref.ref(arg)
def decorator(function):
... | 5,304,169 |
async def embed(user_ns: dict = {}):
"""
Start an IPython shell in the current coroutine.
Unlike using :func:`IPython.embed` directly, the :keyword:`await` keyword
can be used directly from the shell to wait for triggers.
The :keyword:`yield` keyword from the legacy :ref:`yield-syntax` is not suppo... | 5,304,170 |
def run(verbose=True, display_progress=True, reserve_jobs=False, suppress_errors=False):
""" Run all `make` methods from element-deeplabcut
:param verbose: when True (default), display table names before populating
:param display_progress: when True (default) Show progress bar
:param reserve_jobs: when ... | 5,304,171 |
def black_list_second_mapper_test():
"""
将排序后的日志记录转化为热点时间列表:
access_time ip 1 --> ip [{ts:access_time,te:access_time,count:1}]
"""
# 打开记录文件
f_map = open("process_files/black_list_second_map.txt", "w", encoding="utf-8")
# 读取第一次reduce的结果
data = read_input("process_files/black_list_firs... | 5,304,172 |
def feature_manager():
""" Return a feature manager """
return FeatureManager() | 5,304,173 |
def test_find_points_pixel_one_image(ctx):
"""
Processing images should result in an array of pixel points."
"""
image = cv2.imread(ctx.test_image_path +
ctx.chessboard_image,
cv2.IMREAD_COLOR)
if image is not None:
gray = cv2.cvtColor(image, cv2... | 5,304,174 |
def square_image(image, pad_value=0):
"""Pad image array image such the shorter dimension is the same
as the longer one. Dimensions may be different (by 1 pixel)
if the longer dimension is odd.
Args:
image (np.array): 2D or 3D image array
pad_value (int): padding constant
... | 5,304,175 |
def infer_freq(av_seconds, tolerance=0.1):
"""Infer frequency of a time data series."""
if approx_equal(1, av_seconds, tolerance):
freq = 'S'
elif approx_equal(60, av_seconds, tolerance):
freq = 'T'
elif approx_equal(3600, av_seconds, tolerance):
freq = 'H'
elif approx_equal... | 5,304,176 |
def get_method_args_from_code(args, line):
"""Parse arguments from a stringified arguments list inside parentheses
Parameters
----------
args : list
A list where it's size matches the expected number of parsed arguments
line : str
Stringified line of code with method arguments insid... | 5,304,177 |
async def test_deprecated_temperature_conversion(
hass, caplog, enable_custom_integrations
):
"""Test warning on deprecated temperature conversion."""
platform = getattr(hass.components, "test.sensor")
platform.init(empty=True)
platform.ENTITIES["0"] = platform.MockSensor(
name="Test", nativ... | 5,304,178 |
def export_xmp(filename):
"""Exports an .xmp sidecar file from the image."""
try:
xmpfile = XMPFiles(file_path=filename)
except:
return None
return xmpfile.get_xmp() | 5,304,179 |
def gnmi(call, *args, **kwargs):
"""
Function to interact with devices using gNMI protocol utilising one of supported plugins.
:param call: (str) (str) connection object method to call or name of one of extra methods
:param plugin: (str) Name of gNMI plugin to use - pygnmi (default)
:param method_n... | 5,304,180 |
def get_disclosure_interests(code, start_date: datetime.date, end_date: datetime.date):
"""
http://sdinotice.hkex.com.hk/di/NSSrchCorp.aspx?src=MAIN&lang=ZH&in=1&
:param code:
:param start_date: datetime.date
:param end_date: datetime.date
:return: DataFrame or None
"""
# HKEX sharehold... | 5,304,181 |
def string_to_slice(string):
"""convert a string into a slice"""
s = request_slice()
if string != '':
memory_values[s] = list(map(lambda x: ord(x.encode('utf-8')), list(string)))
memory_size[s] = len(memory_values[s])
else:
set_slice_last_index(s, -1)
return s | 5,304,182 |
def test_valid_parsing_generic(verifiable_sdf_string):
"""
Test is successful if it doesn't produce an error. This isn't super amazing
so it might be refactored once I have more sophisticated tests. Meanwhile it
hits on quite a few edge cases of the SDFormat that need to be handled
correctly.
""... | 5,304,183 |
def check_3(df, nm):
"""
Checks that nm, amount adsorbed in the monolayer, is in the range of
data points used in BET analysis.
Parameters
----------
df : dataframe
Dataframe of imported experimental isothermal adsorption data.
nm : array
2D array of BET specific amount of ... | 5,304,184 |
def load_flow(vid_path, fps, start_time, offset_sec=0):
"""
load optical flow given a video.
Args:
vid_path: str, video path
fps: float, fps
start_time: int, start time unixtime in milliseconds
offset_sec: float, start offset in seconds
Returns:
dataframe, optica... | 5,304,185 |
def get_open_dns_resolvers(input_stream, whitelist_domains, whitelist_networks):
"""
Gets used open dns resolvers from input stream
:param input_stream: Input flows
:param whitelist_domains: Regex containing all whitelisted domains
:param whitelist_networks: Array with all whitelisted networks
... | 5,304,186 |
def get_repo(repo, **kwargs):
"""
Display a repo from the sources.list / sources.list.d
The repo passed in needs to be a complete repo entry.
CLI Examples:
.. code-block:: bash
salt '*' pkg.get_repo "myrepo definition"
"""
_check_apt()
ppa_auth = kwargs.get("ppa_auth", None)
... | 5,304,187 |
def create_nic(network_client):
"""Create a Network Interface for a VM.
"""
# Create public ip
creation_result = create_public_ip_address(network_client)
print("------------------------------------------------------")
print(creation_result)
# Create VNet
print('\nCreate Vnet')
async... | 5,304,188 |
def dya(series, n=1):
"""Difference over n years, annualized"""
return (series-series.shift(n*series.index.freq.periodicity)) / n | 5,304,189 |
def new_entry(sector: dict, trying: str) -> bool:
"""
Checks if the text need a new entry.
"""
return sector["color"] is not None and color.__contains__(trying) | 5,304,190 |
def node(env, node_name):
"""Display a dashboard for a node showing as much data as we have on that
node. This includes facts and reports but not Resources as that is too
heavy to do within a single request.
:param env: Ensure that the node, facts and reports are in this environment
:type env: :obj... | 5,304,191 |
def Tanh(input_size, hidden_size, num_layers, bias=True, batch_first=False, dropout=0, bidirectional=False, output_size = None):
"""
Tanh stub
"""
inputRNN = RNNCell(1, input_size, hidden_size, _rnn_impls['RNN_TANH'], 1, bias, output_size)
inputRNN = RNNCell(1, input_size, hidden_size, RNNTanhCell, ... | 5,304,192 |
def combine_config(input_configs: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Combine multiple dcm2bids config dicts into a single config dict.
Args:
input_configs (list[dict[str, Any]]): A list of dcm2bids configs (dicts)
Returns:
dict[str, Any]: The combined/merged config dict.
"""
... | 5,304,193 |
def test_configure_logging_development(caplog: LogCaptureFixture) -> None:
"""Test that development-mode logging is key-value formatted."""
caplog.set_level(logging.INFO)
configure_logging(name="myapp", profile="development", log_level="info")
assert safir_logging.logger_name == "myapp"
logger = s... | 5,304,194 |
def dup_gegenbauer(n, a, K):
"""Low-level implementation of Gegenbauer polynomials."""
seq = [[K.one], [K(2)*a, K.zero]]
for i in range(2, n + 1):
f1 = K(2) * (i + a - K.one) / i
f2 = (i + K(2)*a - K(2)) / i
p1 = dmp_mul_ground(dup_lshift(seq[-1], 1, K), f1, 0, K)
p2 = dmp_m... | 5,304,195 |
def test_num_training_batches(tmpdir):
"""Tests that the correct number of batches are allocated."""
# when we have fewer batches in the dataloader we should use those instead of the limit
model = EvalModelTemplate()
trainer = Trainer(limit_val_batches=100, limit_train_batches=100, max_epochs=1, default... | 5,304,196 |
def find_projects(company_name, project_list):
"""returns list of projects associated with company_name
:param company_name: name of company to return projects for
:type company_name: str
:param project_list: list of projects as dictionaries
:type project_list: list
:return: list
"""
re... | 5,304,197 |
def log_to_stdout(level=15):
"""
Adds the stdout to the logging stream and sets the level to 15 by default
"""
import logging
logger = logging.getLogger("fetch_data")
# remove existing file handlers
for handler in logger.handlers:
if isinstance(handler, logging.StreamHandler):
... | 5,304,198 |
def dh_to_trans_mats(dh_params: np.ndarray) -> np.ndarray:
"""Convert Denavit–Hartenberg parameters into relative transformation
matrices.
Args:
dh_params (np.ndarray): An #Nx4 array of DH parameters, which are
expected to have rows which correspond to the joints, and columns
... | 5,304,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.