content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def sackStringToSack(sackString):
"""
C{sackString} is a C{str}. Returns a L{window.SACK}.
"""
try:
# If not enough args for split, Python raises ValueError
joinedSackList, ackNumberStr = sackString.rsplit('|', 1)
ackNumber = strToIntInRange(ackNumberStr, -1, 2**53)
sackList = tuple(strToNonNegLimit(s, 2**... | 9,300 |
def setup_graph(event, sta, chan, band,
tm_shape, tm_type, wm_family, wm_type, phases,
init_run_name, init_iteration, fit_hz=5, uatemplate_rate=1e-4,
smoothing=0, dummy_fallback=False,
raw_signals=False, init_templates=False, **kwargs):
"""
Set u... | 9,301 |
def _update_sidecar(sidecar_fname, key, val):
"""Update a sidecar JSON file with a given key/value pair.
Parameters
----------
sidecar_fname : str | os.PathLike
Full name of the data file
key : str
The key in the sidecar JSON file. E.g. "PowerLineFrequency"
val : str
The... | 9,302 |
def raw_dataset_fp(tmpdir: pathlib.Path) -> str:
"""Generates dataset to be used in this test.
Returns (str): file path string for dataset to use in this tests
"""
raw_fp = os.path.join(tmpdir, "raw_data.csv")
random.seed(42)
cli_synthesize_dataset(64, INPUT_FEATURES + OUTPUT_FEATURES, raw_fp)... | 9,303 |
def insert_devices_hostname(db_connection, hostnames):
"""
Function stores data into the database, particularly in the node_log table.
Arguments:
- db_connection: sqlite3 database connection
- hostnames: Dictionary which contains MAC address as a key and hostname
as a value.
"""
for key, value in ho... | 9,304 |
def parse(owl_f, pred_list, m):
"""
From an owl file parses subject and objects from each predicate to extract
:param owl_f: owl file path
:param pred_list: list of predicates to extract
:param m: model class
:return:
"""
g = rdflib.Graph()
g.load(owl_f)
for subject, predicate,... | 9,305 |
def getLogisticModelNames(config):
"""
Get the names of the models present in the configobj
Args:
config: configobj object defining the model and its inputs.
Returns:
list: list of model names.
"""
names = []
lmodel_space = config
for key, value in lmodel_space.items():... | 9,306 |
def checkfileCopyright(filename):
""" return true if file has already a Copyright in first X lines """
infile = open(filename, 'r')
for x in xrange(6):
x = x
line = infile.readline()
if "Copyright" in line or "copyright" in line:
return True
return False | 9,307 |
def TopicFormat(topic_name, topic_project=''):
"""Formats a topic name as a fully qualified topic path.
Args:
topic_name: (string) Name of the topic to convert.
topic_project: (string) Name of the project the given topic belongs to.
If not given, then the project defaults to the currentl... | 9,308 |
def mp0(g0):
"""Return 0th order free energy."""
return g0.sum() | 9,309 |
def create_diamond(color=None):
"""
Creates a diamond.
:param color: Diamond color
:type color: list
:return: OpenGL list
"""
# noinspection PyArgumentEqualDefault
a = Point3(-1.0, -1.0, 0.0)
# noinspection PyArgumentEqualDefault
b = Point3(1.0, -1.0, 0.0)
# noinspection PyA... | 9,310 |
def merge_dicts(*dicts):
"""
Recursive dict merge.
Instead of updating only top-level keys,
dict_merge recurses down into dicts nested
to an arbitrary depth, updating keys.
"""
assert len(dicts) > 1
dict_ = copy.deepcopy(dicts[0])
for merge_dict in dicts[1:]:
for k, v i... | 9,311 |
def getAllFWImageIDs(fwInvDict):
"""
gets a list of all the firmware image IDs
@param fwInvDict: the dictionary to search for FW image IDs
@return: list containing string representation of the found image ids
"""
idList = []
for key in fwInvDict:
if 'Version' in fwInv... | 9,312 |
def main():
"""Make a jazz noise here"""
args = get_args()
random.seed(args.seed)
count_file, count_seq = 1, 0
if not os.path.isdir(args.outdir):
os.makedirs(args.outdir)
for fh in args.FILE:
basename = os.path.basename(fh.name)
out_file = os.path.join(args.outdir,... | 9,313 |
def create_dataset(dataset_path, batch_size=1, repeat_size=1, max_dataset_size=None,
shuffle=True, num_parallel_workers=1, phase='train', data_dir='testA', use_S=False):
""" create Mnist dataset for train or eval.
dataset_path: Data path
batch_size: The number of data records in each grou... | 9,314 |
def setup_files():
"""
Clears the csv results files
"""
with open("training_results.csv", 'wb') as f:
wr = csv.writer(f, quoting=csv.QUOTE_NONNUMERIC)
header = ["Subject Number", "Round Number", "Dominant Eye",
"Pair Number", "Name 1", "Name 2"]
wr.writerow(hea... | 9,315 |
def save_model(model, save_path):
"""Saves model with pickle
Parameters
----------
model : object
trained ML model
save_path : str
save directory
"""
with open(save_path, 'wb') as outfile:
dump(model, outfile)
print('Model saved at:', save_path) | 9,316 |
def document_uris_from_data(document_data, claimant):
"""
Return one or more document URI dicts for the given document data.
Returns one document uri dict for each document equivalence claim in
document_data.
Each dict can be used to init a DocumentURI object directly::
document_uri = Doc... | 9,317 |
def get_bond_angle_index(edge_index):
"""
edge_index: (2, E)
bond_angle_index: (3, *)
"""
def _add_item(
node_i_indices, node_j_indices, node_k_indices,
node_i_index, node_j_index, node_k_index):
node_i_indices += [node_i_index, node_k_index]
node_j_indices +=... | 9,318 |
def get_config(section=None, option=None):
"""Return dpm configuration objects.
:param section:
the name of the section in the ini file, e.g. "index:ckan".
- May be omitted only when no other parameters are provided
- Must be omitted elsewhere
:type section: str
:param ... | 9,319 |
def display_pixels(pixels_states, instance, fg=[255, 255, 255], bg=[0, 0, 0]):
"""Given the states of each pixels (1 = on, 0 = off) in a list,
we display the list on the led matrix"""
instance.set_pixels([fg if state else bg for state in pixels_states]) | 9,320 |
def update_repo(name, repo, variant, registry, prefix):
"""
1. generate the kiwi file
2. pull down kiwi file from server
3. if same, skip
4. bco the project/package to a temp location
5. oosc ar
6. display diff
7. prompt for changelog entry (reuse result for other repos for same image)
... | 9,321 |
def match_intervals(intervals_from, intervals_to, strict=True):
"""Match one set of time intervals to another.
This can be useful for tasks such as mapping beat timings
to segments.
Each element ``[a, b]`` of ``intervals_from`` is matched to the
element ``[c, d]`` of ``intervals_to`` which maximiz... | 9,322 |
def correlate(x, y, margin, method='pearson'):
""" Find delay and correlation between x and each column o y
Parameters
----------
x : `pandas.Series`
Main signal
y : `pandas.DataFrame`
Secondary signals
method : `str`, optional
Correlation method. Defaults to `pearson`. ... | 9,323 |
def write_question_settings(session, settings, question_class, json_path):
# type: (Session, Dict[str, Any], str, Optional[List[str]]) -> None
"""Writes settings for a question class."""
if not session.network:
raise ValueError("Network must be set to write question class settings")
json_path_ta... | 9,324 |
def sortList2(head: ListNode) -> ListNode:
"""down2up"""
h, length, intv = head, 0, 1
while h: h, length = h.next, length + 1
res = ListNode(0)
res.next = head
# merge the list in different intv.
while intv < length:
pre, h = res, res.next
while h:
# get the two m... | 9,325 |
def _inverse_frequency_max(searcher, fieldname, term):
"""
Inverse frequency smooth idf schema
"""
n = searcher.doc_frequency(fieldname, term)
maxweight = searcher.term_info(fieldname, term).max_weight()
return log(1 + (maxweight / n), 10) if n != 0.0 else 0.0 | 9,326 |
def main():
"""
This function obtains hosts from core and starts a nessus scan on these hosts.
The nessus tag is appended to the host tags.
"""
config = Config()
core = HostSearch()
hosts = core.get_hosts(tags=['!nessus'], up=True)
hosts = [host for host in hosts]
host_ips = ... | 9,327 |
def test_ap_config_set_errors(dev, apdev):
"""hostapd configuration parsing errors"""
hapd = hostapd.add_ap(apdev[0], { "ssid": "foobar" })
hapd.set("wep_key0", '"hello"')
hapd.set("wep_key1", '"hello"')
hapd.set("wep_key0", '')
hapd.set("wep_key0", '"hello"')
if "FAIL" not in hapd.request("... | 9,328 |
def ha(data):
"""
Hadamard Transform
This function is very slow. Implement a Fast Walsh-Hadamard Transform
with sequency/Walsh ordering (FWHT_w) for faster tranforms.
See:
http://en.wikipedia.org/wiki/Walsh_matrix
http://en.wikipedia.org/wiki/Fast_Hadamard_transform
"""
# i... | 9,329 |
def most_repeated_character(string: str) -> str:
"""
Find the most repeated character in a string.
:param string:
:return:
"""
map: Dict[str, int] = {}
for letter in string:
if letter not in map:
map[letter] = 1
else:
map[letter] += 1
return sort... | 9,330 |
def read_config(config_filename):
"""Read the expected system configuration from the config file."""
config = None
with open(config_filename, 'r') as config_file:
config = json.loads(config_file.read())
config_checks = []
for config_check in config:
if '_comment' in config_check:
... | 9,331 |
def transitions(bits):
"""Count the number of transitions in a bit sequence.
>>> assert transitions([0, 0]) == 0
>>> assert transitions([0, 1]) == 1
>>> assert transitions([1, 1]) == 0
>>> assert transitions([1, 0]) == 1
>>> assert transitions([0, 0, 0]) == 0
>>> assert transitions([0, 1, 0... | 9,332 |
def _convert_code(code):
"""
ๅฐ่ๅฎฝๅฝขๅผ็ไปฃ็ ่ฝฌๅไธบ xalpha ๅฝขๅผ
:param code:
:return:
"""
no, mk = code.split(".")
if mk == "XSHG":
return "SH" + no
elif mk == "XSHE":
return "SZ" + no | 9,333 |
def _is_arg_name(s, index, node):
"""Search for the name of the argument. Right-to-left."""
if not node.arg:
return False
return s[index : index+len(node.arg)] == node.arg | 9,334 |
def fitNoise(Sm_bw, L, K, Gamma):
""" Estimate noise parameters
Parameters
----------
Sm_bw : float array
Sufficient statistics from measurements
Sm_fw : float array
Wavefield explained by modeled waves
Returns
-------
BIC : float
Value of the Bayesian informat... | 9,335 |
def compress_dir(outpath, deleteold=True):
""" Compress the directory of outpaths
"""
outpath = str(outpath)
file = outpath.split('/')[-1]
# print(f'Compressing from these files: {os.listdir(outpath)}')
# print('compressing directory: {}'.format(outpath))
t0 = time.time()
with tarfi... | 9,336 |
def run_command(cmd, debug=False):
"""
Execute the given command and return None.
:param cmd: A `sh.Command` object to execute.
:param debug: An optional bool to toggle debug output.
:return: ``sh`` object
"""
if debug:
print_debug('COMMAND', str(cmd))
return cmd() | 9,337 |
def goodness(signal, freq_range=None, D=None):
"""Compute the goodness of pitch of a signal."""
if D is None:
D = libtfr.dpss(len(signal), 1.5, 1)[0]
signal = signal * D[0, :]
if freq_range is None:
freq_range = 256
if np.all(signal == 0):
return 0
else:
return np... | 9,338 |
def set_request_path(db_object_id=None, request_path=None, **kwargs):
"""Sets the request_path of the given db_object
Args:
db_object_id (int): The id of the schema to list the db_objects from
request_path (str): The request_path that should be set
**kwargs: Additional options
Keyw... | 9,339 |
def checkForRawFile(op, graph, frm, to):
"""
Confirm the source is a raw image.
:param op:
:param graph:
:param frm:
:param to:
:return:
@type op: Operation
@type graph: ImageGraph
@type frm: str
@type to: str
"""
snode = graph.get_node(frm)
exifdata = ex... | 9,340 |
def check_main_dependent_group(setup_contents: str) -> None:
"""
Test for an order of dependencies groups between mark
'# Start dependencies group' and '# End dependencies group' in setup.py
"""
print("[blue]Checking main dependency group[/]")
pattern_main_dependent_group = re.compile(
'... | 9,341 |
def createComparativeSurfPlot(dim, path2SignDir, subSignList, modFileNameList):
"""
@param[in] ### dim ### integer corresponding to the dimension of the approximation domain
@param[in] ### path2SignDir ### string giving the path to the directory of the training session which should
be investigated
@param[in] ... | 9,342 |
def register_relation_in_alias_manager(field: Type["ForeignKeyField"]) -> None:
"""
Registers the relation (and reverse relation) in alias manager.
The m2m relations require registration of through model between
actual end models of the relation.
Delegates the actual registration to:
m2m - regi... | 9,343 |
def test_modelize_summary():
"""
Report document should be correctly modelized from given report
"""
reports = [
(
"/html/foo.html",
{
"messages": [
"ping",
"pong",
],
"statistics": {"... | 9,344 |
def get_ip_address(dev="eth0"):
"""Retrieves the IP address via SIOCGIFADDR - only tested on Linux."""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', dev[:15]))[20:24])
except:
return None | 9,345 |
def connect(**kwargs): # pylint: disable=unused-argument
"""
mock get-a-connection
"""
return MockConn() | 9,346 |
def new_organization(request):
"""Creates a new organization."""
if request.method == 'POST':
new_organization_form = OrganizationForm(request.POST)
if new_organization_form.is_valid():
new_organization = new_organization_form.save(commit=False)
new_organization.owner = ... | 9,347 |
def _build_obs_freq_mat(acc_rep_mat):
"""
build_obs_freq_mat(acc_rep_mat):
Build the observed frequency matrix, from an accepted replacements matrix
The acc_rep_mat matrix should be generated by the user.
"""
# Note: acc_rep_mat should already be a half_matrix!!
total = float(sum(acc_rep_mat... | 9,348 |
def strip(s):
"""strip(s) -> string
Return a copy of the string s with leading and trailing
whitespace removed.
"""
i, j = 0, len(s)
while i < j and s[i] in whitespace: i = i+1
while i < j and s[j-1] in whitespace: j = j-1
return s[i:j] | 9,349 |
def set_news(title: str, text: str, db_user: User, lang: str, main_page: str) -> dict:
"""
Sets a new news into the news table
:param title: of the news
:param text: of the news
:param db_user: author of the news
:param lang: ui_locales
:param main_page: url
:return:
"""
LOG.deb... | 9,350 |
def make_index_file(out_dir, files):
"""Write an index file."""
files = [os.path.splitext(os.path.basename(x))[0] for x in files]
with open(os.path.join(out_dir, 'idx'), 'wb') as f:
pickle.dump(files, f, pickle.HIGHEST_PROTOCOL) | 9,351 |
def _test_theano_compiled_dtw(input_size, hidden_size, ndim, distance_function, normalize, enable_grads, debug_level,
eps):
"""
Performs a test of a Theano DTW implementation.
:param input_size: The size of the inputs.
:param hidden_size: The size of the hidden values (use... | 9,352 |
def connections_definition():
"""Connection definition in connections.yml"""
out = pygments.highlight(
code=(Settings.typhoon_home / 'connections.yml').read_text(),
lexer=YamlLexer(),
formatter=Terminal256Formatter()
)
pydoc.pager(out) | 9,353 |
def test(seriesList):
"""This is a test function"""
return seriesList | 9,354 |
def perform_timeseries_analysis_iterative(dataset_in, intermediate_product=None, no_data=-9999):
"""
Description:
-----
Input:
dataset_in (xarray.DataSet) - dataset with one variable to perform timeseries on
Output:
dataset_out (xarray.DataSet) - dataset containing
variables: no... | 9,355 |
def getDayOfYear(date):
# type: (Date) -> int
"""Extracts the day of the year from a date.
The first day of the year is day 1.
Args:
date: The date to use.
Returns:
An integer that is representative of the extracted value.
"""
print(date)
return _now().timetuple().tm_y... | 9,356 |
def predict(network, X_test):
"""์ ๊ฒฝ๋ง์์ ์ฌ์ฉ๋๋ ๊ฐ์ค์น ํ๋ ฌ๋ค๊ณผ ํ
์คํธ ๋ฐ์ดํฐ๋ฅผ ํ๋ผ๋ฏธํฐ๋ก ์ ๋ฌ๋ฐ์์,
ํ
์คํธ ๋ฐ์ดํฐ์ ์์ธก๊ฐ(๋ฐฐ์ด)์ ๋ฆฌํด.
ํ๋ผ๋ฏธํฐ X_test: 10,000๊ฐ์ ํ
์คํธ ์ด๋ฏธ์ง๋ค์ ์ ๋ณด๋ฅผ ๊ฐ์ง๊ณ ์๋ ๋ฐฐ์ด
"""
y_pred = []
for sample in X_test: # ํ
์คํธ ์ธํธ์ ๊ฐ ์ด๋ฏธ์ง๋ค์ ๋ํด์ ๋ฐ๋ณต
# ์ด๋ฏธ์ง๋ฅผ ์ ๊ฒฝ๋ง์ ์ ํ(ํต๊ณผ)์์ผ์ ์ด๋ค ์ซ์๊ฐ ๋ ์ง ํ๋ฅ ์ ๊ณ์ฐ.
sample_hat = forward(network, sa... | 9,357 |
def test_bad_set_value():
""" Test setting an impossible value """
packet = Packet()
with pytest.raises(TypeError):
packet['uint8'] = 65535
with pytest.raises(TypeError):
packet['uint8'] = 'foo'
with pytest.raises(TypeError):
packet['uint8'] = b'bar'
with pytest.raises(Ty... | 9,358 |
def best_fit_decreasing(last_n_vm_cpu, hosts_cpu, hosts_ram,
inactive_hosts_cpu, inactive_hosts_ram,
vms_cpu, vms_ram):
"""The Best Fit Decreasing (BFD) heuristic for placing VMs on hosts.
:param last_n_vm_cpu: The last n VM CPU usage values to average.
:para... | 9,359 |
def __sanitize_close_input(x, y):
"""
Makes sure that both x and y are ht.DNDarrays.
Provides copies of x and y distributed along the same split axis (if original split axes do not match).
"""
def sanitize_input_type(x, y):
"""
Verifies that x is either a scalar, or a ht.DNDarray. I... | 9,360 |
def _is_buildbot_cmdline(cmdline):
"""Returns (bool): True if a process is a BuildBot process.
We determine this by testing if it has the command pattern:
[...] [.../]python [.../]twistd [...]
Args:
cmdline (list): The command line list.
"""
return any((os.path.basename(cmdline[i]) == 'python' and
... | 9,361 |
def _deps_to_compile_together(dependency_graph):
"""Yield a chunk of (outfile, depnode) pairs.
The rule is that we yield all the chunks at level 1 before any
chunks at level 2, etc. Each chunk holds only files with the same
compile_instance. The caller is still responsible for divvying up
chunks ... | 9,362 |
def analyze_J_full_movie(folder_name,include_eps=False):
"""Analyze the Jacobian -- report timeseries parmeters. Must first run compute_F_whole_movie()."""
# set up folders
external_folder_name = 'ALL_MOVIES_PROCESSED'
if not os.path.exists(external_folder_name):
os.makedirs(external_folder_name)
out_analysis =... | 9,363 |
def seed_everything(seed: int = 42) -> None:
"""
Utility function to seed everything.
"""
random.seed(1)
np.random.seed(seed)
tf.random.set_seed(seed) | 9,364 |
def table_information_one(soup, div_id_name: str = None) -> dict:
""" first method for bringing back table information as a dict.
works on:
parcelInfo
SummaryPropertyValues
SummarySubdivision
"""
table = []
for x in soup.find_all("div", {"id": div_id_name}):
for div i... | 9,365 |
def Eval_point_chan(state, chan, data):
"""External validity, along a channel, where point-data is a
pulled back along the channel """
# for each element, state.sp.get(*a), of the codomain
vals = [(chan >> state)(*a) ** data(*a) for a in data.sp.iter_all()]
val = functools.reduce(lambda p1, p2: ... | 9,366 |
def dfi2pyranges(dfi):
"""Convert dfi to pyranges
Args:
dfi: pd.DataFrame returned by `load_instances`
"""
import pyranges as pr
dfi = dfi.copy()
dfi['Chromosome'] = dfi['example_chrom']
dfi['Start'] = dfi['pattern_start_abs']
dfi['End'] = dfi['pattern_end_abs']
dfi['Name'] = ... | 9,367 |
def cleared_nickname(nick: str) -> str:
"""Perform nickname clearing on given nickname"""
if nick.startswith(('+', '!')):
nick = nick[1:]
if nick.endswith('#'):
nick = nick[:-1]
if all(nick.rpartition('(')):
nick = nick.rpartition('(')[0]
return nick | 9,368 |
def validate_model_on_lfw(
strategy,
model,
left_pairs,
right_pairs,
is_same_list,
) -> float:
"""Validates the given model on the Labeled Faces in the Wild dataset.
### Parameters
model: The model to be tested.
dataset: The Labeled Faces in the Wild dataset, loaded from loa... | 9,369 |
def com_google_fonts_check_repo_upstream_yaml_has_required_fields(upstream_yaml):
"""Check upstream.yaml file contains all required fields"""
required_fields = set(["branch", "files", "repository_url"])
upstream_fields = set(upstream_yaml.keys())
missing_fields = required_fields - upstream_fields
i... | 9,370 |
def get_allsongs():
"""
Get all the songs in your media server
"""
conn = database_connect()
if(conn is None):
return None
cur = conn.cursor()
try:
# Try executing the SQL and get from the database
sql = """select
s.song_id, s.song_title, string_agg(saa.... | 9,371 |
def nlu_audio(settings, logger):
"""Wrapper for NLU audio"""
speech_args = settings['speech']
loop = asyncio.get_event_loop()
interpretations = {}
with Recorder(loop=loop) as recorder:
interpretations = loop.run_until_complete(understand_audio(
loop,
speech_args['url'... | 9,372 |
def _gauss(sigma, n_sigma=3):
"""Discrete, normalized Gaussian centered on zero. Used for filtering data.
Args:
sigma (float): standard deviation of Gaussian
n_sigma (float): extend x in each direction by ext_x * sigma
Returns:
ndarray: discrete Gaussian curve
"""
x_range... | 9,373 |
def write_json_file(path, json_data):
"""write content in json format
Arguments:
path {string} -- path to store json file
json_data {dictionary} -- dictionary of data to write in json
"""
with open(path+'.json', 'w+') as writer:
json.dump(json_data, writer)
writer.close... | 9,374 |
def create_tentacle_mask(points, height, width, buzzmobile_width, pixels_per_m):
"""Creates a mask of a tentacle by drawing the points as a line."""
tentacle_mask = np.zeros((height, width), np.uint8)
for i in range(len(points) - 1):
pt1 = points[i]
pt2 = points[i+1]
cv2.line(tentacl... | 9,375 |
def fill_profile_list(
profile_result: ProfileResult,
optimizer_result: Dict[str, Any],
profile_index: Iterable[int],
profile_list: int,
problem_dimension: int,
global_opt: float
) -> None:
"""
This is a helper function for initialize_profile
Parameters
-... | 9,376 |
def _matrix_to_real_tril_vec(matrix):
"""Parametrize a positive definite hermitian matrix using its Cholesky decomposition"""
tril_matrix = la.cholesky(matrix, lower=True)
diag_vector = tril_matrix[np.diag_indices(tril_matrix.shape[0])].astype(float)
complex_tril_vector = tril_matrix[np.tril_indices(tri... | 9,377 |
def is_subdir(path, directory):
"""Check if path is a sub of directory.
Arguments:
path (string):
the path to check
direcotry (string):
the path to use as relative starting point.
Returns:
bool: True if path is a sub of directory or False otherwise.
"""
... | 9,378 |
def func6():
"""
# Train on new dataset
Here we will train on the Sheep dataset.
First we will clone and split the dataset to 2 partitions - train and validation.
After that we will clone the pretrained snapshot
""" | 9,379 |
def main():
"""
Insantiates a Main object and executes it.
The 'standalone_mode' is so that click doesn't handle usage-exceptions
itself, but bubbles them up.
Arguments:
args (tuple): The command-line arguments.
"""
args = sys.argv[1:]
# If stdin is not empty (being piped to)
if not sys.stdin.isatty():
a... | 9,380 |
def max_pool(pool_size, strides, padding='SAME', name=None):
"""max pooling layer"""
return tf.layers.MaxPooling2D(pool_size, strides, padding, name=name) | 9,381 |
def size_as_minimum_int_or_none(size):
"""
:return: int, max_size as max int or None. For example:
- size = no value, will return: None
- size = simple int value of 5, will return: 5
- size = timed interval(s), like "2@0 22 * * *:24@0 10 * * *", will return: 2
"""
... | 9,382 |
def args_to_numpy(args):
"""Converts all Torch tensors in a list to NumPy arrays
Args:
args (list): list containing QNode arguments, including Torch tensors
Returns:
list: returns the same list, with all Torch tensors converted to NumPy arrays
"""
res = []
for i in ... | 9,383 |
def optimizer_setup(model, params):
"""
creates optimizer, can have layer specific options
"""
if params.optimizer == 'adam':
if params.freeze_backbone:
optimizer = optimizer_handler.layer_specific_adam(model, params)
else:
optimizer = optimizer_handler.plain_adam... | 9,384 |
def charToEmoji(char, spaceCounter=0):
"""
If you insert a space, make sure you have your own
space counter and increment it. Space counter goes from 0 to 3.
"""
if char in emojitable.table:
print(char)
if char == ' ':
emoji = emojitable.table[char][spaceCounter]
... | 9,385 |
def averages_area(averages):
"""
Computes the area of the polygon formed by the hue bin averages.
Parameters
----------
averages : array_like, (n, 2)
Hue bin averages.
Returns
-------
float
Area of the polygon.
"""
N = averages.shape[0]
triangle_areas = np... | 9,386 |
def _tree_cmp(fpath1: PathLike, fpath2: PathLike, tree_format: str = 'newick') -> bool:
"""Returns True if trees stored in `fpath1` and `fpath2` are equivalent, False otherwise.
Args:
fpath1: First tree file path.
fpath2: Second tree file path.
tree_format: Tree format, i.e. ``newick``,... | 9,387 |
def parse_genemark(input_f, genbank_fp):
""" Extract atypical genes identified by GeneMark
Parameters
----------
input_f: string
file descriptor for GeneMark output gene list (*.lst)
genbank_fp: string
file path to genome in GenBank format
Notes
-----
genbank_fp is the ... | 9,388 |
def get_hex(fh, nbytes=1):
"""
get nbyte bytes (1 by default)
and display as hexidecimal
"""
hstr = ""
for i in range(nbytes):
b = "%02X " % ord(fh)
hstr += b
return hstr | 9,389 |
def fetch(pages, per_page, graph):
"""
Get a list of posts from facebook
"""
return [x.replace('\n', '')
for name in pages
for x in fetch_page(name, per_page, graph)] | 9,390 |
def lifted_struct_loss(labels, embeddings, margin=1.0):
"""Computes the lifted structured loss.
Args:
labels: 1-D tf.int32 `Tensor` with shape [batch_size] of
multiclass integer labels.
embeddings: 2-D float `Tensor` of embedding vectors. Embeddings should
not be l2 normalized.
... | 9,391 |
def get_uint8_rgb(dicom_path):
"""
Reads dicom from path and returns rgb uint8 array
where R: min-max normalized, G: CLAHE, B: histogram equalized.
Image size remains original.
"""
dcm = _read_dicom_image(dicom_path)
feats = _calc_image_features(dcm)
return (feats*255).astype(np.uint8) | 9,392 |
def start(host, port, options, timeout=10):
"""Start an instance of mitmproxy server in a subprocess.
Args:
host: The host running mitmproxy.
port: The port mitmproxy will listen on. Pass 0 for automatic
selection.
options: The selenium wire options.
timeout: The num... | 9,393 |
def query_db_cluster(instanceid):
"""
Querying whether DB is Clustered or not
"""
try:
db_instance = RDS.describe_db_instances(
DBInstanceIdentifier=instanceid
)
return db_instance['DBInstances'][0]['DBClusterIdentifier']
except KeyError:
return False | 9,394 |
def is_nsfw() -> Callable[[T], T]:
"""A :func:`.check` that checks if the channel is a NSFW channel.
This check raises a special exception, :exc:`.ApplicationNSFWChannelRequired`
that is derived from :exc:`.ApplicationCheckFailure`.
.. versionchanged:: 2.0
Raise :exc:`.ApplicationNSFWChannelR... | 9,395 |
def calc_MAR(residuals, scalefactor=1.482602218):
"""Return median absolute residual (MAR) of input array. By default,
the result is scaled to the normal distribution."""
return scalefactor * np.median(np.abs(residuals)) | 9,396 |
def resourceimport_redirect():
"""
Returns a redirection action to the main resource importing view,
which is a list of files available for importing.
Returns:
The redirection action.
"""
return redirect(url_for('resourceimportfilesview.index')) | 9,397 |
def valid_attribute(node, whitelist):
"""Check the attribute access validity. Returns True if the member access is valid, False otherwise."""
# TODO: Support more than gast.Name?
if not isinstance(node.value, gast.Name):
if isinstance(node.value, gast.Attribute):
return valid_attribute(n... | 9,398 |
def gen_fov_chan_names(num_fovs, num_chans, return_imgs=False, use_delimiter=False):
"""Generate fov and channel names
Names have the format 'fov0', 'fov1', ..., 'fovN' for fovs and 'chan0', 'chan1', ...,
'chanM' for channels.
Args:
num_fovs (int):
Number of fov names to create
... | 9,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.