code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
shape = [self.batch_size, self.eq_samples, self.iw_samples, self.num_latent]
mu = tf.nn.sigmoid(self.mu)
z = tf.select(tf.random_uniform(shape) - mu > 0, tf.ones(shape), tf.zeros(shape))
return z | def compute_samples(self) | Sample from a Normal distribution with inferred mu and std | 5.044507 | 4.322701 | 1.16698 |
x_reshape = tf.reshape(x, [self.batch_size, self.eq_samples, self.iw_samples, self.num_latent])
density = tf.nn.sigmoid_cross_entropy_with_logits(self.mu, x_reshape)
# sum over all importance weights. average over all eq_samples
return tf.reduce_mean(tf.reduce_sum(-density, axis... | def neg_log_likelihood(self, x) | Calculate Log Likelihood with particular mean and std
x must be 2D. [batch_size * eqsamples* iwsamples, num_latent] | 4.745102 | 3.112257 | 1.52465 |
shape = [self.batch_size, self.eq_samples, self.iw_samples, self.num_latent]
z = tf.nn.softmax(self.pi)
return z | def compute_samples(self) | Sample from a Normal distribution with inferred mu and std | 10.518419 | 9.074791 | 1.159081 |
x_reshape = tf.reshape(x, [self.batch_size, self.eq_samples, self.iw_samples, self.num_latent])
# mean over the softmax outputs inside the log domain.
pi = tf.reduce_mean(self.pi, axis=(1, 2))
density = tf.reduce_mean(x * tf.log(pi + eps))
return tf.reduce_sum(-density... | def neg_log_likelihood(self, x, eps=1e-10) | Calculate Log Likelihood with particular mean and std
x must be 2D. [batch_size * eqsamples* iwsamples, num_latent] | 6.297547 | 4.198939 | 1.499795 |
pisdk = Dispatch('PISDK.PISDK')
my_server = pisdk.Servers(server)
# Not sure if/when the login is necessary
#con = Dispatch('PISDKDlg.Connections')
#con.Login(my_server, '', '', 1, 0)
time_start = Dispatch('PITimeServer.PITimeFormat')
time_end = Dispatch('PITimeServer.PITimeFormat')
... | def PI_read(server, tag, start=None, end=None, frequency=None) | Read function for PI server. It has to be executed by python 32 bit. | 3.543266 | 3.528137 | 1.004288 |
with open(path+fname, 'r') as fobj:
data = fobj.readlines()
header = data[9].split(",")[:-1]
unit_of_measures = data[10].split(",")[:-1]
data = pd.read_csv(path+fname,
skiprows=10,
index_col=0,
usecols=(range(0, le... | def unisim_csv_formatting(path, fname) | Remove some useless stuff from the head of a csv file generated by unisim
and returns a pandas dataframe | 3.808575 | 3.854183 | 0.988167 |
csv_fname = self.fname.split(os.sep)[-1].replace(".usc", ".csv")
scp_fname = self.fname.split(os.sep)[-1].replace(".usc", ".SCP")
case_details = {'case': self.fname.__repr__()[1:-1],
'stripchart': stripchart,
'target': self.path.__repr__()... | def extract_stripchart(self, stripchart='overall', expose_data=True) | Extract a specific stripchard and exposes the data in the namespace | 3.580435 | 3.504847 | 1.021567 |
compas_pipe = self.__profile_definition(pipeline_name)
get_variable = compas_pipe.GEtUserVariable
if os.path.isdir(self.path+'profiles') is not True:
os.mkdir(self.path + 'profiles')
target_dir = self.path + 'profiles'
if expose_data is True:
self... | def extract_profiles(self, pipeline_name, expose_data=True) | Extract all the profiles of a specific pipeline and exposes the data
in the namespace | 4.100768 | 4.054642 | 1.011376 |
pipe = self.flsh.Operations[pipeline_name]
x_st = pipe.GetUserVariable(PROFILE_LENGTH_ST).Variable()
x_non_st = pipe.GetUserVariable(PROFILE_LENGTH_NON_ST).Variable()
timesteps = pipe.GetUserVariable(PROFILE_TIME).Variable()
self.pipes[pipeline_name] = {'grid': x_st,
... | def __profile_definition(self, pipeline_name) | Prepare the profiles extraction from a specific profile | 6.04658 | 6.007064 | 1.006578 |
integrator = self.case.solver.Integrator
integrator.rununtil(endtime, timeunit)
if save is True:
self.case.save() | def run_until(self, endtime, timeunit='minutes', save=True) | Run a case untile the specifiend endtime | 6.218998 | 5.221816 | 1.190965 |
if fname is '':
self.case.save()
else:
self.case.SaveAs(self.path+os.sep+fname) | def save(self, fname='') | Save the current case | 5.616871 | 4.295428 | 1.307639 |
input_data = {'FP': 0,
'SGV': kwargs['SGV'],
'SLV': kwargs['SLV'],
'WC': kwargs['WC'],
'RO_G': kwargs['RO_G'],
'RO_O': kwargs['RO_O'],
'RO_W': kwargs['RO_W'],
... | def run(self, phase_number=3, **kwargs) | Input data description: FLOW PATTERN (FREE=0), SUPERF. GAS VELOCITY, [m/s],
SUPERF. LIQUID VEL, [m/s], WATERCUT (WC), [fraction], DENSITY GAS, [kg/m3],
DENSITY OIL, [kg/m3], DENSITY WATER, [kg/m3], VISCOSITY GAS, [Ns/m2],
VISCOSITY OIL, [Ns/m2], VISCOSITY WATER, [Ns/m2], SURFACE TENSION O/G, [N/... | 3.655946 | 2.395948 | 1.525887 |
baseclass_name = 'FieldsBase_for__{0}'.format('__'.join(fields))
if pass_kwargs:
options = dict(
header_end=', **__fields_kwargs__):\n',
super_call_end=', **__fields_kwargs__)\n',
super_call_pass_allargs=False,
)
else:
options = {}
if ini... | def class_sealer(fields, defaults,
base=__base__, make_init_func=make_init_func,
initializer=True, comparable=True, printable=True, convertible=False, pass_kwargs=False) | This sealer makes a normal container class. It's mutable and supports arguments with default values. | 1.775172 | 1.810859 | 0.980293 |
class __slots_meta__(type):
def __new__(mcs, name, bases, namespace):
if "__slots__" not in namespace:
namespace["__slots__"] = fields
return type.__new__(mcs, name, bases, namespace)
class __slots_base__(_with_metaclass(__slots_meta__, object)):
__s... | def slots_class_sealer(fields, defaults) | This sealer makes a container class that uses ``__slots__`` (it uses :func:`class_sealer` internally).
The resulting class has a metaclass that forcibly sets ``__slots__`` on subclasses. | 2.660122 | 2.608354 | 1.019847 |
baseclass_name = 'FieldsBase_for__{0}'.format('__'.join(fields))
global_namespace, local_namespace = make_init_func(
fields, defaults, baseclass_name,
header_name='__new__',
header_start='def {func_name}(cls',
header_end='):\n',
super_call_start='return tuple.__new__... | def tuple_sealer(fields, defaults) | This sealer returns an equivalent of a ``namedtuple``. | 3.563373 | 3.48086 | 1.023705 |
def filter_trends(self, pattern=''):
filtered_trends = {}
with open(self.abspath) as fobj:
for idx, line in enumerate(fobj):
variable_idx = idx-self._attributes['CATALOG']-1
if 'TIME SERIES' in line:
break
i... | Filter available trends | null | null | null | |
def extract(self, *args):
self.time = np.loadtxt(self.abspath,
skiprows=self._attributes['data_idx']+1,
unpack=True, usecols=(0,))
for variable_idx in args:
data = np.loadtxt(self.abspath,
... | Extract a specific variable | null | null | null | |
def view_trends(self, pattern=''):
d = OrderedDict()
d['Index'] = None
d['Variable'] = []
d['Position'] = []
d['Unit'] = []
d['Description'] = []
raw_d = self.filter_trends(pattern)
d['Index'] = [k for k in raw_d.keys()]
for st i... | Return a pandas df with the available trends | null | null | null | |
def to_excel(self, *args):
path = os.getcwd()
fname = self.fname.replace(".tpl", "_tpl") + ".xlsx"
idxs = self.filter_trends("")
for idx in idxs:
self.extract(idx)
data_df = pd.DataFrame(self.data)
data_df.columns = self.label.values()
... | Dump all the data to excel, fname and path can be passed as args | null | null | null | |
def _tab_type(self):
with open(self.abspath) as fobj:
contents = fobj.readlines()
for line in contents:
if 'COMPONENTS' in line:
return 'keyword'
else:
return 'fixed' | Private method to define the tab type | null | null | null | |
def _partial_extraction_fixed(self, idx, extra_idx=0):
myarray = np.array([])
with open(self.abspath) as fobj:
contents = fobj.readlines()[idx+extra_idx:]
for line in contents:
try:
vals = re.findall(r' *[\w\-\+\.]*', line)
... | Private method for a single extraction on a fixed-type tab file | null | null | null | |
def _export_all_fixed(self):
array_ts = []
array_ps = []
for array_t, array_p in it.product(self.metadata["t_array"][0],
self.metadata["p_array"][0]):
array_ts.append(array_t)
array_ps.append(array_p/1e5)
... | Exports all the properties for a fixed-type tab file | null | null | null | |
def _metadata_keyword(self):
with open(self.abspath) as fobj:
for line in fobj:
if 'PVTTABLE LABEL' in line:
label = re.findall(r"\=[\w\ \"]*\,", line)[0][1:-1]
self.metadata["fluids"].append(label)
if 'PRESSUR... | Define the most important tab parameters for a keyword-type tab file | null | null | null | |
def _export_all_keyword(self):
data = {}
for fluid_idx, fluid in enumerate(self.metadata["fluids"]):
data[fluid] = {}
with open(self.abspath) as fobj:
text = fobj.read()
try:
text = text.split("!Phase properties... | Export method for keyword tab files | null | null | null | |
def export_all(self):
if self.tab_type == 'fixed':
self._export_all_fixed()
if self.tab_type == 'keyword':
self._export_all_keyword() | It makes all the properties avaiable as data attribute | null | null | null | |
while self.running:
packet_length = self.client.recv(2)
if len(packet_length) < 2:
self.stop()
continue
packet_length = struct.unpack("<h", packet_length)[0] - 2
data = self.client.recv(packet_length)
packno = ... | def read_packets(self) | Read packets from the socket and parse them | 3.967711 | 3.90692 | 1.01556 |
while self.running:
if len(self.write_queue) > 0:
self.write_queue[0].send(self.client)
self.write_queue.pop(0) | def write_packets(self) | Write packets from the queue | 3.063354 | 2.87108 | 1.066969 |
if not self.writeThread.isAlive() and not self.readThread.isAlive():
self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.client.connect(self.ADDR)
self.running = True
self.writeThread.start()
self.readThread.start() | def start(self) | Open sockets to the server and start threads | 2.652049 | 2.343349 | 1.131735 |
a = np.zeros(order + 1)
e = np.zeros(order + 1)
# k = 1
a[0] = 1.0
a[1] = - r[1] / r[0]
e[1] = r[0] + r[1] * a[1]
lam = - r[1] / r[0]
for k in xrange(1, order):
# update lambda
lam = 0.0
for j in xrange(k + 1):
lam -= a[j] * r[k + 1 - j]
... | def levinson_durbin(r, order) | from http://aidiary.hatenablog.com/entry/20120415/1334458954 | 2.341226 | 2.337419 | 1.001629 |
r = acf(frame, unbiased=False, nlags=order)
return levinson_durbin(r, order)[0] | def lpc(frame, order) | frame: windowed signal
order: lpc order
return from 0th to `order`th linear predictive coefficients | 5.899271 | 6.986211 | 0.844416 |
c = lpc(frame, lpcorder)
coef = c[1:][::-1] * -1
residuals = []
for i in xrange(frame.size - 10):
residuals.append(frame[i + 10] - np.sum(frame[i:i + 10] * coef))
residuals = np.array(residuals)
return calc_kurtosis(residuals) | def lpr_kurtosis(frame, lpcorder=10) | frame: windowed signal
return kurtosis of linear prediction residual from input signal | 3.278562 | 3.299443 | 0.993671 |
self.params[zlib.crc32(name.encode())] = v | def set_param(self, name: str, v) -> None | Add or update an existing parameter. | 13.706963 | 8.620745 | 1.589998 |
self.objects[zlib.crc32(name.encode())] = pobj | def set_object(self, name: str, pobj: ParameterObject) -> None | Add or update an existing object. | 11.576804 | 6.45482 | 1.793513 |
self.lists[zlib.crc32(name.encode())] = plist | def set_list(self, name: str, plist) -> None | Add or update an existing list. | 11.013403 | 6.693931 | 1.645282 |
train_images = list()
train_labels = list()
test_images = list()
test_labels = list()
return train_images, train_labels, test_images, test_labels | def load_data(self, test_percent=0.15) | Load the dataset into memory. If data is not divided into train/test, use test_percent to divide the data | 2.492688 | 2.362953 | 1.054904 |
valid_images = train_images[:self.num_valid_images]
valid_labels = train_labels[:self.num_valid_images]
train_images = train_images[self.num_valid_images:]
train_labels = train_labels[self.num_valid_images:]
return train_images, train_labels, valid_images, valid_labels | def split_data(self, train_images, train_labels) | :param train_images: numpy array (image_dim, image_dim, num_images)
:param train_labels: numpy array (labels)
:return: train_images, train_labels, valid_images, valid_labels | 1.489817 | 1.477093 | 1.008614 |
start = self.index_in_train_epoch
self.index_in_train_epoch += batch_size
if self.index_in_train_epoch > self.num_train_images:
# Finished epoch
self.train_epochs_completed += 1
# Shuffle the data
perm = np.arange(self.num_train_images)
... | def next_train_batch(self, batch_size) | Return the next batch of examples from train data set
:param batch_size: int, size of image batch returned
:return train_labels: list, of labels
:return images: list, of images | 1.621732 | 1.638617 | 0.989696 |
start = self.index_in_valid_epoch
if self.index_in_valid_epoch + batch_size > self.num_valid_images:
batch_size = 1
self.index_in_valid_epoch += batch_size
end = self.index_in_valid_epoch
return self.valid_labels[start:end], self.img_norm(self.valid_images[st... | def next_valid_batch(self, batch_size) | Return the next batch of examples from validiation data set
:param batch_size: int, size of image batch returned
:return train_labels: list, of labels
:return images: list, of images | 3.11586 | 3.081376 | 1.011191 |
filename_queue = tf.train.string_input_producer([filename], shuffle=True, capacity=16)
if mode == "train":
examples_queue = tf.RandomShuffleQueue(capacity=min_examples + 3 * batch_size,
min_after_dequeue=min_examples, dtypes=[tf.str... | def queue_setup(filename, mode, batch_size, num_readers, min_examples) | Sets up the queue runners for data input | 1.574062 | 1.56794 | 1.003904 |
decoded_data = list()
for _ in range(num_threads):
decoded_data.append(read_and_decode_fn(example_serialized))
return decoded_data | def thread_setup(read_and_decode_fn, example_serialized, num_threads) | Sets up the threads within each reader | 2.363068 | 2.616643 | 0.903091 |
coord = tf.train.Coordinator()
threads = list()
for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
threads.extend(qr.create_threads(tf_session, coord=coord, daemon=True, start=True))
return threads, coord | def init_threads(tf_session) | Starts threads running | 1.928834 | 2.035604 | 0.947549 |
if config_dict is None:
print('Config File not specified. Using only input flags.')
return flags
try:
config_yaml_dict = self.cfg_from_file(flags['YAML_FILE'], config_dict)
except KeyError:
print('Yaml File not specified. Using only input ... | def load_config_yaml(self, flags, config_dict) | Load config dict and yaml dict and then override both with flags dict. | 4.38682 | 3.986875 | 1.100315 |
crucial_keys = ['MODEL_DIRECTORY', 'SAVE_DIRECTORY']
for key in crucial_keys:
if key not in config_yaml_flags_dict:
print('You must define %s. Now exiting...' % key)
exit()
optional_keys = ['RESTORE_SLIM_FILE', 'RESTORE_META', 'RESTORE_SLIM', ... | def check_dict_keys(self, config_yaml_flags_dict) | Fill in all optional keys with None. Exit in a crucial key is not defined. | 3.041331 | 2.851088 | 1.066727 |
folder = 'Model' + str(self.flags['RUN_NUM']) + '/'
folder_restore = 'Model' + str(self.flags['MODEL_RESTORE']) + '/'
self.flags['RESTORE_DIRECTORY'] = self.flags['SAVE_DIRECTORY'] + self.flags[
'MODEL_DIRECTORY'] + folder_restore
self.flags['LOGGING_DIRECTORY'] = se... | def _check_file_io(self) | Create and define logging directory | 3.260861 | 2.949238 | 1.105662 |
merged = tf.summary.merge_all()
saver = tf.train.Saver()
if type(self.flags['GPU']) is int:
os.environ["CUDA_VISIBLE_DEVICES"] = str(self.flags['GPU'])
print('Using GPU %d' % self.flags['GPU'])
gpu_options = tf.GPUOptions(allow_growth=True)
config... | def _set_tf_functions(self) | Sets up summary writer, saver, and session, with configurable gpu visibility | 2.260726 | 2.016432 | 1.121152 |
restore_meta_file = self._get_restore_meta_file()
filename = self.flags['RESTORE_DIRECTORY'] + self._get_restore_meta_file()
new_saver = tf.train.import_meta_graph(filename)
new_saver.restore(self.sess, filename[:-5])
print("Model restored from %s" % restore_meta_file) | def _restore_meta(self) | Restore from meta file. 'RESTORE_META_FILE' is expected to have .meta at the end. | 3.833058 | 3.060321 | 1.252502 |
variables_to_restore = self.get_variables_in_checkpoint_file(self.flags['RESTORE_SLIM_FILE'])
variables_to_restore = {self.name_in_checkpoint(v): v for v in variables if (self.name_in_checkpoint(v) in variables_to_restore)}
if variables_to_restore is []:
print('Check the SLI... | def _restore_slim(self, variables) | Restore from tf-slim file (usually a ImageNet pre-trained model). | 3.210137 | 2.96523 | 1.082593 |
# Initialize all variables first
self.sess.run(tf.local_variables_initializer())
self.sess.run(tf.global_variables_initializer())
if self.flags['RESTORE_META'] == 1:
print('Restoring from .meta file')
self._restore_meta()
elif self.flags['RESTORE_... | def _initialize_model(self) | Initialize the defined network and restore from files is so specified. | 4.000374 | 3.712841 | 1.077443 |
uninit_vars = self.sess.run(tf.report_uninitialized_variables())
vars_list = list()
for v in uninit_vars:
var = v.decode("utf-8")
vars_list.append(var)
uninit_vars_tf = [v for v in tf.global_variables() if v.name.split(':')[0] in vars_list]
self.s... | def _init_uninit_vars(self) | Initialize all other trainable variables, i.e. those which are uninitialized | 2.168715 | 2.102448 | 1.031519 |
checkpoint_name = self.flags['LOGGING_DIRECTORY'] + 'part_%d' % section + '.ckpt'
save_path = self.saver.save(self.sess, checkpoint_name)
print("Model saved in file: %s" % save_path) | def _save_model(self, section) | Save model in the logging directory | 4.104143 | 3.421042 | 1.199676 |
self.writer.add_summary(summary=summary, global_step=self.step)
self.step += 1 | def _record_training_step(self, summary) | Adds summary to writer and increments the step. | 2.915915 | 2.337104 | 1.247662 |
if self.flags['SEED'] is not None:
tf.set_random_seed(self.flags['SEED'])
np.random.seed(self.flags['SEED']) | def _set_seed(self) | Set random seed for numpy and tensorflow packages | 2.767539 | 2.249808 | 1.230122 |
for var in tf.trainable_variables():
tf.summary.histogram(var.name, var)
print(var.name) | def _summaries(self) | Print out summaries for every variable. Can be overriden in main function. | 3.800651 | 2.515135 | 1.511112 |
if isinstance(obj, str):
return obj
if isinstance(obj, float):
return str(int(obj))
else:
return str(obj) | def check_str(obj) | Returns a string for various input types | 2.786694 | 2.436267 | 1.143838 |
if var.op.name.startswith('model/'):
return var.op.name[len('model/'):] | def name_in_checkpoint(var) | Removes 'model' scoping if it is present in order to properly restore weights. | 3.410978 | 2.273847 | 1.500091 |
from easydict import EasyDict as edict
if type(a) is not edict:
return
for k, v in a.items():
# a must specify keys that are in b
if k not in b:
raise KeyError('{} is not a valid config key'.format(k))
# the types must ma... | def _merge_a_into_b(self, a, b) | Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a. | 1.361354 | 1.262558 | 1.07825 |
for k, v in a.items():
b[k] = v
return b | def _merge_a_into_b_simple(self, a, b) | Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a. Do not do any checking. | 3.282575 | 3.825737 | 0.858024 |
import yaml
from easydict import EasyDict as edict
with open(yaml_filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
return self._merge_a_into_b(yaml_cfg, config_dict) | def cfg_from_file(self, yaml_filename, config_dict) | Load a config file and merge it into the default options. | 2.238568 | 2.135283 | 1.048371 |
self.count['conv'] += 1
scope = 'conv_' + str(self.count['conv'])
with tf.variable_scope(scope):
# Conv function
input_channels = self.input.get_shape()[3]
if filter_size == 0: # outputs a 1x1 feature map; used for FCN
filter_size = ... | def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', bn=True, activation_fn=tf.nn.relu,
b_value=0.0, s_value=1.0, trainable=True) | 2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float | 1.972733 | 2.025142 | 0.974121 |
'''
Shortcut for creating a 2D Convolutional Neural Network in one line
Stacks multiple conv2d layers, with arguments for each layer defined in a list.
If an argument is left as None, then the conv2d defaults are kept
:param filter_sizes: int. assumes square filter
:param... | def convnet(self, filter_size, output_channels, stride=None, padding=None, activation_fn=None, b_value=None,
s_value=None, bn=None, trainable=True) | Shortcut for creating a 2D Convolutional Neural Network in one line
Stacks multiple conv2d layers, with arguments for each layer defined in a list.
If an argument is left as None, then the conv2d defaults are kept
:param filter_sizes: int. assumes square filter
:param output_channels: in... | 2.308208 | 1.518456 | 1.520102 |
self.count['deconv'] += 1
scope = 'deconv_' + str(self.count['deconv'])
with tf.variable_scope(scope):
# Calculate the dimensions for deconv function
batch_size = tf.shape(self.input)[0]
input_height = tf.shape(self.input)[1]
input_width ... | def deconv2d(self, filter_size, output_channels, stride=1, padding='SAME', activation_fn=tf.nn.relu, b_value=0.0,
s_value=1.0, bn=True, trainable=True) | 2D Deconvolutional Layer
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float | 1.79471 | 1.798128 | 0.998099 |
'''
Shortcut for creating a 2D Deconvolutional Neural Network in one line
Stacks multiple deconv2d layers, with arguments for each layer defined in a list.
If an argument is left as None, then the conv2d defaults are kept
:param filter_sizes: int. assumes square filter
:p... | def deconvnet(self, filter_sizes, output_channels, strides=None, padding=None, activation_fn=None, b_value=None,
s_value=None, bn=None, trainable=True) | Shortcut for creating a 2D Deconvolutional Neural Network in one line
Stacks multiple deconv2d layers, with arguments for each layer defined in a list.
If an argument is left as None, then the conv2d defaults are kept
:param filter_sizes: int. assumes square filter
:param output_channels... | 2.265843 | 1.506024 | 1.50452 |
self.count['flat'] += 1
scope = 'flat_' + str(self.count['flat'])
with tf.variable_scope(scope):
# Reshape function
input_nodes = tf.Dimension(
self.input.get_shape()[1] * self.input.get_shape()[2] * self.input.get_shape()[3])
output_s... | def flatten(self, keep_prob=1) | Flattens 4D Tensor (from Conv Layer) into 2D Tensor (to FC Layer)
:param keep_prob: int. set to 1 for no dropout | 2.563096 | 2.43426 | 1.052926 |
self.count['fc'] += 1
scope = 'fc_' + str(self.count['fc'])
with tf.variable_scope(scope):
# Flatten if necessary
if len(self.input.get_shape()) == 4:
input_nodes = tf.Dimension(
self.input.get_shape()[1] * self.input.get_shap... | def fc(self, output_nodes, keep_prob=1, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, bn=True,
trainable=True) | Fully Connected Layer
:param output_nodes: int
:param keep_prob: int. set to 1 for no dropout
:param activation_fn: tf.nn function
:param b_value: float or None
:param s_value: float or None
:param bn: bool | 1.803755 | 1.832888 | 0.984105 |
self.count['mp'] += 1
scope = 'maxpool_' + str(self.count['mp'])
with tf.variable_scope(scope):
if globe is True: # Global Pool Parameters
k1 = self.input.get_shape()[1]
k2 = self.input.get_shape()[2]
s1 = 1
s2... | def maxpool(self, k=2, s=None, globe=False) | Takes max value over a k x k area in each input map, or over the entire map (global = True)
:param k: int
:param globe: int, whether to pool over each feature map in its entirety | 2.174628 | 2.260946 | 0.961822 |
self.count['rn'] += 1
scope = 'resnet_' + str(self.count['rn'])
input_channels = self.input.get_shape()[3]
with tf.variable_scope(scope):
# Determine Additive Output if dimensions change
# Decrease Input dimension with 1 x 1 Conv Layer with stride > 1
... | def res_layer(self, output_channels, filter_size=3, stride=1, activation_fn=tf.nn.relu, bottle=False,
trainable=True) | Residual Layer: Input -> BN, Act_fn, Conv1, BN, Act_fn, Conv 2 -> Output. Return: Input + Output
If stride > 1 or number of filters changes, decrease dims of Input by passing through a 1 x 1 Conv Layer
The bottle option changes the Residual layer blocks to the bottleneck structure
:param output... | 1.736948 | 1.69124 | 1.027026 |
assert self.input.get_shape()[3] == num_classes # input tensor should have map depth equal to # of classes
scope = 'noisyAND'
with tf.variable_scope(scope):
a = self.const_variable(name='a', shape=[1], value=1.0, trainable=trainable)
b = self.const_variable(name... | def noisy_and(self, num_classes, trainable=True) | Multiple Instance Learning (MIL), flexible pooling function
:param num_classes: int, determine number of output maps | 2.97871 | 2.951396 | 1.009255 |
# Determine indices over which to calculate moments, based on layer type
if type == 'conv':
size = [0, 1, 2]
else: # type == 'fc'
size = [0]
# Calculate batch mean and variance
batch_mean1, batch_var1 = tf.nn.moments(x, size, keep_dims=True)
... | def batch_norm(self, x, type='conv', epsilon=1e-3) | Batch Normalization: Apply mean subtraction and variance scaling
:param x: input feature map stack
:param type: string, either 'conv' or 'fc'
:param epsilon: float
:return: output feature map stack | 3.715923 | 3.788858 | 0.98075 |
w = tf.get_variable(name=name, shape=shape, initializer=tf.contrib.layers.variance_scaling_initializer(),
trainable=trainable)
weights_norm = tf.reduce_sum(tf.nn.l2_loss(w),
name=name + '_norm') # Should user want to optimize wei... | def weight_variable(name, shape, trainable) | :param name: string
:param shape: 4D array
:return: tf variable | 3.39355 | 3.383964 | 1.002833 |
return tf.get_variable(name, shape, initializer=tf.constant_initializer(value), trainable=trainable) | def const_variable(name, shape, value, trainable) | :param name: string
:param shape: 1D array
:param value: float
:return: tf variable | 1.911044 | 2.529256 | 0.755576 |
'''XOR a given string ``s`` with the one-time-pad ``pad``'''
from itertools import cycle
s = bytearray(force_bytes(s, encoding='latin-1'))
pad = bytearray(force_bytes(pad, encoding='latin-1'))
return binary_type(bytearray(x ^ y for x, y in zip(s, cycle(pad)))) | def xor(s, pad) | XOR a given string ``s`` with the one-time-pad ``pad`` | 4.042815 | 3.214037 | 1.257862 |
compressed_content = cms.ParsableOctetString(
zlib.compress(data_to_compress))
return cms.ContentInfo({
'content_type': cms.ContentType('compressed_data'),
'content': cms.CompressedData({
'version': cms.CMSVersion('v0'),
'compression_algorithm':
... | def compress_message(data_to_compress) | Function compresses data and returns the generated ASN.1
:param data_to_compress: A byte string of the data to be compressed
:return: A CMS ASN.1 byte string of the compressed data. | 3.378625 | 3.292126 | 1.026274 |
try:
cms_content = cms.ContentInfo.load(compressed_data)
if cms_content['content_type'].native == 'compressed_data':
return cms_content['content'].decompressed
else:
raise DecompressionError('Compressed data not found in ASN.1 ')
except Exception as e:
... | def decompress_message(compressed_data) | Function parses an ASN.1 compressed message and extracts/decompresses
the original message.
:param compressed_data: A CMS ASN.1 byte string containing the compressed
data.
:return: A byte string containing the decompressed original message. | 4.671566 | 4.125429 | 1.132383 |
enc_alg_list = enc_alg.split('_')
cipher, key_length, mode = enc_alg_list[0], enc_alg_list[1], enc_alg_list[2]
enc_alg_asn1, key, encrypted_content = None, None, None
# Generate the symmetric encryption key and encrypt the message
if cipher == 'tripledes':
key = util.rand_bytes(int(ke... | def encrypt_message(data_to_encrypt, enc_alg, encryption_cert) | Function encrypts data and returns the generated ASN.1
:param data_to_encrypt: A byte string of the data to be encrypted
:param enc_alg: The algorithm to be used for encrypting the data
:param encryption_cert: The certificate to be used for encrypting the data
:return: A CMS ASN.1 byte strin... | 2.371997 | 2.330064 | 1.017996 |
cms_content = cms.ContentInfo.load(encrypted_data)
cipher, decrypted_content = None, None
if cms_content['content_type'].native == 'enveloped_data':
recipient_info = cms_content['content']['recipient_infos'][0].parse()
key_enc_alg = recipient_info[
'key_encryption_algorith... | def decrypt_message(encrypted_data, decryption_key) | Function parses an ASN.1 encrypted message and extracts/decrypts
the original message.
:param encrypted_data: A CMS ASN.1 byte string containing the encrypted
data.
:param decryption_key: The key to be used for decrypting the data.
:return: A byte string containing the decrypted origina... | 3.13063 | 3.142235 | 0.996307 |
cms_content = cms.ContentInfo.load(signature)
digest_alg = None
if cms_content['content_type'].native == 'signed_data':
for signer in cms_content['content']['signer_infos']:
signed_attributes = signer['signed_attrs'].copy()
digest_alg = signer['digest_algorithm']['alg... | def verify_message(data_to_verify, signature, verify_cert) | Function parses an ASN.1 encrypted message and extracts/decrypts
the original message.
:param data_to_verify:
A byte string of the data to be verified against the signature.
:param signature: A CMS ASN.1 byte string containing the signature.
:param verify_cert: The certificate ... | 2.645091 | 2.56221 | 1.032348 |
try:
# First try to parse as a p12 file
key, cert, _ = asymmetric.load_pkcs12(key_str, key_pass)
except ValueError as e:
# If it fails due to invalid password raise error here
if e.args[0] == 'Password provided is invalid':
raise ... | def load_key(key_str, key_pass) | Function to load password protected key file in p12 or pem format | 4.232562 | 4.009369 | 1.055668 |
if not self.payload:
return ''
if self.payload.is_multipart():
message_bytes = mime_to_bytes(
self.payload, 0).replace(b'\n', b'\r\n')
boundary = b'--' + self.payload.get_boundary().encode('utf-8')
temp = message_bytes.split(boun... | def content(self) | Function returns the body of the as2 payload as a bytes object | 3.259143 | 3.011632 | 1.082185 |
if self.payload:
message_bytes = mime_to_bytes(
self.payload, 0).replace(b'\n', b'\r\n')
boundary = b'--' + self.payload.get_boundary().encode('utf-8')
temp = message_bytes.split(boundary)
temp.pop(0)
return boundary + boundar... | def content(self) | Function returns the body of the mdn message as a byte string | 4.685311 | 3.960421 | 1.183033 |
status, detailed_status = None, None
self.payload = parse_mime(raw_content)
self.orig_message_id, orig_recipient = self.detect_mdn()
# Call the find message callback which should return a Message instance
orig_message = find_message_cb(self.orig_message_id, orig_recipi... | def parse(self, raw_content, find_message_cb) | Function parses the RAW AS2 MDN, verifies it and extracts the
processing status of the orginal AS2 message.
:param raw_content:
A byte string of the received HTTP headers followed by the body.
:param find_message_cb:
A callback the must returns the original Message Obje... | 3.86494 | 3.656762 | 1.05693 |
mdn_message = None
if self.payload.get_content_type() == 'multipart/report':
mdn_message = self.payload
elif self.payload.get_content_type() == 'multipart/signed':
for part in self.payload.walk():
if part.get_content_type() == 'multipart/report':
... | def detect_mdn(self) | Function checks if the received raw message is an AS2 MDN or not.
:raises MDNNotFound: If the received payload is not an MDN then this
exception is raised.
:return:
A two element tuple containing (message_id, message_recipient). The
message_id is the original AS2 messag... | 2.550337 | 2.124141 | 1.200644 |
config_log_level = app.config.get('FLASK_LOG_LEVEL', None)
# Set up format for default logging
hostname = platform.node().split('.')[0]
formatter = (
'[%(asctime)s] %(levelname)s %(process)d [%(name)s] '
'%(filename)s:%(lineno)d - '
'[{hostna... | def init_app(self, app) | Setup the logging handlers, level and formatters.
Level (DEBUG, INFO, CRITICAL, etc) is determined by the
app.config['FLASK_LOG_LEVEL'] setting, and defaults to
``None``/``logging.NOTSET``. | 3.161012 | 3.079745 | 1.026388 |
# Add our formatter to all the handlers
root_logger = logging.getLogger()
for handler in root_logger.handlers:
handler.setFormatter(logging.Formatter(log_formatter)) | def set_formatter(log_formatter) | Override the default log formatter with your own. | 3.439136 | 3.50715 | 0.980607 |
url = url_path_join(os.environ['JUPYTERHUB_API_URL'], path)
client = AsyncHTTPClient()
headers = {
'Authorization': 'token %s' % os.environ['JUPYTERHUB_API_TOKEN'],
}
if kwargs.get('method') == 'POST':
kwargs.setdefault('body', '')
req = HTTPRequest(url, headers=headers, **... | def api_request(path, **kwargs) | Make an API request to the Hub
to reduce boilerplate repetition. | 2.570444 | 2.577418 | 0.997294 |
app_log.info("Deleting user %s", name)
await api_request('users/{}/server'.format(name), method='DELETE')
await api_request('users/{}'.format(name), method='DELETE') | async def delete_user(name) | Stop a user's server and delete the user | 4.572686 | 3.634201 | 1.258237 |
if not os.path.exists(work_directory):
os.makedirs(work_directory)
filepath = os.path.join(work_directory, filename)
if not os.path.exists(filepath):
temp_file_name, _ = urllib.request.urlretrieve(source_url)
copyfile(temp_file_name, filepath)
... | def maybe_download(self, filename, work_directory, source_url) | Download the data from source url, unless it's already here.
Args:
filename: string, name of the file in the directory.
work_directory: string, path to working directory.
source_url: url to download from if file doesn't exist.
Returns:
Path to resulting fi... | 1.862805 | 2.021154 | 0.921654 |
print('Extracting', f.name)
with gzip.GzipFile(fileobj=f) as bytestream:
magic = self._read32(bytestream)
if magic != 2051:
raise ValueError('Invalid magic number %d in MNIST image file: %s' %
(magic, f.name))
... | def extract_images(self, f) | Extract the images into a 4D uint8 numpy array [index, y, x, depth].
Args:
f: A file object that can be passed into a gzip reader.
Returns:
data: A 4D unit8 numpy array [index, y, x, depth].
Raises:
ValueError: If the bytestream does not start with 2051. | 1.5122 | 1.355211 | 1.115842 |
print('Extracting', f.name)
with gzip.GzipFile(fileobj=f) as bytestream:
magic = self._read32(bytestream)
if magic != 2049:
raise ValueError('Invalid magic number %d in MNIST label file: %s' %
(magic, f.name))
... | def extract_labels(self, f, one_hot=False, num_classes=10) | Extract the labels into a 1D uint8 numpy array [index].
Args:
f: A file object that can be passed into a gzip reader.
one_hot: Does one hot encoding for the result.
num_classes: Number of classes for the one hot encoding.
Returns:
labels: a 1D unit8 numpy array.
... | 1.588701 | 1.503099 | 1.05695 |
num_labels = labels_dense.shape[0]
index_offset = np.arange(num_labels) * num_classes
labels_one_hot = np.zeros((num_labels, num_classes))
labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
return labels_one_hot | def dense_to_one_hot(labels_dense, num_classes) | Convert class labels from scalars to one-hot vectors. | 1.338537 | 1.289294 | 1.038194 |
if lens_data is None:
lens_data = apply_lens(df, lens=lens)
patch_clusterings = {}
counter = 0
patches = covering_patches(lens_data, resolution=resolution, gain=gain, equalize=equalize)
for key, patch in patches.items():
if len(patch) > 0:
patch_clusterings[key] = o... | def mapper_graph(df, lens_data=None, lens='pca', resolution=10, gain=0.5, equalize=True, clust='kmeans', stat='db',
max_K=5) | input: N x n_dim image of of raw data under lens function, as a dataframe
output: (undirected graph, list of node contents, dictionary of patches) | 2.555871 | 2.508124 | 1.019037 |
self.count['conv'] += 1
scope = 'conv_' + str(self.count['conv'])
with tf.variable_scope(scope):
# Conv function
input_channels = self.input.get_shape()[3]
if filter_size == 0: # outputs a 1x1 feature map; used for FCN
filter_size = ... | def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', stoch=None, bn=True, test=False, activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0) | 2D Convolutional Layer.
:param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float | 2.029554 | 2.052288 | 0.988923 |
self.count['conv'] += 1
self._layer_count += 1
scope = 'conv_' + str(self.count['conv'])
if stoch is True:
clean = False
else:
clean = True
with tf.variable_scope(scope):
input_channels = self.input.get_shape()[3]
o... | def conv2d(self, filter_size, output_channels, stride=1, padding='SAME', activation_fn=tf.nn.relu, b_value=0.0, s_value=1.0, bn=True, stoch=False) | :param filter_size: int. assumes square filter
:param output_channels: int
:param stride: int
:param padding: 'VALID' or 'SAME'
:param activation_fn: tf.nn function
:param b_value: float
:param s_value: float | 2.052692 | 2.066587 | 0.993277 |
if n_dim != 2:
raise 'error: image of data set must be two-dimensional'
if dist not in ['euclidean', 'correlation']:
raise 'error: only euclidean and correlation distance metrics are supported'
if lens == 'pca' and dist != 'euclidean':
raise 'error: PCA requires the use of eucli... | def apply_lens(df, lens='pca', dist='euclidean', n_dim=2, **kwargs) | input: N x F dataframe of observations
output: N x n_dim image of input data under lens function | 2.313659 | 2.269632 | 1.019398 |
if hasattr(element, 'render'):
return element.render(level)
elif isinstance(element, basestring):
return _render_string(element, level)
elif hasattr(element, '__iter__'):
return _render_iteratable(element, level)
elif element is None:
return ''
raise TypeError(... | def render(element, level=0) | Renders the HTML builder `element` and it's children to a string.
Example::
>>> print(
... render(
... html.form(action='/search', name='f')(
... html.input(name='q'),
... html.input(name='search_button', type='submit')
... ... | 2.500709 | 3.094802 | 0.808035 |
if isinstance(iteratable, basestring):
return unicode(iteratable)
return ''.join([render(element, level) for element in iteratable]) | def _render_iteratable(iteratable, level) | Renders iteratable sequence of HTML elements. | 3.913894 | 3.503602 | 1.117106 |
result = ''
for name, value in attributes.items():
if not value:
continue
result += ' ' + _unmangle_attribute_name(name)
result += '="' + escape(value, True) + '"'
return result | def _serialize_attributes(attributes) | Serializes HTML element attributes in a name="value" pair form. | 3.438697 | 3.180011 | 1.081348 |
# Python keywords cannot be used as variable names, an underscore should
# be appended at the end of each of them when defining attribute names.
name = _PYTHON_KEYWORD_MAP.get(name, name)
# Attribute names are mangled with double underscore, as colon cannot
# be used as a variable character s... | def _unmangle_attribute_name(name) | Unmangles attribute names so that correct Python variable names are
used for mapping attribute names. | 9.478939 | 8.380119 | 1.131122 |
if string is None:
return ''
elif hasattr(string, '__html__'):
return unicode(string)
string = string.replace('&', '&').replace('<', '<').replace('>', '>')
if quote:
string = string.replace('"', """)
return string | def escape(string, quote=False) | Standard HTML text escaping, but protecting against the agressive
behavior of Jinja 2 `Markup` and the like. | 2.167258 | 2.146256 | 1.009785 |
def decorator(block_func):
block = RootBlock(block_func, template_name)
return block_func
return decorator | def root_block(template_name=DEFAULT_TEMPLATE_NAME) | A decorator that is used to define that the decorated block function
will be at the root of the block template hierarchy. In the usual case
this will be the HTML skeleton of the document, unless the template is used
to serve partial HTML rendering for Ajax.
The :func:`root_block` decorator accepts the... | 4.234463 | 6.528988 | 0.648563 |
def decorator(block_func):
block = Block(block_func, view_func)
parent_block = Block.block_mapping[parent_block_func]
parent_block.append_context_block(context_name, block)
return block_func
return decorator | def block(context_name, parent_block_func, view_func=None) | A decorator that is used for inserting the decorated block function in
the block template hierarchy.
The :func:`block` decorator accepts the following arguments:
:param context_name: key in the `g.blocks` dictionary in which the result
of the decorated block function will be store... | 3.230328 | 4.545883 | 0.710605 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.