hexsha
stringlengths
40
40
repo
stringlengths
7
114
path
stringlengths
4
124
license
listlengths
1
9
language
stringclasses
1 value
identifier
stringlengths
1
71
return_type
stringlengths
1
749
original_string
stringlengths
76
22.7k
original_docstring
stringlengths
16
7.61k
docstring
stringlengths
16
2.47k
docstring_tokens
listlengths
6
477
code
stringlengths
14
10.2k
code_tokens
listlengths
6
996
short_docstring
stringlengths
2
644
short_docstring_tokens
listlengths
1
116
comment
listlengths
1
89
parameters
listlengths
0
64
docstring_params
dict
a5924b0c36b5ba633e7767ea924c60f86d736aeb
gavinbarrett/SL_Engine
src/parser.py
[ "MIT" ]
Python
in_order
<not_specific>
def in_order(self, root, table): ''' Traverse the AST in in-order fashion ''' # base case for recursion if root is None: return # traverse down the left branch self.in_order(root.left, table) # add the stack value to the table value = root.eval_stack....
Traverse the AST in in-order fashion
Traverse the AST in in-order fashion
[ "Traverse", "the", "AST", "in", "in", "-", "order", "fashion" ]
def in_order(self, root, table): if root is None: return self.in_order(root.left, table) value = root.eval_stack.pop(0) table.append(value) self.in_order(root.right, table)
[ "def", "in_order", "(", "self", ",", "root", ",", "table", ")", ":", "if", "root", "is", "None", ":", "return", "self", ".", "in_order", "(", "root", ".", "left", ",", "table", ")", "value", "=", "root", ".", "eval_stack", ".", "pop", "(", "0", "...
Traverse the AST in in-order fashion
[ "Traverse", "the", "AST", "in", "in", "-", "order", "fashion" ]
[ "''' Traverse the AST in in-order fashion '''", "# base case for recursion", "# traverse down the left branch", "# add the stack value to the table ", "# traverse down the right branch" ]
[ { "param": "self", "type": null }, { "param": "root", "type": null }, { "param": "table", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "root", "type": null, "docstring": null, "docstring_tokens": [...
a5924b0c36b5ba633e7767ea924c60f86d736aeb
gavinbarrett/SL_Engine
src/parser.py
[ "MIT" ]
Python
check_if_valid
<not_specific>
def check_if_valid(self, vTable): ''' return false if truth matrix contains an instance of all true premises and a false conclusion ''' #FIXME: make sure that we check correct values if we are checking negated terms! for vT in vTable: for idx, v in enumerate(vT): # wh...
return false if truth matrix contains an instance of all true premises and a false conclusion
return false if truth matrix contains an instance of all true premises and a false conclusion
[ "return", "false", "if", "truth", "matrix", "contains", "an", "instance", "of", "all", "true", "premises", "and", "a", "false", "conclusion" ]
def check_if_valid(self, vTable): for vT in vTable: for idx, v in enumerate(vT): if v == '1': continue elif v == '0' and idx == (len(vT)-1): return False else: break return True
[ "def", "check_if_valid", "(", "self", ",", "vTable", ")", ":", "for", "vT", "in", "vTable", ":", "for", "idx", ",", "v", "in", "enumerate", "(", "vT", ")", ":", "if", "v", "==", "'1'", ":", "continue", "elif", "v", "==", "'0'", "and", "idx", "=="...
return false if truth matrix contains an instance of all true premises and a false conclusion
[ "return", "false", "if", "truth", "matrix", "contains", "an", "instance", "of", "all", "true", "premises", "and", "a", "false", "conclusion" ]
[ "''' return false if truth matrix contains an instance of all true premises and a false conclusion '''", "#FIXME: make sure that we check correct values if we are checking negated terms!", "# while the value is true, continue to read", "# if the last truth value is false, the argument is invalid", "# argume...
[ { "param": "self", "type": null }, { "param": "vTable", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "vTable", "type": null, "docstring": null, "docstring_tokens":...
a5924b0c36b5ba633e7767ea924c60f86d736aeb
gavinbarrett/SL_Engine
src/parser.py
[ "MIT" ]
Python
print_tt
<not_specific>
def print_tt(self, root): ''' Loop through the AST and evaluate, returning the set of tables ''' if root is None: return self.handle_root(root.left) self.handle_root(root.right) # evaluate the root node self.evaluate(root)
Loop through the AST and evaluate, returning the set of tables
Loop through the AST and evaluate, returning the set of tables
[ "Loop", "through", "the", "AST", "and", "evaluate", "returning", "the", "set", "of", "tables" ]
def print_tt(self, root): if root is None: return self.handle_root(root.left) self.handle_root(root.right) self.evaluate(root)
[ "def", "print_tt", "(", "self", ",", "root", ")", ":", "if", "root", "is", "None", ":", "return", "self", ".", "handle_root", "(", "root", ".", "left", ")", "self", ".", "handle_root", "(", "root", ".", "right", ")", "self", ".", "evaluate", "(", "...
Loop through the AST and evaluate, returning the set of tables
[ "Loop", "through", "the", "AST", "and", "evaluate", "returning", "the", "set", "of", "tables" ]
[ "''' Loop through the AST and evaluate, returning the set of tables '''", "# evaluate the root node" ]
[ { "param": "self", "type": null }, { "param": "root", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "root", "type": null, "docstring": null, "docstring_tokens": [...
a5924b0c36b5ba633e7767ea924c60f86d736aeb
gavinbarrett/SL_Engine
src/parser.py
[ "MIT" ]
Python
insert_op
null
def insert_op(self, op): ''' Pop stack and make new operator ast ''' #TODO: designate t as the root of the tree; # overwrite child nodes if they are specified as the root t = ast.AST(op) if op == '~': if self.tree_stack: # if it is a negation, put as r...
Pop stack and make new operator ast
Pop stack and make new operator ast
[ "Pop", "stack", "and", "make", "new", "operator", "ast" ]
def insert_op(self, op): t = ast.AST(op) if op == '~': if self.tree_stack: tree = self.tree_stack.pop() tree.root = False t.right = tree self.tree_stack.append(t) else: self.tree_stack.append(op) ...
[ "def", "insert_op", "(", "self", ",", "op", ")", ":", "t", "=", "ast", ".", "AST", "(", "op", ")", "if", "op", "==", "'~'", ":", "if", "self", ".", "tree_stack", ":", "tree", "=", "self", ".", "tree_stack", ".", "pop", "(", ")", "tree", ".", ...
Pop stack and make new operator ast
[ "Pop", "stack", "and", "make", "new", "operator", "ast" ]
[ "''' Pop stack and make new operator ast '''", "#TODO: designate t as the root of the tree;", "# overwrite child nodes if they are specified as the root", "# if it is a negation, put as right child" ]
[ { "param": "self", "type": null }, { "param": "op", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "op", "type": null, "docstring": null, "docstring_tokens": [],...
a5924b0c36b5ba633e7767ea924c60f86d736aeb
gavinbarrett/SL_Engine
src/parser.py
[ "MIT" ]
Python
insert_term
null
def insert_term(self, term): ''' Create new ast with term as root ''' if term not in self.seen: self.seen += term # create a tree with the term as a root tree = ast.AST(term) self.tree_stack.append(tree)
Create new ast with term as root
Create new ast with term as root
[ "Create", "new", "ast", "with", "term", "as", "root" ]
def insert_term(self, term): if term not in self.seen: self.seen += term tree = ast.AST(term) self.tree_stack.append(tree)
[ "def", "insert_term", "(", "self", ",", "term", ")", ":", "if", "term", "not", "in", "self", ".", "seen", ":", "self", ".", "seen", "+=", "term", "tree", "=", "ast", ".", "AST", "(", "term", ")", "self", ".", "tree_stack", ".", "append", "(", "tr...
Create new ast with term as root
[ "Create", "new", "ast", "with", "term", "as", "root" ]
[ "''' Create new ast with term as root '''", "# create a tree with the term as a root" ]
[ { "param": "self", "type": null }, { "param": "term", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "term", "type": null, "docstring": null, "docstring_tokens": [...
a5924b0c36b5ba633e7767ea924c60f86d736aeb
gavinbarrett/SL_Engine
src/parser.py
[ "MIT" ]
Python
normalize
<not_specific>
def normalize(self, fs): ''' split expression string by newline into expressions ''' formulas = fs.split('\n') # return list of expressions after filtering out empty strings (i.e. '') return list(filter(lambda x: False if str(x) == '' else True, formulas))
split expression string by newline into expressions
split expression string by newline into expressions
[ "split", "expression", "string", "by", "newline", "into", "expressions" ]
def normalize(self, fs): formulas = fs.split('\n') return list(filter(lambda x: False if str(x) == '' else True, formulas))
[ "def", "normalize", "(", "self", ",", "fs", ")", ":", "formulas", "=", "fs", ".", "split", "(", "'\\n'", ")", "return", "list", "(", "filter", "(", "lambda", "x", ":", "False", "if", "str", "(", "x", ")", "==", "''", "else", "True", ",", "formula...
split expression string by newline into expressions
[ "split", "expression", "string", "by", "newline", "into", "expressions" ]
[ "''' split expression string by newline into expressions '''", "# return list of expressions after filtering out empty strings (i.e. '')" ]
[ { "param": "self", "type": null }, { "param": "fs", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "fs", "type": null, "docstring": null, "docstring_tokens": [],...
1171395c99a5240017b44b884addbad62b60f789
nourhamdan/sqlalchemy-challenge
app.py
[ "ADSL" ]
Python
station
<not_specific>
def station(): # Create our session (link) from Python to the DB session = Session(engine) """Return a list of all stations""" # Query all stations results = session.query(base.stations).all() session.close() return jsonify(results)
Return a list of all stations
Return a list of all stations
[ "Return", "a", "list", "of", "all", "stations" ]
def station(): session = Session(engine) results = session.query(base.stations).all() session.close() return jsonify(results)
[ "def", "station", "(", ")", ":", "session", "=", "Session", "(", "engine", ")", "results", "=", "session", ".", "query", "(", "base", ".", "stations", ")", ".", "all", "(", ")", "session", ".", "close", "(", ")", "return", "jsonify", "(", "results", ...
Return a list of all stations
[ "Return", "a", "list", "of", "all", "stations" ]
[ "# Create our session (link) from Python to the DB", "\"\"\"Return a list of all stations\"\"\"", "# Query all stations" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
7aa70ed426823629fc3b9d375fafc5ce52a6e7e9
alexkost819/thesis
data_processor.py
[ "Apache-2.0" ]
Python
preprocess_all_data
null
def preprocess_all_data(self): """Shuffle all data and then preprocess the files.""" all_files = self._create_filename_list(SIM_DATA_PATH) np.random.shuffle(all_files) train_val_test_files = self._split_datafiles(all_files) # train_set, val_set, test_set self.train_files = tr...
Shuffle all data and then preprocess the files.
Shuffle all data and then preprocess the files.
[ "Shuffle", "all", "data", "and", "then", "preprocess", "the", "files", "." ]
def preprocess_all_data(self): all_files = self._create_filename_list(SIM_DATA_PATH) np.random.shuffle(all_files) train_val_test_files = self._split_datafiles(all_files) self.train_files = train_val_test_files[0] self.val_files = train_val_test_files[1] self.test_file...
[ "def", "preprocess_all_data", "(", "self", ")", ":", "all_files", "=", "self", ".", "_create_filename_list", "(", "SIM_DATA_PATH", ")", "np", ".", "random", ".", "shuffle", "(", "all_files", ")", "train_val_test_files", "=", "self", ".", "_split_datafiles", "(",...
Shuffle all data and then preprocess the files.
[ "Shuffle", "all", "data", "and", "then", "preprocess", "the", "files", "." ]
[ "\"\"\"Shuffle all data and then preprocess the files.\"\"\"", "# train_set, val_set, test_set", "# Report sizes and load all datasets" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7aa70ed426823629fc3b9d375fafc5ce52a6e7e9
alexkost819/thesis
data_processor.py
[ "Apache-2.0" ]
Python
preprocess_data_by_label
null
def preprocess_data_by_label(self): """Simulation data is organized by label. This method mixes and splits up the data.""" for i in range(self.n_classes): modified_data_path = os.path.join(SIM_DATA_PATH, str(i)) class_files = self._create_filename_list(modified_data_path) ...
Simulation data is organized by label. This method mixes and splits up the data.
Simulation data is organized by label. This method mixes and splits up the data.
[ "Simulation", "data", "is", "organized", "by", "label", ".", "This", "method", "mixes", "and", "splits", "up", "the", "data", "." ]
def preprocess_data_by_label(self): for i in range(self.n_classes): modified_data_path = os.path.join(SIM_DATA_PATH, str(i)) class_files = self._create_filename_list(modified_data_path) result = self._split_datafiles(class_files) self.train_files.extend(result...
[ "def", "preprocess_data_by_label", "(", "self", ")", ":", "for", "i", "in", "range", "(", "self", ".", "n_classes", ")", ":", "modified_data_path", "=", "os", ".", "path", ".", "join", "(", "SIM_DATA_PATH", ",", "str", "(", "i", ")", ")", "class_files", ...
Simulation data is organized by label.
[ "Simulation", "data", "is", "organized", "by", "label", "." ]
[ "\"\"\"Simulation data is organized by label. This method mixes and splits up the data.\"\"\"", "# get files for each thing", "# train_set, val_set, test_set", "# Shuffle data", "# Report sizes and load all datasets" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
7aa70ed426823629fc3b9d375fafc5ce52a6e7e9
alexkost819/thesis
data_processor.py
[ "Apache-2.0" ]
Python
_create_filename_list
<not_specific>
def _create_filename_list(data_dir): """Identify the list of CSV files based on a given data_dir. Args: data_dir (string): local path to where the data is saved. Returns: filenames (list of strings): a list of CSV files found in the data directory """ fi...
Identify the list of CSV files based on a given data_dir. Args: data_dir (string): local path to where the data is saved. Returns: filenames (list of strings): a list of CSV files found in the data directory
Identify the list of CSV files based on a given data_dir.
[ "Identify", "the", "list", "of", "CSV", "files", "based", "on", "a", "given", "data_dir", "." ]
def _create_filename_list(data_dir): filenames = [] for root, _, files in os.walk(data_dir): for filename in files: if filename.endswith(".csv"): rel_filepath = os.path.join(root, filename) abs_filepath = os.path.abspath(rel_filepath) ...
[ "def", "_create_filename_list", "(", "data_dir", ")", ":", "filenames", "=", "[", "]", "for", "root", ",", "_", ",", "files", "in", "os", ".", "walk", "(", "data_dir", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "endswith", ...
Identify the list of CSV files based on a given data_dir.
[ "Identify", "the", "list", "of", "CSV", "files", "based", "on", "a", "given", "data_dir", "." ]
[ "\"\"\"Identify the list of CSV files based on a given data_dir.\n\n Args:\n data_dir (string): local path to where the data is saved.\n\n Returns:\n filenames (list of strings): a list of CSV files found in the data directory\n \"\"\"" ]
[ { "param": "data_dir", "type": null } ]
{ "returns": [ { "docstring": "filenames (list of strings): a list of CSV files found in the data directory", "docstring_tokens": [ "filenames", "(", "list", "of", "strings", ")", ":", "a", "list", "of", "CSV", ...
7aa70ed426823629fc3b9d375fafc5ce52a6e7e9
alexkost819/thesis
data_processor.py
[ "Apache-2.0" ]
Python
_split_datafiles
<not_specific>
def _split_datafiles(data, val_size=0.2, test_size=0.2): """Spit all the data we have into training, validating, and test sets. By default, 60/20/20 split Credit: https://www.slideshare.net/TaegyunJeon1/electricity-price-forecasting-with-recurrent-neural-networks Args: data...
Spit all the data we have into training, validating, and test sets. By default, 60/20/20 split Credit: https://www.slideshare.net/TaegyunJeon1/electricity-price-forecasting-with-recurrent-neural-networks Args: data (list): list of filenames val_size (float, optional): P...
Spit all the data we have into training, validating, and test sets.
[ "Spit", "all", "the", "data", "we", "have", "into", "training", "validating", "and", "test", "sets", "." ]
def _split_datafiles(data, val_size=0.2, test_size=0.2): val_length = int(len(data) * val_size) test_length = int(len(data) * test_size) val_set = data[:val_length] test_set = data[val_length:val_length + test_length] train_set = data[val_length + test_length:] return tra...
[ "def", "_split_datafiles", "(", "data", ",", "val_size", "=", "0.2", ",", "test_size", "=", "0.2", ")", ":", "val_length", "=", "int", "(", "len", "(", "data", ")", "*", "val_size", ")", "test_length", "=", "int", "(", "len", "(", "data", ")", "*", ...
Spit all the data we have into training, validating, and test sets.
[ "Spit", "all", "the", "data", "we", "have", "into", "training", "validating", "and", "test", "sets", "." ]
[ "\"\"\"Spit all the data we have into training, validating, and test sets.\n\n By default, 60/20/20 split\n Credit: https://www.slideshare.net/TaegyunJeon1/electricity-price-forecasting-with-recurrent-neural-networks\n\n Args:\n data (list): list of filenames\n val_size (f...
[ { "param": "data", "type": null }, { "param": "val_size", "type": null }, { "param": "test_size", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": null } ], "raises": [], "params": [ { "identifier": "data", "type": null, "docstring": "list of filenames", "docstring_tokens": [ "list", "of", ...
52dd74ea22c911b8fe934557a92ff00cfc902380
alexkost819/thesis
train.py
[ "Apache-2.0" ]
Python
calculate_helpers
null
def calculate_helpers(self): """Calculate helper variables for training length.""" self._ex_per_epoch = len(self.train_files) self._steps_per_epoch = int(ceil(self._ex_per_epoch / float(self.batch_size))) self._train_length_ex = self._ex_per_epoch * self.n_epochs self._train_leng...
Calculate helper variables for training length.
Calculate helper variables for training length.
[ "Calculate", "helper", "variables", "for", "training", "length", "." ]
def calculate_helpers(self): self._ex_per_epoch = len(self.train_files) self._steps_per_epoch = int(ceil(self._ex_per_epoch / float(self.batch_size))) self._train_length_ex = self._ex_per_epoch * self.n_epochs self._train_length_steps = self._steps_per_epoch * self.n_epochs self....
[ "def", "calculate_helpers", "(", "self", ")", ":", "self", ".", "_ex_per_epoch", "=", "len", "(", "self", ".", "train_files", ")", "self", ".", "_steps_per_epoch", "=", "int", "(", "ceil", "(", "self", ".", "_ex_per_epoch", "/", "float", "(", "self", "."...
Calculate helper variables for training length.
[ "Calculate", "helper", "variables", "for", "training", "length", "." ]
[ "\"\"\"Calculate helper variables for training length.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
52dd74ea22c911b8fe934557a92ff00cfc902380
alexkost819/thesis
train.py
[ "Apache-2.0" ]
Python
evaluate_model_on_data
<not_specific>
def evaluate_model_on_data(self, sess, dataset_label): """Evaluate the model on the entire training data. Args: sess (tf.Session object): active session object dataset_label (string): dataset label Returns: float, float: the cost and accuracy of the model ba...
Evaluate the model on the entire training data. Args: sess (tf.Session object): active session object dataset_label (string): dataset label Returns: float, float: the cost and accuracy of the model based on the dataset.
Evaluate the model on the entire training data.
[ "Evaluate", "the", "model", "on", "the", "entire", "training", "data", "." ]
def evaluate_model_on_data(self, sess, dataset_label): try: dataset_dict = {'test': self.test_data, 'train': self.test_data, 'val': self.val_data} dataset = dataset_dict[dataset_label] except KeyError: raise '"da...
[ "def", "evaluate_model_on_data", "(", "self", ",", "sess", ",", "dataset_label", ")", ":", "try", ":", "dataset_dict", "=", "{", "'test'", ":", "self", ".", "test_data", ",", "'train'", ":", "self", ".", "test_data", ",", "'val'", ":", "self", ".", "val_...
Evaluate the model on the entire training data.
[ "Evaluate", "the", "model", "on", "the", "entire", "training", "data", "." ]
[ "\"\"\"Evaluate the model on the entire training data.\n\n Args:\n sess (tf.Session object): active session object\n dataset_label (string): dataset label\n\n Returns:\n float, float: the cost and accuracy of the model based on the dataset.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "sess", "type": null }, { "param": "dataset_label", "type": null } ]
{ "returns": [ { "docstring": "float, float: the cost and accuracy of the model based on the dataset.", "docstring_tokens": [ "float", "float", ":", "the", "cost", "and", "accuracy", "of", "the", "model", "based", ...
52dd74ea22c911b8fe934557a92ff00cfc902380
alexkost819/thesis
train.py
[ "Apache-2.0" ]
Python
_generate_batch
<not_specific>
def _generate_batch(self, batch_idx): """Generate a batch and increment the sliding batch window within the data.""" features = self.train_data[0] labels = self.train_data[1] start_idx = batch_idx * self.batch_size end_idx = start_idx + self.batch_size - 1 # Error handl...
Generate a batch and increment the sliding batch window within the data.
Generate a batch and increment the sliding batch window within the data.
[ "Generate", "a", "batch", "and", "increment", "the", "sliding", "batch", "window", "within", "the", "data", "." ]
def _generate_batch(self, batch_idx): features = self.train_data[0] labels = self.train_data[1] start_idx = batch_idx * self.batch_size end_idx = start_idx + self.batch_size - 1 if end_idx > self._ex_per_epoch: end_idx = self._ex_per_epoch if self.n_features >...
[ "def", "_generate_batch", "(", "self", ",", "batch_idx", ")", ":", "features", "=", "self", ".", "train_data", "[", "0", "]", "labels", "=", "self", ".", "train_data", "[", "1", "]", "start_idx", "=", "batch_idx", "*", "self", ".", "batch_size", "end_idx...
Generate a batch and increment the sliding batch window within the data.
[ "Generate", "a", "batch", "and", "increment", "the", "sliding", "batch", "window", "within", "the", "data", "." ]
[ "\"\"\"Generate a batch and increment the sliding batch window within the data.\"\"\"", "# Error handling for if sliding window goes beyond data list length" ]
[ { "param": "self", "type": null }, { "param": "batch_idx", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "batch_idx", "type": null, "docstring": null, "docstring_token...
2d6fcc24c023b59f0131bd400fa3ac4c75ae520a
alexkost819/thesis
tune.py
[ "Apache-2.0" ]
Python
create_cnn_experiment
null
def create_cnn_experiment(self): """Create experiment. Modify as needed.""" self.experiment = self.conn.experiments().create( name="CNNModel Accuracy v3", parameters=[dict(name="learning_rate", bounds=dict(min=0.00001, max=0.1), ...
Create experiment. Modify as needed.
Create experiment. Modify as needed.
[ "Create", "experiment", ".", "Modify", "as", "needed", "." ]
def create_cnn_experiment(self): self.experiment = self.conn.experiments().create( name="CNNModel Accuracy v3", parameters=[dict(name="learning_rate", bounds=dict(min=0.00001, max=0.1), type="double"), dict...
[ "def", "create_cnn_experiment", "(", "self", ")", ":", "self", ".", "experiment", "=", "self", ".", "conn", ".", "experiments", "(", ")", ".", "create", "(", "name", "=", "\"CNNModel Accuracy v3\"", ",", "parameters", "=", "[", "dict", "(", "name", "=", ...
Create experiment.
[ "Create", "experiment", "." ]
[ "\"\"\"Create experiment. Modify as needed.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2d6fcc24c023b59f0131bd400fa3ac4c75ae520a
alexkost819/thesis
tune.py
[ "Apache-2.0" ]
Python
create_rnn_experiment
null
def create_rnn_experiment(self): """Create experiment. Modify as needed.""" self.experiment = self.conn.experiments().create( name="RNNModel Accuracy v1", parameters=[dict(name="learning_rate", bounds=dict(min=0.00001, max=0.1), ...
Create experiment. Modify as needed.
Create experiment. Modify as needed.
[ "Create", "experiment", ".", "Modify", "as", "needed", "." ]
def create_rnn_experiment(self): self.experiment = self.conn.experiments().create( name="RNNModel Accuracy v1", parameters=[dict(name="learning_rate", bounds=dict(min=0.00001, max=0.1), type="double"), dict...
[ "def", "create_rnn_experiment", "(", "self", ")", ":", "self", ".", "experiment", "=", "self", ".", "conn", ".", "experiments", "(", ")", ".", "create", "(", "name", "=", "\"RNNModel Accuracy v1\"", ",", "parameters", "=", "[", "dict", "(", "name", "=", ...
Create experiment.
[ "Create", "experiment", "." ]
[ "\"\"\"Create experiment. Modify as needed.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2d6fcc24c023b59f0131bd400fa3ac4c75ae520a
alexkost819/thesis
tune.py
[ "Apache-2.0" ]
Python
update_parameters
null
def update_parameters(self): """Update model parameters with suggestions.""" #model_type = self.model.__class__.__name__.replace('Model', '') params = self.suggestion.assignments # if model_type == 'CNN': # self.model.num_filt_1 = int(params['num_filt_1']) # self...
Update model parameters with suggestions.
Update model parameters with suggestions.
[ "Update", "model", "parameters", "with", "suggestions", "." ]
def update_parameters(self): params = self.suggestion.assignments self.model.learning_rate = params['learning_rate'] self.model.beta1 = params['beta1'] self.model.beta2 = params['beta2'] self.model.epsilon = params['epsilon']
[ "def", "update_parameters", "(", "self", ")", ":", "params", "=", "self", ".", "suggestion", ".", "assignments", "self", ".", "model", ".", "learning_rate", "=", "params", "[", "'learning_rate'", "]", "self", ".", "model", ".", "beta1", "=", "params", "[",...
Update model parameters with suggestions.
[ "Update", "model", "parameters", "with", "suggestions", "." ]
[ "\"\"\"Update model parameters with suggestions.\"\"\"", "#model_type = self.model.__class__.__name__.replace('Model', '')", "# if model_type == 'CNN':", "# self.model.num_filt_1 = int(params['num_filt_1'])", "# self.model.kernel_size = int(params['kernel_size'])", "# self.model.num_fc_1 = int...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2d6fcc24c023b59f0131bd400fa3ac4c75ae520a
alexkost819/thesis
tune.py
[ "Apache-2.0" ]
Python
optimization_loop
null
def optimization_loop(self, model): """Optimize the parameters based on suggestions.""" for i in range(100): self.logger.info('Optimization Loop Count: %d', i) # assign suggestions to parameters and hyperparameters self.get_suggestions() # update model c...
Optimize the parameters based on suggestions.
Optimize the parameters based on suggestions.
[ "Optimize", "the", "parameters", "based", "on", "suggestions", "." ]
def optimization_loop(self, model): for i in range(100): self.logger.info('Optimization Loop Count: %d', i) self.get_suggestions() self.model = model() self.update_parameters() self.model.build_model() train = TrainModel(self.model, n_epoch...
[ "def", "optimization_loop", "(", "self", ",", "model", ")", ":", "for", "i", "in", "range", "(", "100", ")", ":", "self", ".", "logger", ".", "info", "(", "'Optimization Loop Count: %d'", ",", "i", ")", "self", ".", "get_suggestions", "(", ")", "self", ...
Optimize the parameters based on suggestions.
[ "Optimize", "the", "parameters", "based", "on", "suggestions", "." ]
[ "\"\"\"Optimize the parameters based on suggestions.\"\"\"", "# assign suggestions to parameters and hyperparameters", "# update model class", "# update training class", "# run the training stuff", "# report to SigOpt" ]
[ { "param": "self", "type": null }, { "param": "model", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model", "type": null, "docstring": null, "docstring_tokens": ...
2d6fcc24c023b59f0131bd400fa3ac4c75ae520a
alexkost819/thesis
tune.py
[ "Apache-2.0" ]
Python
tune_cnn_with_gridsearch
null
def tune_cnn_with_gridsearch(): """Grid search to identify best hyperparameters for CNN model.""" cnn_model_values = [] n_epoch_list = [100, 200, 300, 400, 500] # 5 batch_size_list = [16, 32, 64, 128, 256] # 5 learning...
Grid search to identify best hyperparameters for CNN model.
Grid search to identify best hyperparameters for CNN model.
[ "Grid", "search", "to", "identify", "best", "hyperparameters", "for", "CNN", "model", "." ]
def tune_cnn_with_gridsearch(): cnn_model_values = [] n_epoch_list = [100, 200, 300, 400, 500] batch_size_list = [16, 32, 64, 128, 256] learning_rate_list = [.0001, .0005, .00001, .00005] dropout...
[ "def", "tune_cnn_with_gridsearch", "(", ")", ":", "cnn_model_values", "=", "[", "]", "n_epoch_list", "=", "[", "100", ",", "200", ",", "300", ",", "400", ",", "500", "]", "batch_size_list", "=", "[", "16", ",", "32", ",", "64", ",", "128", ",", "256"...
Grid search to identify best hyperparameters for CNN model.
[ "Grid", "search", "to", "identify", "best", "hyperparameters", "for", "CNN", "model", "." ]
[ "\"\"\"Grid search to identify best hyperparameters for CNN model.\"\"\"", "# 5", "# 5", "# 4", "# 3", "# CNN ONLY # 3", "# CNN ONLY # 4", "# CNN ONLY # 4" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
2d6fcc24c023b59f0131bd400fa3ac4c75ae520a
alexkost819/thesis
tune.py
[ "Apache-2.0" ]
Python
tune_rnn_with_gridsearch
null
def tune_rnn_with_gridsearch(): """Grid search to identify best hyperparameters for RNN.""" rnn_model_values = [] n_epoch_list = [200, 400, 600, 800, 1000] # 5 batch_size_list = [16, 32, 64, 128, 256] # 5 learning_rate_...
Grid search to identify best hyperparameters for RNN.
Grid search to identify best hyperparameters for RNN.
[ "Grid", "search", "to", "identify", "best", "hyperparameters", "for", "RNN", "." ]
def tune_rnn_with_gridsearch(): rnn_model_values = [] n_epoch_list = [200, 400, 600, 800, 1000] batch_size_list = [16, 32, 64, 128, 256] learning_rate_list = [.001, .005, .0001, .0005] dropout...
[ "def", "tune_rnn_with_gridsearch", "(", ")", ":", "rnn_model_values", "=", "[", "]", "n_epoch_list", "=", "[", "200", ",", "400", ",", "600", ",", "800", ",", "1000", "]", "batch_size_list", "=", "[", "16", ",", "32", ",", "64", ",", "128", ",", "256...
Grid search to identify best hyperparameters for RNN.
[ "Grid", "search", "to", "identify", "best", "hyperparameters", "for", "RNN", "." ]
[ "\"\"\"Grid search to identify best hyperparameters for RNN.\"\"\"", "# 5", "# 5", "# 4", "# 3", "# RNN ONLY", "# RNN ONLY", "# RNN ONLY" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
8ef124b8f053736d19f8b080d34818cab2096c63
sinamoqadam/Farsi-OCR
detect.py
[ "MIT" ]
Python
arg_parse
<not_specific>
def arg_parse(): """ Parse arguments to the detect module """ parser = argparse.ArgumentParser(description='Farsi digit Detection Network') parser.add_argument("--cfg", dest='cfgfile', help= "Config file", default="cfg/architecture.cfg", type=str) return parser.par...
Parse arguments to the detect module
Parse arguments to the detect module
[ "Parse", "arguments", "to", "the", "detect", "module" ]
def arg_parse(): parser = argparse.ArgumentParser(description='Farsi digit Detection Network') parser.add_argument("--cfg", dest='cfgfile', help= "Config file", default="cfg/architecture.cfg", type=str) return parser.parse_args()
[ "def", "arg_parse", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Farsi digit Detection Network'", ")", "parser", ".", "add_argument", "(", "\"--cfg\"", ",", "dest", "=", "'cfgfile'", ",", "help", "=", "\"Config file...
Parse arguments to the detect module
[ "Parse", "arguments", "to", "the", "detect", "module" ]
[ "\"\"\"\n Parse arguments to the detect module\n\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
f1ee7119bfcb799fd6174dddd30d1182542b6fbf
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/baseline_network.py
[ "MIT" ]
Python
add_baseline_op
null
def add_baseline_op(self, scope = "baseline"): """ Build the baseline network within the scope. In this function we will build the baseline network. Use build_mlp with the same parameters as the policy network to get the baseline estimate. You also have to setup a target placeholder and an upda...
Build the baseline network within the scope. In this function we will build the baseline network. Use build_mlp with the same parameters as the policy network to get the baseline estimate. You also have to setup a target placeholder and an update operation so the baseline can be trained. Args...
Build the baseline network within the scope. In this function we will build the baseline network. Use build_mlp with the same parameters as the policy network to get the baseline estimate. You also have to setup a target placeholder and an update operation so the baseline can be trained.
[ "Build", "the", "baseline", "network", "within", "the", "scope", ".", "In", "this", "function", "we", "will", "build", "the", "baseline", "network", ".", "Use", "build_mlp", "with", "the", "same", "parameters", "as", "the", "policy", "network", "to", "get", ...
def add_baseline_op(self, scope = "baseline"): self.baseline = build_mlp(self.observation_placeholder, 1, scope, self.config.n_layers, self.config.layer_size, self.co...
[ "def", "add_baseline_op", "(", "self", ",", "scope", "=", "\"baseline\"", ")", ":", "self", ".", "baseline", "=", "build_mlp", "(", "self", ".", "observation_placeholder", ",", "1", ",", "scope", ",", "self", ".", "config", ".", "n_layers", ",", "self", ...
Build the baseline network within the scope.
[ "Build", "the", "baseline", "network", "within", "the", "scope", "." ]
[ "\"\"\"\n Build the baseline network within the scope.\n\n In this function we will build the baseline network.\n Use build_mlp with the same parameters as the policy network to\n get the baseline estimate. You also have to setup a target\n placeholder and an update operation so the baseline can be t...
[ { "param": "self", "type": null }, { "param": "scope", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "scope", "type": null, "docstring": "the scope of the baseline netwo...
f1ee7119bfcb799fd6174dddd30d1182542b6fbf
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/baseline_network.py
[ "MIT" ]
Python
update_baseline
null
def update_baseline(self, returns, observations): """ Update the baseline from given returns and observation. Args: returns: Returns from get_returns observations: observations TODO: apply the baseline update op with the observations and the returns. HINT: Run self.u...
Update the baseline from given returns and observation. Args: returns: Returns from get_returns observations: observations TODO: apply the baseline update op with the observations and the returns. HINT: Run self.update_baseline_op with self.sess.run(...)
Update the baseline from given returns and observation.
[ "Update", "the", "baseline", "from", "given", "returns", "and", "observation", "." ]
def update_baseline(self, returns, observations): self.sess.run(self.update_baseline_op, feed_dict={self.baseline_target_placeholder : returns, self.observation_placeholder : observations})
[ "def", "update_baseline", "(", "self", ",", "returns", ",", "observations", ")", ":", "self", ".", "sess", ".", "run", "(", "self", ".", "update_baseline_op", ",", "feed_dict", "=", "{", "self", ".", "baseline_target_placeholder", ":", "returns", ",", "self"...
Update the baseline from given returns and observation.
[ "Update", "the", "baseline", "from", "given", "returns", "and", "observation", "." ]
[ "\"\"\"\n Update the baseline from given returns and observation.\n\n Args:\n returns: Returns from get_returns\n observations: observations\n TODO:\n apply the baseline update op with the observations and the returns.\n HINT: Run self.update_baseline_op with self.sess.run(....
[ { "param": "self", "type": null }, { "param": "returns", "type": null }, { "param": "observations", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "returns", "type": null, "docstring": "Returns from get_returns", ...
460f0dace23270b4f148fcd044584157f3c8085c
ksang/cs234-assignments
assignment2_coding/starter_code/q2_linear.py
[ "MIT" ]
Python
add_placeholders_op
null
def add_placeholders_op(self): """ Adds placeholders to the graph These placeholders are used as inputs to the rest of the model and will be fed data during training. """ # this information might be useful state_shape = list(self.env.observation_space.sha...
Adds placeholders to the graph These placeholders are used as inputs to the rest of the model and will be fed data during training.
Adds placeholders to the graph These placeholders are used as inputs to the rest of the model and will be fed data during training.
[ "Adds", "placeholders", "to", "the", "graph", "These", "placeholders", "are", "used", "as", "inputs", "to", "the", "rest", "of", "the", "model", "and", "will", "be", "fed", "data", "during", "training", "." ]
def add_placeholders_op(self): state_shape = list(self.env.observation_space.shape) h, w, c = state_shape state_history = self.config.state_history self.s = tf.placeholder(tf.uint8, (None, h, w, c * state_history)) self.a = tf.placeholder(tf.int32, (None)) self.r = tf.pla...
[ "def", "add_placeholders_op", "(", "self", ")", ":", "state_shape", "=", "list", "(", "self", ".", "env", ".", "observation_space", ".", "shape", ")", "\"\"\"\r\n TODO:\r\n Add placeholders:\r\n Remember that we stack 4 consecutive frames together.\r\...
Adds placeholders to the graph These placeholders are used as inputs to the rest of the model and will be fed data during training.
[ "Adds", "placeholders", "to", "the", "graph", "These", "placeholders", "are", "used", "as", "inputs", "to", "the", "rest", "of", "the", "model", "and", "will", "be", "fed", "data", "during", "training", "." ]
[ "\"\"\"\r\n Adds placeholders to the graph\r\n\r\n These placeholders are used as inputs to the rest of the model and will be fed\r\n data during training.\r\n \"\"\"", "# this information might be useful\r", "##############################################################\r", "\"\"...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
460f0dace23270b4f148fcd044584157f3c8085c
ksang/cs234-assignments
assignment2_coding/starter_code/q2_linear.py
[ "MIT" ]
Python
add_update_target_op
null
def add_update_target_op(self, q_scope, target_q_scope): """ update_target_op will be called periodically to copy Q network weights to target Q network Remember that in DQN, we maintain two identical Q networks with 2 different sets of weights. In tensorflow, we distinguis...
update_target_op will be called periodically to copy Q network weights to target Q network Remember that in DQN, we maintain two identical Q networks with 2 different sets of weights. In tensorflow, we distinguish them with two different scopes. If you're not familiar wit...
update_target_op will be called periodically to copy Q network weights to target Q network Remember that in DQN, we maintain two identical Q networks with 2 different sets of weights. In tensorflow, we distinguish them with two different scopes. Periodically, we need to update all the weights of the Q network and ass...
[ "update_target_op", "will", "be", "called", "periodically", "to", "copy", "Q", "network", "weights", "to", "target", "Q", "network", "Remember", "that", "in", "DQN", "we", "maintain", "two", "identical", "Q", "networks", "with", "2", "different", "sets", "of",...
def add_update_target_op(self, q_scope, target_q_scope): q_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=q_scope) tq_vars = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=target_q_scope) ops = [tf.assign(tq_vars[i], q_vars[i]) for i in range(len(q_vars))] self.upd...
[ "def", "add_update_target_op", "(", "self", ",", "q_scope", ",", "target_q_scope", ")", ":", "\"\"\"\r\n TODO:\r\n Add an operator self.update_target_op that for each variable in\r\n tf.GraphKeys.GLOBAL_VARIABLES that is in q_scope, assigns its\r\n value t...
update_target_op will be called periodically to copy Q network weights to target Q network
[ "update_target_op", "will", "be", "called", "periodically", "to", "copy", "Q", "network", "weights", "to", "target", "Q", "network" ]
[ "\"\"\"\r\n update_target_op will be called periodically\r\n to copy Q network weights to target Q network\r\n\r\n Remember that in DQN, we maintain two identical Q networks with\r\n 2 different sets of weights. In tensorflow, we distinguish them\r\n with two different scopes. If ...
[ { "param": "self", "type": null }, { "param": "q_scope", "type": null }, { "param": "target_q_scope", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "q_scope", "type": null, "docstring": "(string) name of the scope of...
460f0dace23270b4f148fcd044584157f3c8085c
ksang/cs234-assignments
assignment2_coding/starter_code/q2_linear.py
[ "MIT" ]
Python
add_loss_op
null
def add_loss_op(self, q, target_q): """ Sets the loss of a batch, self.loss is a scalar Args: q: (tf tensor) shape = (batch_size, num_actions) target_q: (tf tensor) shape = (batch_size, num_actions) """ # you may need this variable num_ac...
Sets the loss of a batch, self.loss is a scalar Args: q: (tf tensor) shape = (batch_size, num_actions) target_q: (tf tensor) shape = (batch_size, num_actions)
Sets the loss of a batch, self.loss is a scalar
[ "Sets", "the", "loss", "of", "a", "batch", "self", ".", "loss", "is", "a", "scalar" ]
def add_loss_op(self, q, target_q): num_actions = self.env.action_space.n default = self.r + self.config.gamma * tf.reduce_max(target_q, axis=1) q_samp = tf.where(self.done_mask, self.r, default) actions = tf.one_hot(self.a, num_actions) q_old = tf.reduce_sum(tf.multiply(actions,...
[ "def", "add_loss_op", "(", "self", ",", "q", ",", "target_q", ")", ":", "num_actions", "=", "self", ".", "env", ".", "action_space", ".", "n", "\"\"\"\r\n TODO:\r\n The loss for an example is defined as:\r\n Q_samp(s) = r if done\r\n ...
Sets the loss of a batch, self.loss is a scalar
[ "Sets", "the", "loss", "of", "a", "batch", "self", ".", "loss", "is", "a", "scalar" ]
[ "\"\"\"\r\n Sets the loss of a batch, self.loss is a scalar\r\n\r\n Args:\r\n q: (tf tensor) shape = (batch_size, num_actions)\r\n target_q: (tf tensor) shape = (batch_size, num_actions)\r\n \"\"\"", "# you may need this variable\r", "##################################...
[ { "param": "self", "type": null }, { "param": "q", "type": null }, { "param": "target_q", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "q", "type": null, "docstring": "(tf tensor) shape = (batch_size, nu...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
add_placeholders_op
null
def add_placeholders_op(self): """ Add placeholders for observation, action, and advantage: self.observation_placeholder, type: tf.float32 self.action_placeholder, type: depends on the self.discrete self.advantage_placeholder, type: tf.float32 HINT: Check self.observation_dim and se...
Add placeholders for observation, action, and advantage: self.observation_placeholder, type: tf.float32 self.action_placeholder, type: depends on the self.discrete self.advantage_placeholder, type: tf.float32 HINT: Check self.observation_dim and self.action_dim HINT: In the case of...
Check self.observation_dim and self.action_dim HINT: In the case of continuous action space, an action will be specified by 'self.action_dim' float32 numbers
[ "Check", "self", ".", "observation_dim", "and", "self", ".", "action_dim", "HINT", ":", "In", "the", "case", "of", "continuous", "action", "space", "an", "action", "will", "be", "specified", "by", "'", "self", ".", "action_dim", "'", "float32", "numbers" ]
def add_placeholders_op(self): self.observation_placeholder = tf.placeholder(tf.float32, (None, self.observation_dim)) if gym.spaces.Discrete: self.action_placeholder = tf.placeholder(tf.int32, (None, )) else: self.action_placeholder = tf.placeholder(tf.float32, (None, self.action_dim)) ...
[ "def", "add_placeholders_op", "(", "self", ")", ":", "self", ".", "observation_placeholder", "=", "tf", ".", "placeholder", "(", "tf", ".", "float32", ",", "(", "None", ",", "self", ".", "observation_dim", ")", ")", "if", "gym", ".", "spaces", ".", "Disc...
Add placeholders for observation, action, and advantage: self.observation_placeholder, type: tf.float32 self.action_placeholder, type: depends on the self.discrete self.advantage_placeholder, type: tf.float32
[ "Add", "placeholders", "for", "observation", "action", "and", "advantage", ":", "self", ".", "observation_placeholder", "type", ":", "tf", ".", "float32", "self", ".", "action_placeholder", "type", ":", "depends", "on", "the", "self", ".", "discrete", "self", ...
[ "\"\"\"\n Add placeholders for observation, action, and advantage:\n self.observation_placeholder, type: tf.float32\n self.action_placeholder, type: depends on the self.discrete\n self.advantage_placeholder, type: tf.float32\n\n HINT: Check self.observation_dim and self.action_dim\n HI...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
build_policy_network_op
null
def build_policy_network_op(self, scope = "policy_network"): """ Build the policy network, construct the tensorflow operation to sample actions from the policy network outputs, and compute the log probabilities of the actions taken (for computing the loss later). These operations are stored in self....
Build the policy network, construct the tensorflow operation to sample actions from the policy network outputs, and compute the log probabilities of the actions taken (for computing the loss later). These operations are stored in self.sampled_action and self.logprob. Must handle both settings of se...
Build the policy network, construct the tensorflow operation to sample actions from the policy network outputs, and compute the log probabilities of the actions taken (for computing the loss later).
[ "Build", "the", "policy", "network", "construct", "the", "tensorflow", "operation", "to", "sample", "actions", "from", "the", "policy", "network", "outputs", "and", "compute", "the", "log", "probabilities", "of", "the", "actions", "taken", "(", "for", "computing...
def build_policy_network_op(self, scope = "policy_network"): if self.discrete: action_logits = build_mlp(self.observation_placeholder, self.action_dim, scope, self.config.n_layers, ...
[ "def", "build_policy_network_op", "(", "self", ",", "scope", "=", "\"policy_network\"", ")", ":", "if", "self", ".", "discrete", ":", "action_logits", "=", "build_mlp", "(", "self", ".", "observation_placeholder", ",", "self", ".", "action_dim", ",", "scope", ...
Build the policy network, construct the tensorflow operation to sample actions from the policy network outputs, and compute the log probabilities of the actions taken (for computing the loss later).
[ "Build", "the", "policy", "network", "construct", "the", "tensorflow", "operation", "to", "sample", "actions", "from", "the", "policy", "network", "outputs", "and", "compute", "the", "log", "probabilities", "of", "the", "actions", "taken", "(", "for", "computing...
[ "\"\"\"\n Build the policy network, construct the tensorflow operation to sample\n actions from the policy network outputs, and compute the log probabilities\n of the actions taken (for computing the loss later). These operations are\n stored in self.sampled_action and self.logprob. Must handle both set...
[ { "param": "self", "type": null }, { "param": "scope", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "scope", "type": null, "docstring": "the scope of the neural network...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
build
null
def build(self): """ Build the model by adding all necessary variables. You don't have to change anything here - we are just calling all the operations you already defined above to build the tensorflow graph. """ # add placeholders self.add_placeholders_op() # create policy net sel...
Build the model by adding all necessary variables. You don't have to change anything here - we are just calling all the operations you already defined above to build the tensorflow graph.
Build the model by adding all necessary variables. You don't have to change anything here - we are just calling all the operations you already defined above to build the tensorflow graph.
[ "Build", "the", "model", "by", "adding", "all", "necessary", "variables", ".", "You", "don", "'", "t", "have", "to", "change", "anything", "here", "-", "we", "are", "just", "calling", "all", "the", "operations", "you", "already", "defined", "above", "to", ...
def build(self): self.add_placeholders_op() self.build_policy_network_op() self.add_loss_op() self.add_optimizer_op() if self.config.use_baseline: self.baseline_network = BaselineNetwork(self.env, self.config, self.observation_placeholder) self.baseline_network.add_baseline_op()
[ "def", "build", "(", "self", ")", ":", "self", ".", "add_placeholders_op", "(", ")", "self", ".", "build_policy_network_op", "(", ")", "self", ".", "add_loss_op", "(", ")", "self", ".", "add_optimizer_op", "(", ")", "if", "self", ".", "config", ".", "use...
Build the model by adding all necessary variables.
[ "Build", "the", "model", "by", "adding", "all", "necessary", "variables", "." ]
[ "\"\"\"\n Build the model by adding all necessary variables.\n\n You don't have to change anything here - we are just calling\n all the operations you already defined above to build the tensorflow graph.\n \"\"\"", "# add placeholders", "# create policy net", "# add square loss", "# add optmizer...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
initialize
null
def initialize(self): """ Assumes the graph has been constructed (have called self.build()) Creates a tf Session and run initializer of variables You don't have to change or use anything here. """ # setting the seed #pdb.set_trace() # create tf session self.sess = tf.Session() ...
Assumes the graph has been constructed (have called self.build()) Creates a tf Session and run initializer of variables You don't have to change or use anything here.
Assumes the graph has been constructed (have called self.build()) Creates a tf Session and run initializer of variables You don't have to change or use anything here.
[ "Assumes", "the", "graph", "has", "been", "constructed", "(", "have", "called", "self", ".", "build", "()", ")", "Creates", "a", "tf", "Session", "and", "run", "initializer", "of", "variables", "You", "don", "'", "t", "have", "to", "change", "or", "use",...
def initialize(self): self.sess = tf.Session() self.add_summary() init = tf.global_variables_initializer() self.sess.run(init) if self.config.use_baseline: self.baseline_network.set_session(self.sess)
[ "def", "initialize", "(", "self", ")", ":", "self", ".", "sess", "=", "tf", ".", "Session", "(", ")", "self", ".", "add_summary", "(", ")", "init", "=", "tf", ".", "global_variables_initializer", "(", ")", "self", ".", "sess", ".", "run", "(", "init"...
Assumes the graph has been constructed (have called self.build()) Creates a tf Session and run initializer of variables
[ "Assumes", "the", "graph", "has", "been", "constructed", "(", "have", "called", "self", ".", "build", "()", ")", "Creates", "a", "tf", "Session", "and", "run", "initializer", "of", "variables" ]
[ "\"\"\"\n Assumes the graph has been constructed (have called self.build())\n Creates a tf Session and run initializer of variables\n\n You don't have to change or use anything here.\n \"\"\"", "# setting the seed", "#pdb.set_trace()", "# create tf session", "# tensorboard stuff", "# initiliaz...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
init_averages
null
def init_averages(self): """ Defines extra attributes for tensorboard. You don't have to change or use anything here. """ self.avg_reward = 0. self.max_reward = 0. self.std_reward = 0. self.eval_reward = 0.
Defines extra attributes for tensorboard. You don't have to change or use anything here.
Defines extra attributes for tensorboard. You don't have to change or use anything here.
[ "Defines", "extra", "attributes", "for", "tensorboard", ".", "You", "don", "'", "t", "have", "to", "change", "or", "use", "anything", "here", "." ]
def init_averages(self): self.avg_reward = 0. self.max_reward = 0. self.std_reward = 0. self.eval_reward = 0.
[ "def", "init_averages", "(", "self", ")", ":", "self", ".", "avg_reward", "=", "0.", "self", ".", "max_reward", "=", "0.", "self", ".", "std_reward", "=", "0.", "self", ".", "eval_reward", "=", "0." ]
Defines extra attributes for tensorboard.
[ "Defines", "extra", "attributes", "for", "tensorboard", "." ]
[ "\"\"\"\n Defines extra attributes for tensorboard.\n\n You don't have to change or use anything here.\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
update_averages
null
def update_averages(self, rewards, scores_eval): """ Update the averages. You don't have to change or use anything here. Args: rewards: deque scores_eval: list """ self.avg_reward = np.mean(rewards) self.max_reward = np.max(rewards) self.std_reward = np.sqrt(np.var(rewa...
Update the averages. You don't have to change or use anything here. Args: rewards: deque scores_eval: list
Update the averages. You don't have to change or use anything here.
[ "Update", "the", "averages", ".", "You", "don", "'", "t", "have", "to", "change", "or", "use", "anything", "here", "." ]
def update_averages(self, rewards, scores_eval): self.avg_reward = np.mean(rewards) self.max_reward = np.max(rewards) self.std_reward = np.sqrt(np.var(rewards) / len(rewards)) if len(scores_eval) > 0: self.eval_reward = scores_eval[-1]
[ "def", "update_averages", "(", "self", ",", "rewards", ",", "scores_eval", ")", ":", "self", ".", "avg_reward", "=", "np", ".", "mean", "(", "rewards", ")", "self", ".", "max_reward", "=", "np", ".", "max", "(", "rewards", ")", "self", ".", "std_reward...
Update the averages.
[ "Update", "the", "averages", "." ]
[ "\"\"\"\n Update the averages.\n\n You don't have to change or use anything here.\n\n Args:\n rewards: deque\n scores_eval: list\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "rewards", "type": null }, { "param": "scores_eval", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "rewards", "type": null, "docstring": null, "docstring_tokens"...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
record_summary
null
def record_summary(self, t): """ Add summary to tensorboard You don't have to change or use anything here. """ fd = { self.avg_reward_placeholder: self.avg_reward, self.max_reward_placeholder: self.max_reward, self.std_reward_placeholder: self.std_reward, self.eval_reward_p...
Add summary to tensorboard You don't have to change or use anything here.
Add summary to tensorboard You don't have to change or use anything here.
[ "Add", "summary", "to", "tensorboard", "You", "don", "'", "t", "have", "to", "change", "or", "use", "anything", "here", "." ]
def record_summary(self, t): fd = { self.avg_reward_placeholder: self.avg_reward, self.max_reward_placeholder: self.max_reward, self.std_reward_placeholder: self.std_reward, self.eval_reward_placeholder: self.eval_reward, } summary = self.sess.run(self.merged, feed_dict=fd) self....
[ "def", "record_summary", "(", "self", ",", "t", ")", ":", "fd", "=", "{", "self", ".", "avg_reward_placeholder", ":", "self", ".", "avg_reward", ",", "self", ".", "max_reward_placeholder", ":", "self", ".", "max_reward", ",", "self", ".", "std_reward_placeho...
Add summary to tensorboard You don't have to change or use anything here.
[ "Add", "summary", "to", "tensorboard", "You", "don", "'", "t", "have", "to", "change", "or", "use", "anything", "here", "." ]
[ "\"\"\"\n Add summary to tensorboard\n\n You don't have to change or use anything here.\n \"\"\"", "# tensorboard stuff" ]
[ { "param": "self", "type": null }, { "param": "t", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "t", "type": null, "docstring": null, "docstring_tokens": [], ...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
sample_path
<not_specific>
def sample_path(self, env, num_episodes = None): """ Sample paths (trajectories) from the environment. Args: num_episodes: the number of episodes to be sampled if none, sample one batch (size indicated by config file) env: open AI Gym envinronment Returns: paths: a ...
Sample paths (trajectories) from the environment. Args: num_episodes: the number of episodes to be sampled if none, sample one batch (size indicated by config file) env: open AI Gym envinronment Returns: paths: a list of paths. Each path in paths is a dictionary with ...
Sample paths (trajectories) from the environment.
[ "Sample", "paths", "(", "trajectories", ")", "from", "the", "environment", "." ]
def sample_path(self, env, num_episodes = None): episode = 0 episode_rewards = [] paths = [] t = 0 while (num_episodes or t < self.config.batch_size): state = env.reset() states, actions, rewards = [], [], [] episode_reward = 0 for step in range(self.config.max_ep_len): ...
[ "def", "sample_path", "(", "self", ",", "env", ",", "num_episodes", "=", "None", ")", ":", "episode", "=", "0", "episode_rewards", "=", "[", "]", "paths", "=", "[", "]", "t", "=", "0", "while", "(", "num_episodes", "or", "t", "<", "self", ".", "con...
Sample paths (trajectories) from the environment.
[ "Sample", "paths", "(", "trajectories", ")", "from", "the", "environment", "." ]
[ "\"\"\"\n Sample paths (trajectories) from the environment.\n\n Args:\n num_episodes: the number of episodes to be sampled\n if none, sample one batch (size indicated by config file)\n env: open AI Gym envinronment\n\n Returns:\n paths: a list of paths. Each path in paths is...
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "num_episodes", "type": null } ]
{ "returns": [ { "docstring": "a list of paths. Each path in paths is a dictionary with\npath[\"observation\"] a numpy array of ordered observations in the path\npath[\"actions\"] a numpy array of the corresponding actions in the path\npath[\"reward\"] a numpy array of the corresponding rewards in the path\...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
normalize_advantage
<not_specific>
def normalize_advantage(self, advantages): """ Normalizes the advantage. This function is called only if self.config.normalize_advantage is True. Args: advantages: the advantages Returns: adv: Normalized Advantage Calculate the advantages, by normalizing the advantages. ...
Normalizes the advantage. This function is called only if self.config.normalize_advantage is True. Args: advantages: the advantages Returns: adv: Normalized Advantage Calculate the advantages, by normalizing the advantages. TODO: Normalize the advantages so that they ...
Normalizes the advantage. This function is called only if self.config.normalize_advantage is True.
[ "Normalizes", "the", "advantage", ".", "This", "function", "is", "called", "only", "if", "self", ".", "config", ".", "normalize_advantage", "is", "True", "." ]
def normalize_advantage(self, advantages): advantages = (advantages - np.mean(advantages)) / np.std(advantages) return advantages
[ "def", "normalize_advantage", "(", "self", ",", "advantages", ")", ":", "advantages", "=", "(", "advantages", "-", "np", ".", "mean", "(", "advantages", ")", ")", "/", "np", ".", "std", "(", "advantages", ")", "return", "advantages" ]
Normalizes the advantage.
[ "Normalizes", "the", "advantage", "." ]
[ "\"\"\"\n Normalizes the advantage. This function is called only if self.config.normalize_advantage is True.\n\n Args:\n advantages: the advantages\n Returns:\n adv: Normalized Advantage\n\n Calculate the advantages, by normalizing the advantages.\n\n TODO:\n Normalize the ad...
[ { "param": "self", "type": null }, { "param": "advantages", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "adv" } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null ...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
calculate_advantage
<not_specific>
def calculate_advantage(self, returns, observations): """ Calculates the advantage for each of the observations Args: returns: the returns observations: the observations Returns: advantage: the advantage """ if self.config.use_baseline: # override the behavior of advantag...
Calculates the advantage for each of the observations Args: returns: the returns observations: the observations Returns: advantage: the advantage
Calculates the advantage for each of the observations
[ "Calculates", "the", "advantage", "for", "each", "of", "the", "observations" ]
def calculate_advantage(self, returns, observations): if self.config.use_baseline: advantages = self.baseline_network.calculate_advantage(returns, observations) else: advantages = returns if self.config.normalize_advantage: advantages = self.normalize_advantage(advantages) return advan...
[ "def", "calculate_advantage", "(", "self", ",", "returns", ",", "observations", ")", ":", "if", "self", ".", "config", ".", "use_baseline", ":", "advantages", "=", "self", ".", "baseline_network", ".", "calculate_advantage", "(", "returns", ",", "observations", ...
Calculates the advantage for each of the observations
[ "Calculates", "the", "advantage", "for", "each", "of", "the", "observations" ]
[ "\"\"\"\n Calculates the advantage for each of the observations\n Args:\n returns: the returns\n observations: the observations\n Returns:\n advantage: the advantage\n \"\"\"", "# override the behavior of advantage by subtracting baseline" ]
[ { "param": "self", "type": null }, { "param": "returns", "type": null }, { "param": "observations", "type": null } ]
{ "returns": [ { "docstring": null, "docstring_tokens": [ "None" ], "type": "advantage" } ], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": ...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
train
null
def train(self): """ Performs training You do not have to change or use anything here, but take a look to see how all the code you've written fits together! """ last_eval = 0 last_record = 0 scores_eval = [] self.init_averages() scores_eval = [] # list of scores computed at ite...
Performs training You do not have to change or use anything here, but take a look to see how all the code you've written fits together!
Performs training You do not have to change or use anything here, but take a look to see how all the code you've written fits together!
[ "Performs", "training", "You", "do", "not", "have", "to", "change", "or", "use", "anything", "here", "but", "take", "a", "look", "to", "see", "how", "all", "the", "code", "you", "'", "ve", "written", "fits", "together!" ]
def train(self): last_eval = 0 last_record = 0 scores_eval = [] self.init_averages() scores_eval = [] for t in range(self.config.num_batches): paths, total_rewards = self.sample_path(self.env) scores_eval = scores_eval + total_rewards observations = np.concatenate([path["obser...
[ "def", "train", "(", "self", ")", ":", "last_eval", "=", "0", "last_record", "=", "0", "scores_eval", "=", "[", "]", "self", ".", "init_averages", "(", ")", "scores_eval", "=", "[", "]", "for", "t", "in", "range", "(", "self", ".", "config", ".", "...
Performs training You do not have to change or use anything here, but take a look to see how all the code you've written fits together!
[ "Performs", "training", "You", "do", "not", "have", "to", "change", "or", "use", "anything", "here", "but", "take", "a", "look", "to", "see", "how", "all", "the", "code", "you", "'", "ve", "written", "fits", "together!" ]
[ "\"\"\"\n Performs training\n\n You do not have to change or use anything here, but take a look\n to see how all the code you've written fits together!\n \"\"\"", "# list of scores computed at iteration time", "# collect a minibatch of samples", "# compute Q-val estimates (discounted future return...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
evaluate
<not_specific>
def evaluate(self, env=None, num_episodes=1): """ Evaluates the return for num_episodes episodes. Not used right now, all evaluation statistics are computed during training episodes. """ if env==None: env = self.env paths, rewards = self.sample_path(env, num_episodes) avg_reward = np.mea...
Evaluates the return for num_episodes episodes. Not used right now, all evaluation statistics are computed during training episodes.
Evaluates the return for num_episodes episodes. Not used right now, all evaluation statistics are computed during training episodes.
[ "Evaluates", "the", "return", "for", "num_episodes", "episodes", ".", "Not", "used", "right", "now", "all", "evaluation", "statistics", "are", "computed", "during", "training", "episodes", "." ]
def evaluate(self, env=None, num_episodes=1): if env==None: env = self.env paths, rewards = self.sample_path(env, num_episodes) avg_reward = np.mean(rewards) sigma_reward = np.sqrt(np.var(rewards) / len(rewards)) msg = "Average reward: {:04.2f} +/- {:04.2f}".format(avg_reward, sigma_reward) self...
[ "def", "evaluate", "(", "self", ",", "env", "=", "None", ",", "num_episodes", "=", "1", ")", ":", "if", "env", "==", "None", ":", "env", "=", "self", ".", "env", "paths", ",", "rewards", "=", "self", ".", "sample_path", "(", "env", ",", "num_episod...
Evaluates the return for num_episodes episodes.
[ "Evaluates", "the", "return", "for", "num_episodes", "episodes", "." ]
[ "\"\"\"\n Evaluates the return for num_episodes episodes.\n Not used right now, all evaluation statistics are computed during training\n episodes.\n \"\"\"" ]
[ { "param": "self", "type": null }, { "param": "env", "type": null }, { "param": "num_episodes", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
record
null
def record(self): """ Recreate an env and record a video for one episode """ env = gym.make(self.config.env_name) env.seed(self.r_seed) env = gym.wrappers.Monitor(env, self.config.record_path, video_callable=lambda x: True, resume=True) self.evaluate(env, 1)
Recreate an env and record a video for one episode
Recreate an env and record a video for one episode
[ "Recreate", "an", "env", "and", "record", "a", "video", "for", "one", "episode" ]
def record(self): env = gym.make(self.config.env_name) env.seed(self.r_seed) env = gym.wrappers.Monitor(env, self.config.record_path, video_callable=lambda x: True, resume=True) self.evaluate(env, 1)
[ "def", "record", "(", "self", ")", ":", "env", "=", "gym", ".", "make", "(", "self", ".", "config", ".", "env_name", ")", "env", ".", "seed", "(", "self", ".", "r_seed", ")", "env", "=", "gym", ".", "wrappers", ".", "Monitor", "(", "env", ",", ...
Recreate an env and record a video for one episode
[ "Recreate", "an", "env", "and", "record", "a", "video", "for", "one", "episode" ]
[ "\"\"\"\n Recreate an env and record a video for one episode\n \"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
ee5b82ce09b21069b49532168c4e22a4184ca1db
ksang/cs234-assignments
assignment3_coding/starter_code 2/code/policy_network.py
[ "MIT" ]
Python
run
null
def run(self): """ Apply procedures of training for a PG. """ # initialize self.initialize() # record one game at the beginning if self.config.record: self.record() # model self.train() # record one game at the end if self.config.record: self.record()
Apply procedures of training for a PG.
Apply procedures of training for a PG.
[ "Apply", "procedures", "of", "training", "for", "a", "PG", "." ]
def run(self): self.initialize() if self.config.record: self.record() self.train() if self.config.record: self.record()
[ "def", "run", "(", "self", ")", ":", "self", ".", "initialize", "(", ")", "if", "self", ".", "config", ".", "record", ":", "self", ".", "record", "(", ")", "self", ".", "train", "(", ")", "if", "self", ".", "config", ".", "record", ":", "self", ...
Apply procedures of training for a PG.
[ "Apply", "procedures", "of", "training", "for", "a", "PG", "." ]
[ "\"\"\"\n Apply procedures of training for a PG.\n \"\"\"", "# initialize", "# record one game at the beginning", "# model", "# record one game at the end" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
465d5e265e29ccf902fa556a32b1d3b89a561889
ksang/cs234-assignments
assignment1_coding/vi_and_pi.py
[ "MIT" ]
Python
policy_improvement
<not_specific>
def policy_improvement(P, nS, nA, value_from_policy, policy, gamma=0.9): """Given the value function from policy improve the policy. Parameters ---------- P, nS, nA, gamma: defined at beginning of file value_from_policy: np.ndarray The value calculated from the policy policy: np...
Given the value function from policy improve the policy. Parameters ---------- P, nS, nA, gamma: defined at beginning of file value_from_policy: np.ndarray The value calculated from the policy policy: np.array The previous policy. Returns ------- new_policy: np....
Given the value function from policy improve the policy. Parameters P, nS, nA, gamma: defined at beginning of file value_from_policy: np.ndarray The value calculated from the policy policy: np.array The previous policy. Returns np.ndarray[nS] An array of integers. Each integer is the optimal action to take in that s...
[ "Given", "the", "value", "function", "from", "policy", "improve", "the", "policy", ".", "Parameters", "P", "nS", "nA", "gamma", ":", "defined", "at", "beginning", "of", "file", "value_from_policy", ":", "np", ".", "ndarray", "The", "value", "calculated", "fr...
def policy_improvement(P, nS, nA, value_from_policy, policy, gamma=0.9): new_policy = np.zeros(nS, dtype='int') for s in range(nS): action = 0 q_max = 0 for a in range(nA): probability, nextstate, reward, terminal = P[s][a][0] q = reward + gamma * probability * va...
[ "def", "policy_improvement", "(", "P", ",", "nS", ",", "nA", ",", "value_from_policy", ",", "policy", ",", "gamma", "=", "0.9", ")", ":", "new_policy", "=", "np", ".", "zeros", "(", "nS", ",", "dtype", "=", "'int'", ")", "for", "s", "in", "range", ...
Given the value function from policy improve the policy.
[ "Given", "the", "value", "function", "from", "policy", "improve", "the", "policy", "." ]
[ "\"\"\"Given the value function from policy improve the policy.\n\n Parameters\n ----------\n P, nS, nA, gamma:\n defined at beginning of file\n value_from_policy: np.ndarray\n The value calculated from the policy\n policy: np.array\n The previous policy.\n\n Returns\n ----...
[ { "param": "P", "type": null }, { "param": "nS", "type": null }, { "param": "nA", "type": null }, { "param": "value_from_policy", "type": null }, { "param": "policy", "type": null }, { "param": "gamma", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "P", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "nS", "type": null, "docstring": null, "docstring_tokens": [], ...
465d5e265e29ccf902fa556a32b1d3b89a561889
ksang/cs234-assignments
assignment1_coding/vi_and_pi.py
[ "MIT" ]
Python
render_single
null
def render_single(env, policy, max_steps=100): """ This function does not need to be modified Renders policy once on environment. Watch your agent play! Parameters ---------- env: gym.core.Environment Environment to play on. Must have nS, nA, and P as attributes. Policy: np.array ...
This function does not need to be modified Renders policy once on environment. Watch your agent play! Parameters ---------- env: gym.core.Environment Environment to play on. Must have nS, nA, and P as attributes. Policy: np.array of shape [env.nS] The action to take at a give...
This function does not need to be modified Renders policy once on environment. Watch your agent play! Parameters gym.core.Environment Environment to play on. Must have nS, nA, and P as attributes. Policy: np.array of shape [env.nS] The action to take at a given state
[ "This", "function", "does", "not", "need", "to", "be", "modified", "Renders", "policy", "once", "on", "environment", ".", "Watch", "your", "agent", "play!", "Parameters", "gym", ".", "core", ".", "Environment", "Environment", "to", "play", "on", ".", "Must",...
def render_single(env, policy, max_steps=100): episode_reward = 0 ob = env.reset() for t in range(max_steps): env.render() time.sleep(0.25) a = policy[ob] ob, rew, done, _ = env.step(a) episode_reward += rew if done: break env.render(); if not done: print("The agent didn't re...
[ "def", "render_single", "(", "env", ",", "policy", ",", "max_steps", "=", "100", ")", ":", "episode_reward", "=", "0", "ob", "=", "env", ".", "reset", "(", ")", "for", "t", "in", "range", "(", "max_steps", ")", ":", "env", ".", "render", "(", ")", ...
This function does not need to be modified Renders policy once on environment.
[ "This", "function", "does", "not", "need", "to", "be", "modified", "Renders", "policy", "once", "on", "environment", "." ]
[ "\"\"\"\n This function does not need to be modified\n Renders policy once on environment. Watch your agent play!\n\n Parameters\n ----------\n env: gym.core.Environment\n Environment to play on. Must have nS, nA, and P as\n attributes.\n Policy: np.array of shape [env.nS]\n The act...
[ { "param": "env", "type": null }, { "param": "policy", "type": null }, { "param": "max_steps", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "policy", "type": null, "docstring": null, "docstring_tokens": ...
838c8223290b4feb6aa083a005ee36e0c8118489
Saran33/TickerScrape
TickerScrape/models.py
[ "MIT" ]
Python
db_connect
<not_specific>
def db_connect(): """ Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance """ return create_engine(get_project_settings().get("CONNECTION_STRING"), connect_args={'check_same_thread': False},) # po...
Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance
Performs database connection using database settings from settings.py. Returns sqlalchemy engine instance
[ "Performs", "database", "connection", "using", "database", "settings", "from", "settings", ".", "py", ".", "Returns", "sqlalchemy", "engine", "instance" ]
def db_connect(): return create_engine(get_project_settings().get("CONNECTION_STRING"), connect_args={'check_same_thread': False},)
[ "def", "db_connect", "(", ")", ":", "return", "create_engine", "(", "get_project_settings", "(", ")", ".", "get", "(", "\"CONNECTION_STRING\"", ")", ",", "connect_args", "=", "{", "'check_same_thread'", ":", "False", "}", ",", ")" ]
Performs database connection using database settings from settings.py.
[ "Performs", "database", "connection", "using", "database", "settings", "from", "settings", ".", "py", "." ]
[ "\"\"\"\n Performs database connection using database settings from settings.py.\n Returns sqlalchemy engine instance\n \"\"\"", "# poolclass=StaticPool) # , echo=True)", "# return create_engine(get_project_settings().get(\"CONNECTION_STRING\"), connect_args={'check_same_thread': False})" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
2de350d2b0bb0fc9e74598a275a388f1523b63ba
Saran33/TickerScrape
TickerScrape/items.py
[ "MIT" ]
Python
curr_str_to_float
<not_specific>
def curr_str_to_float(cur_str, symbol='$'): '''Convert a currency string-formatted number into a float.''' num_strs = ['thousand', 'million', 'billion', 'trillion'] str_num_1 = None try: if not cur_str[0].isdigit(): symbol = cur_str[0] for x in num_strs: if x in ...
Convert a currency string-formatted number into a float.
Convert a currency string-formatted number into a float.
[ "Convert", "a", "currency", "string", "-", "formatted", "number", "into", "a", "float", "." ]
def curr_str_to_float(cur_str, symbol='$'): num_strs = ['thousand', 'million', 'billion', 'trillion'] str_num_1 = None try: if not cur_str[0].isdigit(): symbol = cur_str[0] for x in num_strs: if x in cur_str.lower(): str_num_1 = cur_str.lower().replace...
[ "def", "curr_str_to_float", "(", "cur_str", ",", "symbol", "=", "'$'", ")", ":", "num_strs", "=", "[", "'thousand'", ",", "'million'", ",", "'billion'", ",", "'trillion'", "]", "str_num_1", "=", "None", "try", ":", "if", "not", "cur_str", "[", "0", "]", ...
Convert a currency string-formatted number into a float.
[ "Convert", "a", "currency", "string", "-", "formatted", "number", "into", "a", "float", "." ]
[ "'''Convert a currency string-formatted number into a float.'''", "# str_num_1 = [cur_str.replace(x, '') for x in num_strs if x in cur_str.lower()]", "# print (\"${0:,.2f}\".format(fl_num))" ]
[ { "param": "cur_str", "type": null }, { "param": "symbol", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cur_str", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "symbol", "type": null, "docstring": null, "docstring_token...
2de350d2b0bb0fc9e74598a275a388f1523b63ba
Saran33/TickerScrape
TickerScrape/items.py
[ "MIT" ]
Python
curr_str_to_int
<not_specific>
def curr_str_to_int(cur_str, symbol='$'): '''Convert a currency string-formatted number into a float.''' num_strs = ['thousand', 'million', 'billion', 'trillion'] str_num_1 = None try: if not cur_str[0].isdigit(): symbol = cur_str[0] for x in num_strs: if x in cu...
Convert a currency string-formatted number into a float.
Convert a currency string-formatted number into a float.
[ "Convert", "a", "currency", "string", "-", "formatted", "number", "into", "a", "float", "." ]
def curr_str_to_int(cur_str, symbol='$'): num_strs = ['thousand', 'million', 'billion', 'trillion'] str_num_1 = None try: if not cur_str[0].isdigit(): symbol = cur_str[0] for x in num_strs: if x in cur_str.lower(): str_num_1 = cur_str.lower().replace(x...
[ "def", "curr_str_to_int", "(", "cur_str", ",", "symbol", "=", "'$'", ")", ":", "num_strs", "=", "[", "'thousand'", ",", "'million'", ",", "'billion'", ",", "'trillion'", "]", "str_num_1", "=", "None", "try", ":", "if", "not", "cur_str", "[", "0", "]", ...
Convert a currency string-formatted number into a float.
[ "Convert", "a", "currency", "string", "-", "formatted", "number", "into", "a", "float", "." ]
[ "'''Convert a currency string-formatted number into a float.'''", "# str_num_1 = [cur_str.replace(x, '') for x in num_strs if x in cur_str.lower()]" ]
[ { "param": "cur_str", "type": null }, { "param": "symbol", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cur_str", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "symbol", "type": null, "docstring": null, "docstring_token...
2de350d2b0bb0fc9e74598a275a388f1523b63ba
Saran33/TickerScrape
TickerScrape/items.py
[ "MIT" ]
Python
float_to_curr_str
<not_specific>
def float_to_curr_str(cur_float, symbol='$', decimals=0): '''Convert a float into a human readable shorthand format, using the numerize module. Then format the number with a currency symbol.''' try: cur_str = symbol + numerize(cur_float, decimals) except: cur_str = float("NaN") r...
Convert a float into a human readable shorthand format, using the numerize module. Then format the number with a currency symbol.
Convert a float into a human readable shorthand format, using the numerize module. Then format the number with a currency symbol.
[ "Convert", "a", "float", "into", "a", "human", "readable", "shorthand", "format", "using", "the", "numerize", "module", ".", "Then", "format", "the", "number", "with", "a", "currency", "symbol", "." ]
def float_to_curr_str(cur_float, symbol='$', decimals=0): try: cur_str = symbol + numerize(cur_float, decimals) except: cur_str = float("NaN") return cur_str
[ "def", "float_to_curr_str", "(", "cur_float", ",", "symbol", "=", "'$'", ",", "decimals", "=", "0", ")", ":", "try", ":", "cur_str", "=", "symbol", "+", "numerize", "(", "cur_float", ",", "decimals", ")", "except", ":", "cur_str", "=", "float", "(", "\...
Convert a float into a human readable shorthand format, using the numerize module.
[ "Convert", "a", "float", "into", "a", "human", "readable", "shorthand", "format", "using", "the", "numerize", "module", "." ]
[ "'''Convert a float into a human readable shorthand format, using the numerize module.\n Then format the number with a currency symbol.'''" ]
[ { "param": "cur_float", "type": null }, { "param": "symbol", "type": null }, { "param": "decimals", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "cur_float", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "symbol", "type": null, "docstring": null, "docstring_tok...
2de350d2b0bb0fc9e74598a275a388f1523b63ba
Saran33/TickerScrape
TickerScrape/items.py
[ "MIT" ]
Python
perc_str_to_float
<not_specific>
def perc_str_to_float(perc_str): '''Convert a percentage string-formatted number into a float.''' if type(perc_str) is str: try: fl_num = float(perc_str.replace(',', '').replace('%', '')) fl = fl_num / 100 except: fl = float("NaN") else: try: ...
Convert a percentage string-formatted number into a float.
Convert a percentage string-formatted number into a float.
[ "Convert", "a", "percentage", "string", "-", "formatted", "number", "into", "a", "float", "." ]
def perc_str_to_float(perc_str): if type(perc_str) is str: try: fl_num = float(perc_str.replace(',', '').replace('%', '')) fl = fl_num / 100 except: fl = float("NaN") else: try: fl_num = float(perc_str) fl = fl_num / 100 ...
[ "def", "perc_str_to_float", "(", "perc_str", ")", ":", "if", "type", "(", "perc_str", ")", "is", "str", ":", "try", ":", "fl_num", "=", "float", "(", "perc_str", ".", "replace", "(", "','", ",", "''", ")", ".", "replace", "(", "'%'", ",", "''", ")"...
Convert a percentage string-formatted number into a float.
[ "Convert", "a", "percentage", "string", "-", "formatted", "number", "into", "a", "float", "." ]
[ "'''Convert a percentage string-formatted number into a float.'''" ]
[ { "param": "perc_str", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "perc_str", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2de350d2b0bb0fc9e74598a275a388f1523b63ba
Saran33/TickerScrape
TickerScrape/items.py
[ "MIT" ]
Python
strp_brackets
<not_specific>
def strp_brackets(text): """ Strip brackets surrounding a string. """ return text.strip().strip('(').strip(')')
Strip brackets surrounding a string.
Strip brackets surrounding a string.
[ "Strip", "brackets", "surrounding", "a", "string", "." ]
def strp_brackets(text): return text.strip().strip('(').strip(')')
[ "def", "strp_brackets", "(", "text", ")", ":", "return", "text", ".", "strip", "(", ")", ".", "strip", "(", "'('", ")", ".", "strip", "(", "')'", ")" ]
Strip brackets surrounding a string.
[ "Strip", "brackets", "surrounding", "a", "string", "." ]
[ "\"\"\"\n Strip brackets surrounding a string.\n \"\"\"" ]
[ { "param": "text", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
2de350d2b0bb0fc9e74598a275a388f1523b63ba
Saran33/TickerScrape
TickerScrape/items.py
[ "MIT" ]
Python
convert_bi_dt
<not_specific>
def convert_bi_dt(text): """ convert string 'Sun Sep 26 2021 16:10:49 GMT+0000 (Coordinated Universal Time)' to Python date """ text = text.replace('(Coordinated Universal Time)', '').strip() try: dt = datetime.strptime(text, "%a %b %d %Y %H:%M:%S GMT%z") except: dt = parser.pars...
convert string 'Sun Sep 26 2021 16:10:49 GMT+0000 (Coordinated Universal Time)' to Python date
convert string 'Sun Sep 26 2021 16:10:49 GMT+0000 (Coordinated Universal Time)' to Python date
[ "convert", "string", "'", "Sun", "Sep", "26", "2021", "16", ":", "10", ":", "49", "GMT", "+", "0000", "(", "Coordinated", "Universal", "Time", ")", "'", "to", "Python", "date" ]
def convert_bi_dt(text): text = text.replace('(Coordinated Universal Time)', '').strip() try: dt = datetime.strptime(text, "%a %b %d %Y %H:%M:%S GMT%z") except: dt = parser.parse(text) return dt
[ "def", "convert_bi_dt", "(", "text", ")", ":", "text", "=", "text", ".", "replace", "(", "'(Coordinated Universal Time)'", ",", "''", ")", ".", "strip", "(", ")", "try", ":", "dt", "=", "datetime", ".", "strptime", "(", "text", ",", "\"%a %b %d %Y %H:%M:%S...
convert string 'Sun Sep 26 2021 16:10:49 GMT+0000 (Coordinated Universal Time)' to Python date
[ "convert", "string", "'", "Sun", "Sep", "26", "2021", "16", ":", "10", ":", "49", "GMT", "+", "0000", "(", "Coordinated", "Universal", "Time", ")", "'", "to", "Python", "date" ]
[ "\"\"\"\n convert string 'Sun Sep 26 2021 16:10:49 GMT+0000 (Coordinated Universal Time)' to Python date\n \"\"\"" ]
[ { "param": "text", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "text", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9a764412cfe29509e43e8d18db321f41d31a5805
GlobWetlandAfrica/installer
installer.py
[ "MIT" ]
Python
execute_cmd
null
def execute_cmd(self, cmd, shell=False, notify=False): """Execute cmd and save output to log file""" logger.info('Executing command: %s', cmd) try: si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW output = subprocess.check_output( ...
Execute cmd and save output to log file
Execute cmd and save output to log file
[ "Execute", "cmd", "and", "save", "output", "to", "log", "file" ]
def execute_cmd(self, cmd, shell=False, notify=False): logger.info('Executing command: %s', cmd) try: si = subprocess.STARTUPINFO() si.dwFlags |= subprocess.STARTF_USESHOWWINDOW output = subprocess.check_output( cmd, stdin=subprocess.PI...
[ "def", "execute_cmd", "(", "self", ",", "cmd", ",", "shell", "=", "False", ",", "notify", "=", "False", ")", ":", "logger", ".", "info", "(", "'Executing command: %s'", ",", "cmd", ")", "try", ":", "si", "=", "subprocess", ".", "STARTUPINFO", "(", ")",...
Execute cmd and save output to log file
[ "Execute", "cmd", "and", "save", "output", "to", "log", "file" ]
[ "\"\"\"Execute cmd and save output to log file\"\"\"" ]
[ { "param": "self", "type": null }, { "param": "cmd", "type": null }, { "param": "shell", "type": null }, { "param": "notify", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "cmd", "type": null, "docstring": null, "docstring_tokens": []...
39b1a66df447283c8a41d64cd0398ed297e76620
pcav/GeodesicDensifier3
geodesic_densifier.py
[ "CC-BY-4.0" ]
Python
initGui
null
def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/GeodesicDensifier3/icon.png' self.add_action( icon_path, text=u'Geodesic Densifier', callback=self.run, parent=self.iface.mainWindow())
Create the menu entries and toolbar icons inside the QGIS GUI.
Create the menu entries and toolbar icons inside the QGIS GUI.
[ "Create", "the", "menu", "entries", "and", "toolbar", "icons", "inside", "the", "QGIS", "GUI", "." ]
def initGui(self): icon_path = ':/plugins/GeodesicDensifier3/icon.png' self.add_action( icon_path, text=u'Geodesic Densifier', callback=self.run, parent=self.iface.mainWindow())
[ "def", "initGui", "(", "self", ")", ":", "icon_path", "=", "':/plugins/GeodesicDensifier3/icon.png'", "self", ".", "add_action", "(", "icon_path", ",", "text", "=", "u'Geodesic Densifier'", ",", "callback", "=", "self", ".", "run", ",", "parent", "=", "self", ...
Create the menu entries and toolbar icons inside the QGIS GUI.
[ "Create", "the", "menu", "entries", "and", "toolbar", "icons", "inside", "the", "QGIS", "GUI", "." ]
[ "\"\"\"Create the menu entries and toolbar icons inside the QGIS GUI.\"\"\"" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
39b1a66df447283c8a41d64cd0398ed297e76620
pcav/GeodesicDensifier3
geodesic_densifier.py
[ "CC-BY-4.0" ]
Python
unload
null
def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" for action in self.actions: self.iface.removePluginMenu(u'&Geodesic Densifier', action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar
Removes the plugin menu item and icon from QGIS GUI.
Removes the plugin menu item and icon from QGIS GUI.
[ "Removes", "the", "plugin", "menu", "item", "and", "icon", "from", "QGIS", "GUI", "." ]
def unload(self): for action in self.actions: self.iface.removePluginMenu(u'&Geodesic Densifier', action) self.iface.removeToolBarIcon(action) del self.toolbar
[ "def", "unload", "(", "self", ")", ":", "for", "action", "in", "self", ".", "actions", ":", "self", ".", "iface", ".", "removePluginMenu", "(", "u'&Geodesic Densifier'", ",", "action", ")", "self", ".", "iface", ".", "removeToolBarIcon", "(", "action", ")"...
Removes the plugin menu item and icon from QGIS GUI.
[ "Removes", "the", "plugin", "menu", "item", "and", "icon", "from", "QGIS", "GUI", "." ]
[ "\"\"\"Removes the plugin menu item and icon from QGIS GUI.\"\"\"", "# remove the toolbar" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
852fabbacb189afdab20e963a5b0ca388a1215eb
CollabAttempt/ForkCNN
DataBase Processing/CodeSnippet/VGG16 Multi Stream.py
[ "MIT" ]
Python
train_and_score
<not_specific>
def train_and_score(nb_classes,model_name): """Train the model, return test loss. Args: network (dict): the parameters of the network dataset (str): Dataset to use for training/evaluating """ ## setting network parameters batch_size = 64 epoch = 50 activation = "relu" ...
Train the model, return test loss. Args: network (dict): the parameters of the network dataset (str): Dataset to use for training/evaluating
Train the model, return test loss.
[ "Train", "the", "model", "return", "test", "loss", "." ]
def train_and_score(nb_classes,model_name): batch_size = 64 epoch = 50 activation = "relu" optimizer = optimizers.SGD(lr=0.003) img_rows, img_cols, img_channels = 128, 128, 3 print("Compling Keras model") thermal_input = Input(shape=(img_rows,img_cols,3),name='thermal_input') visible_in...
[ "def", "train_and_score", "(", "nb_classes", ",", "model_name", ")", ":", "batch_size", "=", "64", "epoch", "=", "50", "activation", "=", "\"relu\"", "optimizer", "=", "optimizers", ".", "SGD", "(", "lr", "=", "0.003", ")", "img_rows", ",", "img_cols", ","...
Train the model, return test loss.
[ "Train", "the", "model", "return", "test", "loss", "." ]
[ "\"\"\"Train the model, return test loss.\n\n Args:\n network (dict): the parameters of the network\n dataset (str): Dataset to use for training/evaluating\n\n \"\"\"", "## setting network parameters", "#in this case the number of GPus is 2", "######################################## Defin...
[ { "param": "nb_classes", "type": null }, { "param": "model_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "nb_classes", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "model_name", "type": null, "docstring": null, "docstrin...
a9ace7dab5426f9b1f6a161c7c60dd95526a1516
Whillikers/universal_attention
universal_attention/data.py
[ "MIT" ]
Python
load_segmentation_dataset
DatasetAndInfo
def load_segmentation_dataset(batch_size: int) -> DatasetAndInfo: """ Load the dataset used for zero-shot segmentation. Parameters ---------- batch_size: int Batch size to load the dataset with. Returns ------- dataset, info: DatasetAndInfo The segmentation dataset and ...
Load the dataset used for zero-shot segmentation. Parameters ---------- batch_size: int Batch size to load the dataset with. Returns ------- dataset, info: DatasetAndInfo The segmentation dataset and its information.
Load the dataset used for zero-shot segmentation. Parameters int Batch size to load the dataset with. Returns dataset, info: DatasetAndInfo The segmentation dataset and its information.
[ "Load", "the", "dataset", "used", "for", "zero", "-", "shot", "segmentation", ".", "Parameters", "int", "Batch", "size", "to", "load", "the", "dataset", "with", ".", "Returns", "dataset", "info", ":", "DatasetAndInfo", "The", "segmentation", "dataset", "and", ...
def load_segmentation_dataset(batch_size: int) -> DatasetAndInfo: splits, info = _load_dataset(SEGMENTATION_DATASET, batch_size) splits_processed = { key: ds.map( _resize_segmentation, num_parallel_calls=tf.data.experimental.AUTOTUNE, ) .batch(batch_size) ...
[ "def", "load_segmentation_dataset", "(", "batch_size", ":", "int", ")", "->", "DatasetAndInfo", ":", "splits", ",", "info", "=", "_load_dataset", "(", "SEGMENTATION_DATASET", ",", "batch_size", ")", "splits_processed", "=", "{", "key", ":", "ds", ".", "map", "...
Load the dataset used for zero-shot segmentation.
[ "Load", "the", "dataset", "used", "for", "zero", "-", "shot", "segmentation", "." ]
[ "\"\"\"\n Load the dataset used for zero-shot segmentation.\n\n Parameters\n ----------\n batch_size: int\n Batch size to load the dataset with.\n\n Returns\n -------\n dataset, info: DatasetAndInfo\n The segmentation dataset and its information.\n \"\"\"" ]
[ { "param": "batch_size", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "batch_size", "type": "int", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
d1150539192cf92cc79e4c6eb3c20801c17f2977
Whillikers/universal_attention
universal_attention/models.py
[ "MIT" ]
Python
attending_classifier
tf.keras.Model
def attending_classifier( encoder: layers.Layer, dataset_and_info: data.DatasetAndInfo ) -> tf.keras.Model: """ A classifier, made up of an encoder (possibly with attention) and a head to a fixed number of classes, run on fixed-size imagery. Parameters ---------- encoder: tf.keras.layers.La...
A classifier, made up of an encoder (possibly with attention) and a head to a fixed number of classes, run on fixed-size imagery. Parameters ---------- encoder: tf.keras.layers.Layer A layer returning AttendingEncoderOutput. dataset_and_info: data.DatasetAndInfo A dataset and i...
A classifier, made up of an encoder (possibly with attention) and a head to a fixed number of classes, run on fixed-size imagery. Parameters tf.keras.layers.Layer A layer returning AttendingEncoderOutput. dataset_and_info: data.DatasetAndInfo A dataset and its information, used to decide shapes. Returns tf.keras.Mo...
[ "A", "classifier", "made", "up", "of", "an", "encoder", "(", "possibly", "with", "attention", ")", "and", "a", "head", "to", "a", "fixed", "number", "of", "classes", "run", "on", "fixed", "-", "size", "imagery", ".", "Parameters", "tf", ".", "keras", "...
def attending_classifier( encoder: layers.Layer, dataset_and_info: data.DatasetAndInfo ) -> tf.keras.Model: splits, info = dataset_and_info img_shape = splits["train"].element_spec[0].shape[1:] num_classes = info.features["label"].num_classes image = tf.keras.Input(shape=(img_shape), name="image") ...
[ "def", "attending_classifier", "(", "encoder", ":", "layers", ".", "Layer", ",", "dataset_and_info", ":", "data", ".", "DatasetAndInfo", ")", "->", "tf", ".", "keras", ".", "Model", ":", "splits", ",", "info", "=", "dataset_and_info", "img_shape", "=", "spli...
A classifier, made up of an encoder (possibly with attention) and a head to a fixed number of classes, run on fixed-size imagery.
[ "A", "classifier", "made", "up", "of", "an", "encoder", "(", "possibly", "with", "attention", ")", "and", "a", "head", "to", "a", "fixed", "number", "of", "classes", "run", "on", "fixed", "-", "size", "imagery", "." ]
[ "\"\"\"\n A classifier, made up of an encoder (possibly with attention) and a head\n to a fixed number of classes, run on fixed-size imagery.\n\n Parameters\n ----------\n encoder: tf.keras.layers.Layer\n A layer returning AttendingEncoderOutput.\n dataset_and_info: data.DatasetAndInfo\n ...
[ { "param": "encoder", "type": "layers.Layer" }, { "param": "dataset_and_info", "type": "data.DatasetAndInfo" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "encoder", "type": "layers.Layer", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dataset_and_info", "type": "data.DatasetAndInfo", "doc...
13184fc266bbcff21dd5297e6a10d0f3f5a92eba
Whillikers/universal_attention
universal_attention/utils.py
[ "MIT" ]
Python
register_path_validator
None
def register_path_validator(flag_name: str, is_dir: bool = False) -> None: """ Register a validator ensuring that `flag_name` is an existing file. Parameters ---------- flag_name: str Name of the flag to register a validator for. is_dir: bool (default: False) Whether the file mu...
Register a validator ensuring that `flag_name` is an existing file. Parameters ---------- flag_name: str Name of the flag to register a validator for. is_dir: bool (default: False) Whether the file must also be a directory.
Register a validator ensuring that `flag_name` is an existing file. Parameters str Name of the flag to register a validator for. is_dir: bool (default: False) Whether the file must also be a directory.
[ "Register", "a", "validator", "ensuring", "that", "`", "flag_name", "`", "is", "an", "existing", "file", ".", "Parameters", "str", "Name", "of", "the", "flag", "to", "register", "a", "validator", "for", ".", "is_dir", ":", "bool", "(", "default", ":", "F...
def register_path_validator(flag_name: str, is_dir: bool = False) -> None: if is_dir: flags.register_validator( flag_name, _dir_validator, f"--{flag_name} must be an existing directory.", ) else: flags.register_validator( flag_name, ...
[ "def", "register_path_validator", "(", "flag_name", ":", "str", ",", "is_dir", ":", "bool", "=", "False", ")", "->", "None", ":", "if", "is_dir", ":", "flags", ".", "register_validator", "(", "flag_name", ",", "_dir_validator", ",", "f\"--{flag_name} must be an ...
Register a validator ensuring that `flag_name` is an existing file.
[ "Register", "a", "validator", "ensuring", "that", "`", "flag_name", "`", "is", "an", "existing", "file", "." ]
[ "\"\"\"\n Register a validator ensuring that `flag_name` is an existing file.\n\n Parameters\n ----------\n flag_name: str\n Name of the flag to register a validator for.\n is_dir: bool (default: False)\n Whether the file must also be a directory.\n \"\"\"" ]
[ { "param": "flag_name", "type": "str" }, { "param": "is_dir", "type": "bool" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "flag_name", "type": "str", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "is_dir", "type": "bool", "docstring": null, "docstring_...
13184fc266bbcff21dd5297e6a10d0f3f5a92eba
Whillikers/universal_attention
universal_attention/utils.py
[ "MIT" ]
Python
initialize_hardware
None
def initialize_hardware() -> None: """ Initialize the hardware for training or evaluation. Can only be called once globally. """ global _INITIALIZED # pylint:disable=global-statement if _INITIALIZED: raise RuntimeError("Hardware has already been initialized.") device = tf.config.l...
Initialize the hardware for training or evaluation. Can only be called once globally.
Initialize the hardware for training or evaluation. Can only be called once globally.
[ "Initialize", "the", "hardware", "for", "training", "or", "evaluation", ".", "Can", "only", "be", "called", "once", "globally", "." ]
def initialize_hardware() -> None: global _INITIALIZED if _INITIALIZED: raise RuntimeError("Hardware has already been initialized.") device = tf.config.list_physical_devices("GPU")[0] tf.config.experimental.set_memory_growth(device, True) if FLAGS.mixed_precision: precision_policy ...
[ "def", "initialize_hardware", "(", ")", "->", "None", ":", "global", "_INITIALIZED", "if", "_INITIALIZED", ":", "raise", "RuntimeError", "(", "\"Hardware has already been initialized.\"", ")", "device", "=", "tf", ".", "config", ".", "list_physical_devices", "(", "\...
Initialize the hardware for training or evaluation.
[ "Initialize", "the", "hardware", "for", "training", "or", "evaluation", "." ]
[ "\"\"\"\n Initialize the hardware for training or evaluation.\n Can only be called once globally.\n \"\"\"", "# pylint:disable=global-statement" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
989669bfcbf55bf9a02f0fddfd74048d39fa5b08
Whillikers/universal_attention
universal_attention/train.py
[ "MIT" ]
Python
train_subtask
None
def train_subtask( classifier: tf.keras.Model, task: data.DatasetAndInfo, num_batches: int, plot_summaries: bool = False, meta_step: Optional[int] = None, ) -> None: """ Use an encoder to create and train a new classifier on a meta-training dataset. Modifies the encoder's weights in plac...
Use an encoder to create and train a new classifier on a meta-training dataset. Modifies the encoder's weights in place. Parameters ---------- classifier: tf.keras.Model (tf.Tensor -> models.AttendingClassifierOutput) A classifier for this dataset. Assumed to be compiled. task: data.Da...
Use an encoder to create and train a new classifier on a meta-training dataset. Modifies the encoder's weights in place. Parameters
[ "Use", "an", "encoder", "to", "create", "and", "train", "a", "new", "classifier", "on", "a", "meta", "-", "training", "dataset", ".", "Modifies", "the", "encoder", "'", "s", "weights", "in", "place", ".", "Parameters" ]
def train_subtask( classifier: tf.keras.Model, task: data.DatasetAndInfo, num_batches: int, plot_summaries: bool = False, meta_step: Optional[int] = None, ) -> None: if plot_summaries: first_batch = True if meta_step is None: raise ValueError( "If plot...
[ "def", "train_subtask", "(", "classifier", ":", "tf", ".", "keras", ".", "Model", ",", "task", ":", "data", ".", "DatasetAndInfo", ",", "num_batches", ":", "int", ",", "plot_summaries", ":", "bool", "=", "False", ",", "meta_step", ":", "Optional", "[", "...
Use an encoder to create and train a new classifier on a meta-training dataset.
[ "Use", "an", "encoder", "to", "create", "and", "train", "a", "new", "classifier", "on", "a", "meta", "-", "training", "dataset", "." ]
[ "\"\"\"\n Use an encoder to create and train a new classifier on a meta-training\n dataset. Modifies the encoder's weights in place.\n\n Parameters\n ----------\n classifier: tf.keras.Model (tf.Tensor -> models.AttendingClassifierOutput)\n A classifier for this dataset. Assumed to be compiled....
[ { "param": "classifier", "type": "tf.keras.Model" }, { "param": "task", "type": "data.DatasetAndInfo" }, { "param": "num_batches", "type": "int" }, { "param": "plot_summaries", "type": "bool" }, { "param": "meta_step", "type": "Optional[int]" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "classifier", "type": "tf.keras.Model", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "task", "type": "data.DatasetAndInfo", "docstring"...
989669bfcbf55bf9a02f0fddfd74048d39fa5b08
Whillikers/universal_attention
universal_attention/train.py
[ "MIT" ]
Python
train_reptile
float
def train_reptile( meta_encoder: layers.Layer, run_name: str, batch_size: int, num_subtask_batches: int, subtask_learning_rate: float, meta_learning_rate: float, target_learning_rate: float, max_steps: Optional[int] = None, initial_step: int = 0, initial_checkpoint: Optional[str]...
Meta-train encoder with Reptile, evaluating on the target task periodically and at the end of training. NOTE: not all arguments to this function should should be left at their default values! This will lead to an infinite training run with no logs, checkpoints, or evaluation results. Paramete...
Meta-train encoder with Reptile, evaluating on the target task periodically and at the end of training. not all arguments to this function should should be left at their default values. This will lead to an infinite training run with no logs, checkpoints, or evaluation results. Parameters tf.keras.layers.Layer The e...
[ "Meta", "-", "train", "encoder", "with", "Reptile", "evaluating", "on", "the", "target", "task", "periodically", "and", "at", "the", "end", "of", "training", ".", "not", "all", "arguments", "to", "this", "function", "should", "should", "be", "left", "at", ...
def train_reptile( meta_encoder: layers.Layer, run_name: str, batch_size: int, num_subtask_batches: int, subtask_learning_rate: float, meta_learning_rate: float, target_learning_rate: float, max_steps: Optional[int] = None, initial_step: int = 0, initial_checkpoint: Optional[str]...
[ "def", "train_reptile", "(", "meta_encoder", ":", "layers", ".", "Layer", ",", "run_name", ":", "str", ",", "batch_size", ":", "int", ",", "num_subtask_batches", ":", "int", ",", "subtask_learning_rate", ":", "float", ",", "meta_learning_rate", ":", "float", "...
Meta-train encoder with Reptile, evaluating on the target task periodically and at the end of training.
[ "Meta", "-", "train", "encoder", "with", "Reptile", "evaluating", "on", "the", "target", "task", "periodically", "and", "at", "the", "end", "of", "training", "." ]
[ "\"\"\"\n Meta-train encoder with Reptile, evaluating on the target task periodically\n and at the end of training.\n\n NOTE: not all arguments to this function should should be left at their\n default values! This will lead to an infinite training run with no logs,\n checkpoints, or evaluation resul...
[ { "param": "meta_encoder", "type": "layers.Layer" }, { "param": "run_name", "type": "str" }, { "param": "batch_size", "type": "int" }, { "param": "num_subtask_batches", "type": "int" }, { "param": "subtask_learning_rate", "type": "float" }, { "param": ...
{ "returns": [], "raises": [], "params": [ { "identifier": "meta_encoder", "type": "layers.Layer", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "run_name", "type": "str", "docstring": null, ...
d4a6eeb252da9b62bb35d9fc36ef705f339164a5
Whillikers/universal_attention
universal_attention/summaries.py
[ "MIT" ]
Python
plot_summaries
None
def plot_summaries( images: np.ndarray, labels: np.ndarray, model: tf.keras.Model, ds_info: tfds.core.DatasetInfo, step: int, ) -> None: """ Plot classification performance and attention on a set of images. Parameters ---------- images: np.ndarray Images to use. labe...
Plot classification performance and attention on a set of images. Parameters ---------- images: np.ndarray Images to use. labels: np.ndarray True integer labels for the images. model: np.ndarray A Model: images -> AttendingClassifierOutput. ds_info: tfds.core.Datase...
Plot classification performance and attention on a set of images. Parameters
[ "Plot", "classification", "performance", "and", "attention", "on", "a", "set", "of", "images", ".", "Parameters" ]
def plot_summaries( images: np.ndarray, labels: np.ndarray, model: tf.keras.Model, ds_info: tfds.core.DatasetInfo, step: int, ) -> None: if not FLAGS.num_debug_images: return logits, attention_maps = model.predict_on_batch( images[: FLAGS.num_debug_images] ) probs = t...
[ "def", "plot_summaries", "(", "images", ":", "np", ".", "ndarray", ",", "labels", ":", "np", ".", "ndarray", ",", "model", ":", "tf", ".", "keras", ".", "Model", ",", "ds_info", ":", "tfds", ".", "core", ".", "DatasetInfo", ",", "step", ":", "int", ...
Plot classification performance and attention on a set of images.
[ "Plot", "classification", "performance", "and", "attention", "on", "a", "set", "of", "images", "." ]
[ "\"\"\"\n Plot classification performance and attention on a set of images.\n\n Parameters\n ----------\n images: np.ndarray\n Images to use.\n labels: np.ndarray\n True integer labels for the images.\n model: np.ndarray\n A Model: images -> AttendingClassifierOutput.\n ds_...
[ { "param": "images", "type": "np.ndarray" }, { "param": "labels", "type": "np.ndarray" }, { "param": "model", "type": "tf.keras.Model" }, { "param": "ds_info", "type": "tfds.core.DatasetInfo" }, { "param": "step", "type": "int" } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "images", "type": "np.ndarray", "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "labels", "type": "np.ndarray", "docstring": null, "...
a4a8fe91b0cc6b96f4e89f1de0435b1fee0c40ce
dvlbhanderi/Kali-p1
src/malware_classifier.py
[ "MIT" ]
Python
classify
<not_specific>
def classify(likelihoods, priors, data): """ creates classifications for each document in data parameters: likelihoods: an rdd of likelihoods for each class for each word priors: an rdd of priors for each class data: a pair rdd of tokens for each file """ # join likelihoods onto tokens f...
creates classifications for each document in data parameters: likelihoods: an rdd of likelihoods for each class for each word priors: an rdd of priors for each class data: a pair rdd of tokens for each file
creates classifications for each document in data parameters: likelihoods: an rdd of likelihoods for each class for each word priors: an rdd of priors for each class data: a pair rdd of tokens for each file
[ "creates", "classifications", "for", "each", "document", "in", "data", "parameters", ":", "likelihoods", ":", "an", "rdd", "of", "likelihoods", "for", "each", "class", "for", "each", "word", "priors", ":", "an", "rdd", "of", "priors", "for", "each", "class",...
def classify(likelihoods, priors, data): data = data.map(lambda x: (x[1], x[0])).join(likelihoods).map(lambda x: x[1]) data = data.mapValues(lambda x: [log(i) for i in x]) data = data.reduceByKey(lambda x, y: [i+j for i, j in zip(x, y)]) log_priors = priors.mapValues(lambda x: log(x)).values().collect()...
[ "def", "classify", "(", "likelihoods", ",", "priors", ",", "data", ")", ":", "data", "=", "data", ".", "map", "(", "lambda", "x", ":", "(", "x", "[", "1", "]", ",", "x", "[", "0", "]", ")", ")", ".", "join", "(", "likelihoods", ")", ".", "map...
creates classifications for each document in data parameters: likelihoods: an rdd of likelihoods for each class for each word priors: an rdd of priors for each class data: a pair rdd of tokens for each file
[ "creates", "classifications", "for", "each", "document", "in", "data", "parameters", ":", "likelihoods", ":", "an", "rdd", "of", "likelihoods", "for", "each", "class", "for", "each", "word", "priors", ":", "an", "rdd", "of", "priors", "for", "each", "class",...
[ "\"\"\"\n creates classifications for each document in data\n parameters:\n likelihoods: an rdd of likelihoods for each class for each word\n priors: an rdd of priors for each class\n data: a pair rdd of tokens for each file\n \"\"\"", "# join likelihoods onto tokens from test data", "# conver...
[ { "param": "likelihoods", "type": null }, { "param": "priors", "type": null }, { "param": "data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "likelihoods", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "priors", "type": null, "docstring": null, "docstring_t...
a4a8fe91b0cc6b96f4e89f1de0435b1fee0c40ce
dvlbhanderi/Kali-p1
src/malware_classifier.py
[ "MIT" ]
Python
smoothing
<not_specific>
def smoothing(train_dat, test_dat): '''The Function being tested should take labeled training data and tokenized testing data and number of classes and return an RDD of the training data with a new entry added for each unique (label, word) pair to increase the count of all vocab by 1 for each l...
The Function being tested should take labeled training data and tokenized testing data and number of classes and return an RDD of the training data with a new entry added for each unique (label, word) pair to increase the count of all vocab by 1 for each label to avoid 0 probabilities
The Function being tested should take labeled training data and tokenized testing data and number of classes and return an RDD of the training data with a new entry added for each unique (label, word) pair to increase the count of all vocab by 1 for each label to avoid 0 probabilities
[ "The", "Function", "being", "tested", "should", "take", "labeled", "training", "data", "and", "tokenized", "testing", "data", "and", "number", "of", "classes", "and", "return", "an", "RDD", "of", "the", "training", "data", "with", "a", "new", "entry", "added...
def smoothing(train_dat, test_dat): label_dat = train_dat.flatMap(lambda x : x) label_dat = label_dat.filter(lambda x : len(x) != 2) label_dat = label_dat.distinct() n = label.count() word_dat = train_dat.flatMap(lambda x : x) word_dat = word_dat.filter(lambda x : len(x) == 2) word_dat = word_dat.distinct() ...
[ "def", "smoothing", "(", "train_dat", ",", "test_dat", ")", ":", "label_dat", "=", "train_dat", ".", "flatMap", "(", "lambda", "x", ":", "x", ")", "label_dat", "=", "label_dat", ".", "filter", "(", "lambda", "x", ":", "len", "(", "x", ")", "!=", "2",...
The Function being tested should take labeled training data and tokenized testing data and number of classes and return an RDD of the training data with a new entry added for each unique (label, word) pair to increase the count of all vocab by 1 for each label to avoid 0 probabilities
[ "The", "Function", "being", "tested", "should", "take", "labeled", "training", "data", "and", "tokenized", "testing", "data", "and", "number", "of", "classes", "and", "return", "an", "RDD", "of", "the", "training", "data", "with", "a", "new", "entry", "added...
[ "'''The Function being tested should take labeled training data and\n tokenized testing data and number of classes and return an RDD of the training data with a\n new entry added for each unique (label, word) pair to increase the\n count of all vocab by 1 for each label to avoid 0 probabilities...
[ { "param": "train_dat", "type": null }, { "param": "test_dat", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "train_dat", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "test_dat", "type": null, "docstring": null, "docstring_t...
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
configure_spark
<not_specific>
def configure_spark(exec_mem, driver_mem, result_mem): ''' This function configures spark. It accepts as input the memory to be allocated to each executor, memory to be allocated to the driver and memory to be allocated for the output. Argument 1(String) : Memory to be allocated to the executors ...
This function configures spark. It accepts as input the memory to be allocated to each executor, memory to be allocated to the driver and memory to be allocated for the output. Argument 1(String) : Memory to be allocated to the executors Argument 2(String) : Memory to be allocated to the driver ...
This function configures spark. It accepts as input the memory to be allocated to each executor, memory to be allocated to the driver and memory to be allocated for the output. Argument 1(String) : Memory to be allocated to the executors Argument 2(String) : Memory to be allocated to the driver Argument 3(String) : Ma...
[ "This", "function", "configures", "spark", ".", "It", "accepts", "as", "input", "the", "memory", "to", "be", "allocated", "to", "each", "executor", "memory", "to", "be", "allocated", "to", "the", "driver", "and", "memory", "to", "be", "allocated", "for", "...
def configure_spark(exec_mem, driver_mem, result_mem): conf = pyspark.SparkConf().setAppName('Malware Classification') conf = (conf.setMaster('local[*]') .set('spark.executor.memory', exec_mem) .set('spark.driver.memory', driver_mem) .set('spark.driver.maxResultSize', result_mem)) sc = ...
[ "def", "configure_spark", "(", "exec_mem", ",", "driver_mem", ",", "result_mem", ")", ":", "conf", "=", "pyspark", ".", "SparkConf", "(", ")", ".", "setAppName", "(", "'Malware Classification'", ")", "conf", "=", "(", "conf", ".", "setMaster", "(", "'local[*...
This function configures spark.
[ "This", "function", "configures", "spark", "." ]
[ "'''\n This function configures spark. It accepts as input the memory to be allocated\n to each executor, memory to be allocated to the driver and memory to be allocated\n for the output.\n\n Argument 1(String) : Memory to be allocated to the executors\n Argument 2(String) : Memory to be allocated to...
[ { "param": "exec_mem", "type": null }, { "param": "driver_mem", "type": null }, { "param": "result_mem", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "exec_mem", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "driver_mem", "type": null, "docstring": null, "docstring_...
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
readFile
<not_specific>
def readFile(path): ''' This function reads the files from the given path and return an rdd containing file data. Arg1: path of the directory of the files. ''' return sc.textFile(path,minPartitions = 32)
This function reads the files from the given path and return an rdd containing file data. Arg1: path of the directory of the files.
This function reads the files from the given path and return an rdd containing file data. path of the directory of the files.
[ "This", "function", "reads", "the", "files", "from", "the", "given", "path", "and", "return", "an", "rdd", "containing", "file", "data", ".", "path", "of", "the", "directory", "of", "the", "files", "." ]
def readFile(path): return sc.textFile(path,minPartitions = 32)
[ "def", "readFile", "(", "path", ")", ":", "return", "sc", ".", "textFile", "(", "path", ",", "minPartitions", "=", "32", ")" ]
This function reads the files from the given path and return an rdd containing file data.
[ "This", "function", "reads", "the", "files", "from", "the", "given", "path", "and", "return", "an", "rdd", "containing", "file", "data", "." ]
[ "'''\n This function reads the files from the given path and return an rdd containing\n file data.\n\n Arg1: path of the directory of the files.\n\n '''" ]
[ { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
readWholeFile
<not_specific>
def readWholeFile(path): ''' This function reads the files along with filenames from the given path and return an rdd containing filename and its data. Arg1: Path of the directory of the files. ''' return sc.wholeTextFiles(path, minPartitions = 32)
This function reads the files along with filenames from the given path and return an rdd containing filename and its data. Arg1: Path of the directory of the files.
This function reads the files along with filenames from the given path and return an rdd containing filename and its data. Path of the directory of the files.
[ "This", "function", "reads", "the", "files", "along", "with", "filenames", "from", "the", "given", "path", "and", "return", "an", "rdd", "containing", "filename", "and", "its", "data", ".", "Path", "of", "the", "directory", "of", "the", "files", "." ]
def readWholeFile(path): return sc.wholeTextFiles(path, minPartitions = 32)
[ "def", "readWholeFile", "(", "path", ")", ":", "return", "sc", ".", "wholeTextFiles", "(", "path", ",", "minPartitions", "=", "32", ")" ]
This function reads the files along with filenames from the given path and return an rdd containing filename and its data.
[ "This", "function", "reads", "the", "files", "along", "with", "filenames", "from", "the", "given", "path", "and", "return", "an", "rdd", "containing", "filename", "and", "its", "data", "." ]
[ "'''\n This function reads the files along with filenames from the given path\n and return an rdd containing filename and its data.\n\n Arg1: Path of the directory of the files.\n\n '''" ]
[ { "param": "path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
readTrainingFiles
<not_specific>
def readTrainingFiles(filename_path, filelabel_path, data_path): ''' This function reads the name of the training files, their labels and their data given each of these paths and returns an rdd containing the data and an rdd containing the labels. Arg1 : Path of the file storing the name of the fil...
This function reads the name of the training files, their labels and their data given each of these paths and returns an rdd containing the data and an rdd containing the labels. Arg1 : Path of the file storing the name of the files. Arg2 : Path of the file storing the labels of these files. A...
This function reads the name of the training files, their labels and their data given each of these paths and returns an rdd containing the data and an rdd containing the labels. Arg1 : Path of the file storing the name of the files. Arg2 : Path of the file storing the labels of these files. Arg3 : Path where the data...
[ "This", "function", "reads", "the", "name", "of", "the", "training", "files", "their", "labels", "and", "their", "data", "given", "each", "of", "these", "paths", "and", "returns", "an", "rdd", "containing", "the", "data", "and", "an", "rdd", "containing", ...
def readTrainingFiles(filename_path, filelabel_path, data_path): x_train = readFile(filename_path) y_train = readFile(filelabel_path) byte_data_directory = data_path x_filenames = x_train.map(lambda x: byte_data_directory+x+'.bytes') x_filenames = x_filenames.collect() dat_train = readWholeFile(...
[ "def", "readTrainingFiles", "(", "filename_path", ",", "filelabel_path", ",", "data_path", ")", ":", "x_train", "=", "readFile", "(", "filename_path", ")", "y_train", "=", "readFile", "(", "filelabel_path", ")", "byte_data_directory", "=", "data_path", "x_filenames"...
This function reads the name of the training files, their labels and their data given each of these paths and returns an rdd containing the data and an rdd containing the labels.
[ "This", "function", "reads", "the", "name", "of", "the", "training", "files", "their", "labels", "and", "their", "data", "given", "each", "of", "these", "paths", "and", "returns", "an", "rdd", "containing", "the", "data", "and", "an", "rdd", "containing", ...
[ "'''\n This function reads the name of the training files, their labels\n and their data given each of these paths and returns an rdd containing\n the data and an rdd containing the labels.\n\n Arg1 : Path of the file storing the name of the files.\n Arg2 : Path of the file storing the labels of thes...
[ { "param": "filename_path", "type": null }, { "param": "filelabel_path", "type": null }, { "param": "data_path", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "filename_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "filelabel_path", "type": null, "docstring": null, "d...
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
preprocessing_trainingfiles
<not_specific>
def preprocessing_trainingfiles(labelfile_rdd, dat_rdd): ''' This function preprocess the training files and returns and rdd containing the filenames,data and their labels. Arg1 : rdd containing the labels and filenames Arg2 : rdd containing the data and filenames. ''' #shortening the full f...
This function preprocess the training files and returns and rdd containing the filenames,data and their labels. Arg1 : rdd containing the labels and filenames Arg2 : rdd containing the data and filenames.
This function preprocess the training files and returns and rdd containing the filenames,data and their labels. Arg1 : rdd containing the labels and filenames Arg2 : rdd containing the data and filenames.
[ "This", "function", "preprocess", "the", "training", "files", "and", "returns", "and", "rdd", "containing", "the", "filenames", "data", "and", "their", "labels", ".", "Arg1", ":", "rdd", "containing", "the", "labels", "and", "filenames", "Arg2", ":", "rdd", ...
def preprocessing_trainingfiles(labelfile_rdd, dat_rdd): labelfile_rdd = labelfile_rdd.map(lambda x : (x[0].split('/')[-1],x[1])) dat_rdd = dat_rdd.map(lambda x : (x[0],x[1].split()[1:])) dat_rdd = dat_rdd.map(lambda x : (x[0].split('/')[-1],x[1])) dat_rdd = labelfile_rdd.join(dat_rdd) return dat_rd...
[ "def", "preprocessing_trainingfiles", "(", "labelfile_rdd", ",", "dat_rdd", ")", ":", "labelfile_rdd", "=", "labelfile_rdd", ".", "map", "(", "lambda", "x", ":", "(", "x", "[", "0", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ",", "x", "[...
This function preprocess the training files and returns and rdd containing the filenames,data and their labels.
[ "This", "function", "preprocess", "the", "training", "files", "and", "returns", "and", "rdd", "containing", "the", "filenames", "data", "and", "their", "labels", "." ]
[ "'''\n This function preprocess the training files and returns and rdd containing\n the filenames,data and their labels.\n Arg1 : rdd containing the labels and filenames\n Arg2 : rdd containing the data and filenames.\n '''", "#shortening the full filepath to just the filename for the label", "#R...
[ { "param": "labelfile_rdd", "type": null }, { "param": "dat_rdd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "labelfile_rdd", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "dat_rdd", "type": null, "docstring": null, "docstrin...
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
rddToDf_training
<not_specific>
def rddToDf_training(dat_rdd): ''' This function converts rdd of the training files to the data frame and returns the dataframe. Arg1(rdd) : rdd to be converted to dataframe. ''' #converting the rdd to dataframe with labels print('*********** inside to convert into dataframe ********************...
This function converts rdd of the training files to the data frame and returns the dataframe. Arg1(rdd) : rdd to be converted to dataframe.
This function converts rdd of the training files to the data frame and returns the dataframe. Arg1(rdd) : rdd to be converted to dataframe.
[ "This", "function", "converts", "rdd", "of", "the", "training", "files", "to", "the", "data", "frame", "and", "returns", "the", "dataframe", ".", "Arg1", "(", "rdd", ")", ":", "rdd", "to", "be", "converted", "to", "dataframe", "." ]
def rddToDf_training(dat_rdd): print('*********** inside to convert into dataframe *********************') print('*********** inside to convert into dataframe *********************') print('*********** inside to convert into dataframe *********************') final_df = dat_rdd.map(lambda line : Row(data...
[ "def", "rddToDf_training", "(", "dat_rdd", ")", ":", "print", "(", "'*********** inside to convert into dataframe *********************'", ")", "print", "(", "'*********** inside to convert into dataframe *********************'", ")", "print", "(", "'*********** inside to convert int...
This function converts rdd of the training files to the data frame and returns the dataframe.
[ "This", "function", "converts", "rdd", "of", "the", "training", "files", "to", "the", "data", "frame", "and", "returns", "the", "dataframe", "." ]
[ "'''\n This function converts rdd of the training files to the data frame and returns the dataframe.\n Arg1(rdd) : rdd to be converted to dataframe.\n '''", "#converting the rdd to dataframe with labels" ]
[ { "param": "dat_rdd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "dat_rdd", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
typeCastColumn
<not_specific>
def typeCastColumn(countVector_df): ''' This function type casts column of a dataframe to the specified data type, and returns the modified dataframe. Arg1 : dataframe whose column has to be typecasted. Arg2 : name of the column which has to be typecasted. Arg3 : Data type to which it has to be ...
This function type casts column of a dataframe to the specified data type, and returns the modified dataframe. Arg1 : dataframe whose column has to be typecasted. Arg2 : name of the column which has to be typecasted. Arg3 : Data type to which it has to be type casted.
This function type casts column of a dataframe to the specified data type, and returns the modified dataframe. Arg1 : dataframe whose column has to be typecasted. Arg2 : name of the column which has to be typecasted. Arg3 : Data type to which it has to be type casted.
[ "This", "function", "type", "casts", "column", "of", "a", "dataframe", "to", "the", "specified", "data", "type", "and", "returns", "the", "modified", "dataframe", ".", "Arg1", ":", "dataframe", "whose", "column", "has", "to", "be", "typecasted", ".", "Arg2",...
def typeCastColumn(countVector_df): print('************ insdie type casting **************') print('************ insdie type casting **************') print('************ insdie type casting **************') final_df = countVector_df.withColumn('label', countVector_df['label'].cast('int')) print('***...
[ "def", "typeCastColumn", "(", "countVector_df", ")", ":", "print", "(", "'************ insdie type casting **************'", ")", "print", "(", "'************ insdie type casting **************'", ")", "print", "(", "'************ insdie type casting **************'", ")", "final...
This function type casts column of a dataframe to the specified data type, and returns the modified dataframe.
[ "This", "function", "type", "casts", "column", "of", "a", "dataframe", "to", "the", "specified", "data", "type", "and", "returns", "the", "modified", "dataframe", "." ]
[ "'''\n This function type casts column of a dataframe to the specified data type,\n and returns the modified dataframe.\n Arg1 : dataframe whose column has to be typecasted.\n Arg2 : name of the column which has to be typecasted.\n Arg3 : Data type to which it has to be type casted.\n '''", "#ty...
[ { "param": "countVector_df", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "countVector_df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
train_random_forest
<not_specific>
def train_random_forest(final_df): ''' This function accepts a dataframe as an input and train the machine using this data on randomforest algorithm to generate a model and returns the model. Arg1 : dataframe on which model has to be trained. ''' print('********* inside training random forest ...
This function accepts a dataframe as an input and train the machine using this data on randomforest algorithm to generate a model and returns the model. Arg1 : dataframe on which model has to be trained.
This function accepts a dataframe as an input and train the machine using this data on randomforest algorithm to generate a model and returns the model. Arg1 : dataframe on which model has to be trained.
[ "This", "function", "accepts", "a", "dataframe", "as", "an", "input", "and", "train", "the", "machine", "using", "this", "data", "on", "randomforest", "algorithm", "to", "generate", "a", "model", "and", "returns", "the", "model", ".", "Arg1", ":", "dataframe...
def train_random_forest(final_df): print('********* inside training random forest **************') print('********* inside training random forest ************') print('********* inside training random forest ************') rf = RandomForestClassifier(labelCol = "label", featuresCol = "indexedFeatures", ...
[ "def", "train_random_forest", "(", "final_df", ")", ":", "print", "(", "'********* inside training random forest **************'", ")", "print", "(", "'********* inside training random forest ************'", ")", "print", "(", "'********* inside training random forest ************'",...
This function accepts a dataframe as an input and train the machine using this data on randomforest algorithm to generate a model and returns the model.
[ "This", "function", "accepts", "a", "dataframe", "as", "an", "input", "and", "train", "the", "machine", "using", "this", "data", "on", "randomforest", "algorithm", "to", "generate", "a", "model", "and", "returns", "the", "model", "." ]
[ "'''\n This function accepts a dataframe as an input and train the machine using\n this data on randomforest algorithm to generate a model and returns the model.\n\n Arg1 : dataframe on which model has to be trained.\n '''", "#training the model" ]
[ { "param": "final_df", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "final_df", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
c774634be98d7e0254c0fe5fff1961d61a5b70e4
dvlbhanderi/Kali-p1
src/random_forest.py
[ "MIT" ]
Python
predict
<not_specific>
def predict(rfModel, data): ''' This functoin accepts as input the model previously trained and the data on which prediction has to be made and returns the predictions. Arg1 : Model obtained from training. Arg2 : Data on which predictions has to be made. ''' predictions = rfModel.transform(...
This functoin accepts as input the model previously trained and the data on which prediction has to be made and returns the predictions. Arg1 : Model obtained from training. Arg2 : Data on which predictions has to be made.
This functoin accepts as input the model previously trained and the data on which prediction has to be made and returns the predictions. Arg1 : Model obtained from training. Arg2 : Data on which predictions has to be made.
[ "This", "functoin", "accepts", "as", "input", "the", "model", "previously", "trained", "and", "the", "data", "on", "which", "prediction", "has", "to", "be", "made", "and", "returns", "the", "predictions", ".", "Arg1", ":", "Model", "obtained", "from", "train...
def predict(rfModel, data): predictions = rfModel.transform(data) return predictions
[ "def", "predict", "(", "rfModel", ",", "data", ")", ":", "predictions", "=", "rfModel", ".", "transform", "(", "data", ")", "return", "predictions" ]
This functoin accepts as input the model previously trained and the data on which prediction has to be made and returns the predictions.
[ "This", "functoin", "accepts", "as", "input", "the", "model", "previously", "trained", "and", "the", "data", "on", "which", "prediction", "has", "to", "be", "made", "and", "returns", "the", "predictions", "." ]
[ "'''\n This functoin accepts as input the model previously trained and the data on which\n prediction has to be made and returns the predictions.\n\n Arg1 : Model obtained from training.\n Arg2 : Data on which predictions has to be made.\n '''" ]
[ { "param": "rfModel", "type": null }, { "param": "data", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "rfModel", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "data", "type": null, "docstring": null, "docstring_tokens"...
0d5dcf64a74c50ea36999746d6fe268b024c2deb
dvlbhanderi/Kali-p1
src/spark_NB.py
[ "MIT" ]
Python
read_data
<not_specific>
def read_data(byte_data_directory, x_filename, y_filename=None): """ reads in byte date from a list of filenames given in file located at x_filename. if y_filename is supplied labels will be read in and a map will be created as well and a label column added to the returned dataframe """ X_files...
reads in byte date from a list of filenames given in file located at x_filename. if y_filename is supplied labels will be read in and a map will be created as well and a label column added to the returned dataframe
reads in byte date from a list of filenames given in file located at x_filename. if y_filename is supplied labels will be read in and a map will be created as well and a label column added to the returned dataframe
[ "reads", "in", "byte", "date", "from", "a", "list", "of", "filenames", "given", "in", "file", "located", "at", "x_filename", ".", "if", "y_filename", "is", "supplied", "labels", "will", "be", "read", "in", "and", "a", "map", "will", "be", "created", "as"...
def read_data(byte_data_directory, x_filename, y_filename=None): X_files = sc.textFile(x_filename).collect() X_filenames = list(map(lambda x: byte_data_directory+x+'.bytes', X_files)) dat = sc.wholeTextFiles(",".join(X_filenames), minPartitions=300) X_df = sc.parallelize(X_filenames, numSlices=300).map(...
[ "def", "read_data", "(", "byte_data_directory", ",", "x_filename", ",", "y_filename", "=", "None", ")", ":", "X_files", "=", "sc", ".", "textFile", "(", "x_filename", ")", ".", "collect", "(", ")", "X_filenames", "=", "list", "(", "map", "(", "lambda", "...
reads in byte date from a list of filenames given in file located at x_filename.
[ "reads", "in", "byte", "date", "from", "a", "list", "of", "filenames", "given", "in", "file", "located", "at", "x_filename", "." ]
[ "\"\"\"\n reads in byte date from a list of filenames given in file located\n at x_filename. if y_filename is supplied labels will be read in and a map\n will be created as well and a label column added to the returned dataframe\n \"\"\"" ]
[ { "param": "byte_data_directory", "type": null }, { "param": "x_filename", "type": null }, { "param": "y_filename", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "byte_data_directory", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "x_filename", "type": null, "docstring": null, ...
0d5dcf64a74c50ea36999746d6fe268b024c2deb
dvlbhanderi/Kali-p1
src/spark_NB.py
[ "MIT" ]
Python
create_pipeline
<not_specific>
def create_pipeline(): """ creates model pipeline Currently uses RegexTokenizer to get bytewords as tokens, hashingTF to featurize the tokens as word counts, and NaiveBayes to fit and classify This is where most of the work will be done in improving the model """ tokenizer = RegexTokenizer...
creates model pipeline Currently uses RegexTokenizer to get bytewords as tokens, hashingTF to featurize the tokens as word counts, and NaiveBayes to fit and classify This is where most of the work will be done in improving the model
creates model pipeline Currently uses RegexTokenizer to get bytewords as tokens, hashingTF to featurize the tokens as word counts, and NaiveBayes to fit and classify This is where most of the work will be done in improving the model
[ "creates", "model", "pipeline", "Currently", "uses", "RegexTokenizer", "to", "get", "bytewords", "as", "tokens", "hashingTF", "to", "featurize", "the", "tokens", "as", "word", "counts", "and", "NaiveBayes", "to", "fit", "and", "classify", "This", "is", "where", ...
def create_pipeline(): tokenizer = RegexTokenizer(inputCol="text", outputCol="words", pattern="(?<=\\s)..", gaps=False) ngram = NGram(n=2, inputCol="words", outputCol="grams") hashingTF = HashingTF(numFeatures=65792, inputCol=ngram.getOutputCol(), out...
[ "def", "create_pipeline", "(", ")", ":", "tokenizer", "=", "RegexTokenizer", "(", "inputCol", "=", "\"text\"", ",", "outputCol", "=", "\"words\"", ",", "pattern", "=", "\"(?<=\\\\s)..\"", ",", "gaps", "=", "False", ")", "ngram", "=", "NGram", "(", "n", "="...
creates model pipeline Currently uses RegexTokenizer to get bytewords as tokens, hashingTF to featurize the tokens as word counts, and NaiveBayes to fit and classify
[ "creates", "model", "pipeline", "Currently", "uses", "RegexTokenizer", "to", "get", "bytewords", "as", "tokens", "hashingTF", "to", "featurize", "the", "tokens", "as", "word", "counts", "and", "NaiveBayes", "to", "fit", "and", "classify" ]
[ "\"\"\"\n creates model pipeline\n Currently uses RegexTokenizer to get bytewords as tokens, hashingTF to\n featurize the tokens as word counts, and NaiveBayes to fit and classify\n\n This is where most of the work will be done in improving the model\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
437d662a596fdec58dbb53484e64c9106037140a
michi1992/item-catalog
vagrant/itemcatalog.py
[ "MIT" ]
Python
show_categories
<not_specific>
def show_categories(): """ Shows a list of all categories """ # return 'Hello, World!' <-- Basic usage # returning HTML websites as Python strings is not very convenient. # It's far better to use Flask's `render_template()` function and # Jinja2 templates, which are really awesome. # see: ht...
Shows a list of all categories
Shows a list of all categories
[ "Shows", "a", "list", "of", "all", "categories" ]
def show_categories(): return render_template('categories.html', page_heading="Catalog App", categories=db.get_categories())
[ "def", "show_categories", "(", ")", ":", "return", "render_template", "(", "'categories.html'", ",", "page_heading", "=", "\"Catalog App\"", ",", "categories", "=", "db", ".", "get_categories", "(", ")", ")" ]
Shows a list of all categories
[ "Shows", "a", "list", "of", "all", "categories" ]
[ "\"\"\" Shows a list of all categories \"\"\"", "# return 'Hello, World!' <-- Basic usage", "# returning HTML websites as Python strings is not very convenient.", "# It's far better to use Flask's `render_template()` function and", "# Jinja2 templates, which are really awesome.", "# see: http://flask.p...
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
437d662a596fdec58dbb53484e64c9106037140a
michi1992/item-catalog
vagrant/itemcatalog.py
[ "MIT" ]
Python
show_items
<not_specific>
def show_items(category_name): """ Displays a list of all items in this category """ return render_template('items.html', page_heading=category_name + ' Items', items=db.get_items_of_category(category_name), category=category_name)
Displays a list of all items in this category
Displays a list of all items in this category
[ "Displays", "a", "list", "of", "all", "items", "in", "this", "category" ]
def show_items(category_name): return render_template('items.html', page_heading=category_name + ' Items', items=db.get_items_of_category(category_name), category=category_name)
[ "def", "show_items", "(", "category_name", ")", ":", "return", "render_template", "(", "'items.html'", ",", "page_heading", "=", "category_name", "+", "' Items'", ",", "items", "=", "db", ".", "get_items_of_category", "(", "category_name", ")", ",", "category", ...
Displays a list of all items in this category
[ "Displays", "a", "list", "of", "all", "items", "in", "this", "category" ]
[ "\"\"\" Displays a list of all items in this category \"\"\"" ]
[ { "param": "category_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "category_name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
437d662a596fdec58dbb53484e64c9106037140a
michi1992/item-catalog
vagrant/itemcatalog.py
[ "MIT" ]
Python
show_item
<not_specific>
def show_item(category_name, item_name): """ Returns the item's detail page """ return render_template('item.html', page_heading=item_name, item=db.get_item_by_title(item_name))
Returns the item's detail page
Returns the item's detail page
[ "Returns", "the", "item", "'", "s", "detail", "page" ]
def show_item(category_name, item_name): return render_template('item.html', page_heading=item_name, item=db.get_item_by_title(item_name))
[ "def", "show_item", "(", "category_name", ",", "item_name", ")", ":", "return", "render_template", "(", "'item.html'", ",", "page_heading", "=", "item_name", ",", "item", "=", "db", ".", "get_item_by_title", "(", "item_name", ")", ")" ]
Returns the item's detail page
[ "Returns", "the", "item", "'", "s", "detail", "page" ]
[ "\"\"\" Returns the item's detail page \"\"\"" ]
[ { "param": "category_name", "type": null }, { "param": "item_name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "category_name", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "item_name", "type": null, "docstring": null, "docstr...
ab0d4877165d8f2110a9a8b6e62ea510304b654f
ArrayOfThrones/playboy-on-reddit
src/garbage_collector.py
[ "MIT" ]
Python
log_cleaner
null
def log_cleaner(): """This function cleans out the run_log.log file. This function is meant to run once per month. Returns ------- """ open('../data/run_log.log', 'w')
This function cleans out the run_log.log file. This function is meant to run once per month. Returns -------
This function cleans out the run_log.log file. This function is meant to run once per month. Returns
[ "This", "function", "cleans", "out", "the", "run_log", ".", "log", "file", ".", "This", "function", "is", "meant", "to", "run", "once", "per", "month", ".", "Returns" ]
def log_cleaner(): open('../data/run_log.log', 'w')
[ "def", "log_cleaner", "(", ")", ":", "open", "(", "'../data/run_log.log'", ",", "'w'", ")" ]
This function cleans out the run_log.log file.
[ "This", "function", "cleans", "out", "the", "run_log", ".", "log", "file", "." ]
[ "\"\"\"This function cleans out the run_log.log file. This function is meant\n to run once per month.\n\n Returns\n -------\n\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
ab0d4877165d8f2110a9a8b6e62ea510304b654f
ArrayOfThrones/playboy-on-reddit
src/garbage_collector.py
[ "MIT" ]
Python
submissions_cleaner
null
def submissions_cleaner(): """This function cleans out the submissions_processed.txt file. This function is meant to run once per month. Returns ------- """ submission_file = \ open('../data/submissions_processed.txt', 'r').read().split('\n') last_50 = '\n'.join(submission_file[-5...
This function cleans out the submissions_processed.txt file. This function is meant to run once per month. Returns -------
This function cleans out the submissions_processed.txt file. This function is meant to run once per month. Returns
[ "This", "function", "cleans", "out", "the", "submissions_processed", ".", "txt", "file", ".", "This", "function", "is", "meant", "to", "run", "once", "per", "month", ".", "Returns" ]
def submissions_cleaner(): submission_file = \ open('../data/submissions_processed.txt', 'r').read().split('\n') last_50 = '\n'.join(submission_file[-51:-1]) open('../data/submissions_processed.txt', 'w') open('../data/submissions_processed.txt', 'a').write( last_50 )
[ "def", "submissions_cleaner", "(", ")", ":", "submission_file", "=", "open", "(", "'../data/submissions_processed.txt'", ",", "'r'", ")", ".", "read", "(", ")", ".", "split", "(", "'\\n'", ")", "last_50", "=", "'\\n'", ".", "join", "(", "submission_file", "[...
This function cleans out the submissions_processed.txt file.
[ "This", "function", "cleans", "out", "the", "submissions_processed", ".", "txt", "file", "." ]
[ "\"\"\"This function cleans out the submissions_processed.txt file. This\n function is meant to run once per month.\n\n Returns\n -------\n\n \"\"\"" ]
[]
{ "returns": [], "raises": [], "params": [], "outlier_params": [], "others": [] }
3ed84b7894cddd8ccafc41a2c3604f9beee0e990
mrmansano/sublime-ycmd
lib/ycmd/settings.py
[ "MIT" ]
Python
generate_settings_data
<not_specific>
def generate_settings_data(ycmd_settings_path, hmac_secret): ''' Generates and returns a settings `dict` containing the options for starting a ycmd server. This settings object should be written to a json file and supplied as a command-line argument to the ycmd module. The `hmac_secret` argument sho...
Generates and returns a settings `dict` containing the options for starting a ycmd server. This settings object should be written to a json file and supplied as a command-line argument to the ycmd module. The `hmac_secret` argument should be the binary-encoded HMAC secret. It will be base64-encoded...
Generates and returns a settings `dict` containing the options for starting a ycmd server. This settings object should be written to a json file and supplied as a command-line argument to the ycmd module. The `hmac_secret` argument should be the binary-encoded HMAC secret. It will be base64-encoded before adding it to ...
[ "Generates", "and", "returns", "a", "settings", "`", "dict", "`", "containing", "the", "options", "for", "starting", "a", "ycmd", "server", ".", "This", "settings", "object", "should", "be", "written", "to", "a", "json", "file", "and", "supplied", "as", "a...
def generate_settings_data(ycmd_settings_path, hmac_secret): assert isinstance(ycmd_settings_path, str), \ 'ycmd settings path must be a str: %r' % (ycmd_settings_path) if not is_file(ycmd_settings_path): logger.warning( 'ycmd settings path appears to be invalid: %r', ycmd_settings_p...
[ "def", "generate_settings_data", "(", "ycmd_settings_path", ",", "hmac_secret", ")", ":", "assert", "isinstance", "(", "ycmd_settings_path", ",", "str", ")", ",", "'ycmd settings path must be a str: %r'", "%", "(", "ycmd_settings_path", ")", "if", "not", "is_file", "(...
Generates and returns a settings `dict` containing the options for starting a ycmd server.
[ "Generates", "and", "returns", "a", "settings", "`", "dict", "`", "containing", "the", "options", "for", "starting", "a", "ycmd", "server", "." ]
[ "'''\n Generates and returns a settings `dict` containing the options for\n starting a ycmd server. This settings object should be written to a json\n file and supplied as a command-line argument to the ycmd module.\n The `hmac_secret` argument should be the binary-encoded HMAC secret. It\n will be b...
[ { "param": "ycmd_settings_path", "type": null }, { "param": "hmac_secret", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "ycmd_settings_path", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "hmac_secret", "type": null, "docstring": null, ...
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
args
<not_specific>
def args(self): ''' Returns the process args. Initializes it if it is None. ''' if self._args is None: self._args = [] return self._args
Returns the process args. Initializes it if it is None.
Returns the process args. Initializes it if it is None.
[ "Returns", "the", "process", "args", ".", "Initializes", "it", "if", "it", "is", "None", "." ]
def args(self): if self._args is None: self._args = [] return self._args
[ "def", "args", "(", "self", ")", ":", "if", "self", ".", "_args", "is", "None", ":", "self", ".", "_args", "=", "[", "]", "return", "self", ".", "_args" ]
Returns the process args.
[ "Returns", "the", "process", "args", "." ]
[ "''' Returns the process args. Initializes it if it is None. '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
env
<not_specific>
def env(self): ''' Returns the process env. Initializes it if it is `None`. ''' if self._env is None: self._env = {} return self._env
Returns the process env. Initializes it if it is `None`.
Returns the process env. Initializes it if it is `None`.
[ "Returns", "the", "process", "env", ".", "Initializes", "it", "if", "it", "is", "`", "None", "`", "." ]
def env(self): if self._env is None: self._env = {} return self._env
[ "def", "env", "(", "self", ")", ":", "if", "self", ".", "_env", "is", "None", ":", "self", ".", "_env", "=", "{", "}", "return", "self", ".", "_env" ]
Returns the process env.
[ "Returns", "the", "process", "env", "." ]
[ "''' Returns the process env. Initializes it if it is `None`. '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
env
null
def env(self, env): ''' Sets the process environment variables. ''' if self.alive(): logger.warning('process already started... no point setting env') assert isinstance(env, dict), 'env must be a dictionary: %r' % env if self._env is not None: logger.warning('ov...
Sets the process environment variables.
Sets the process environment variables.
[ "Sets", "the", "process", "environment", "variables", "." ]
def env(self, env): if self.alive(): logger.warning('process already started... no point setting env') assert isinstance(env, dict), 'env must be a dictionary: %r' % env if self._env is not None: logger.warning('overwriting existing process env: %r', self._env) lo...
[ "def", "env", "(", "self", ",", "env", ")", ":", "if", "self", ".", "alive", "(", ")", ":", "logger", ".", "warning", "(", "'process already started... no point setting env'", ")", "assert", "isinstance", "(", "env", ",", "dict", ")", ",", "'env must be a di...
Sets the process environment variables.
[ "Sets", "the", "process", "environment", "variables", "." ]
[ "''' Sets the process environment variables. '''" ]
[ { "param": "self", "type": null }, { "param": "env", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "env", "type": null, "docstring": null, "docstring_tokens": []...
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
cwd
null
def cwd(self, cwd): ''' Sets the process working directory. ''' if self.alive(): logger.warning('process already started... no point setting cwd') assert isinstance(cwd, str), 'cwd must be a string: %r' % cwd if not is_directory(cwd): logger.warning('invalid work...
Sets the process working directory.
Sets the process working directory.
[ "Sets", "the", "process", "working", "directory", "." ]
def cwd(self, cwd): if self.alive(): logger.warning('process already started... no point setting cwd') assert isinstance(cwd, str), 'cwd must be a string: %r' % cwd if not is_directory(cwd): logger.warning('invalid working directory: %s', cwd) logger.debug('settin...
[ "def", "cwd", "(", "self", ",", "cwd", ")", ":", "if", "self", ".", "alive", "(", ")", ":", "logger", ".", "warning", "(", "'process already started... no point setting cwd'", ")", "assert", "isinstance", "(", "cwd", ",", "str", ")", ",", "'cwd must be a str...
Sets the process working directory.
[ "Sets", "the", "process", "working", "directory", "." ]
[ "''' Sets the process working directory. '''" ]
[ { "param": "self", "type": null }, { "param": "cwd", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "cwd", "type": null, "docstring": null, "docstring_tokens": []...
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
alive
<not_specific>
def alive(self): ''' Returns whether or not the process is active. ''' if self._handle is None: return False assert isinstance(self._handle, subprocess.Popen), \ '[internal] handle is not a Popen instance: %r' % self._handle status = self._handle.poll() s...
Returns whether or not the process is active.
Returns whether or not the process is active.
[ "Returns", "whether", "or", "not", "the", "process", "is", "active", "." ]
def alive(self): if self._handle is None: return False assert isinstance(self._handle, subprocess.Popen), \ '[internal] handle is not a Popen instance: %r' % self._handle status = self._handle.poll() status_desc = 'alive' if status is None else 'exited (%r)' % (st...
[ "def", "alive", "(", "self", ")", ":", "if", "self", ".", "_handle", "is", "None", ":", "return", "False", "assert", "isinstance", "(", "self", ".", "_handle", ",", "subprocess", ".", "Popen", ")", ",", "'[internal] handle is not a Popen instance: %r'", "%", ...
Returns whether or not the process is active.
[ "Returns", "whether", "or", "not", "the", "process", "is", "active", "." ]
[ "''' Returns whether or not the process is active. '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
start
null
def start(self): ''' Starts the process according to current configuration. ''' if self.alive(): raise Exception('process has already been started') assert self._binary is not None and isinstance(self._binary, str), \ 'process binary is invalid: %r' % self._binary ...
Starts the process according to current configuration.
Starts the process according to current configuration.
[ "Starts", "the", "process", "according", "to", "current", "configuration", "." ]
def start(self): if self.alive(): raise Exception('process has already been started') assert self._binary is not None and isinstance(self._binary, str), \ 'process binary is invalid: %r' % self._binary assert self._args is None or hasattr(self._args, '__iter__'), \ ...
[ "def", "start", "(", "self", ")", ":", "if", "self", ".", "alive", "(", ")", ":", "raise", "Exception", "(", "'process has already been started'", ")", "assert", "self", ".", "_binary", "is", "not", "None", "and", "isinstance", "(", "self", ".", "_binary",...
Starts the process according to current configuration.
[ "Starts", "the", "process", "according", "to", "current", "configuration", "." ]
[ "''' Starts the process according to current configuration. '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
communicate
<not_specific>
def communicate(self, inpt=None, timeout=None): ''' Sends data via stdin and reads data from stdout, stderr. This will likely block if the process is still alive. When `inpt` is `None`, stdin is immediately closed. When `timeout` is `None`, this waits indefinitely for the process...
Sends data via stdin and reads data from stdout, stderr. This will likely block if the process is still alive. When `inpt` is `None`, stdin is immediately closed. When `timeout` is `None`, this waits indefinitely for the process to terminate. Otherwise, it is interpreted as the ...
Sends data via stdin and reads data from stdout, stderr. This will likely block if the process is still alive. When `inpt` is `None`, stdin is immediately closed. When `timeout` is `None`, this waits indefinitely for the process to terminate. Otherwise, it is interpreted as the number of seconds to wait for until raisi...
[ "Sends", "data", "via", "stdin", "and", "reads", "data", "from", "stdout", "stderr", ".", "This", "will", "likely", "block", "if", "the", "process", "is", "still", "alive", ".", "When", "`", "inpt", "`", "is", "`", "None", "`", "stdin", "is", "immediat...
def communicate(self, inpt=None, timeout=None): if not self.alive(): logger.debug('process not alive, unlikely to block') assert self._handle is not None, '[internal] process handle is null' return self._handle.communicate(inpt, timeout)
[ "def", "communicate", "(", "self", ",", "inpt", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "alive", "(", ")", ":", "logger", ".", "debug", "(", "'process not alive, unlikely to block'", ")", "assert", "self", ".", "_han...
Sends data via stdin and reads data from stdout, stderr.
[ "Sends", "data", "via", "stdin", "and", "reads", "data", "from", "stdout", "stderr", "." ]
[ "'''\n Sends data via stdin and reads data from stdout, stderr.\n This will likely block if the process is still alive.\n When `inpt` is `None`, stdin is immediately closed.\n When `timeout` is `None`, this waits indefinitely for the process to\n terminate. Otherwise, it is interp...
[ { "param": "self", "type": null }, { "param": "inpt", "type": null }, { "param": "timeout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "inpt", "type": null, "docstring": null, "docstring_tokens": [...
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
wait
<not_specific>
def wait(self, timeout=10): ''' Waits `timeout` seconds for the process to finish. ''' if not self.alive(): logger.debug('process not alive, nothing to wait for') return assert self._handle is not None, '[internal] process handle is null' try: self._...
Waits `timeout` seconds for the process to finish.
Waits `timeout` seconds for the process to finish.
[ "Waits", "`", "timeout", "`", "seconds", "for", "the", "process", "to", "finish", "." ]
def wait(self, timeout=10): if not self.alive(): logger.debug('process not alive, nothing to wait for') return assert self._handle is not None, '[internal] process handle is null' try: self._handle.wait(timeout=timeout) except subprocess.TimeoutExpired...
[ "def", "wait", "(", "self", ",", "timeout", "=", "10", ")", ":", "if", "not", "self", ".", "alive", "(", ")", ":", "logger", ".", "debug", "(", "'process not alive, nothing to wait for'", ")", "return", "assert", "self", ".", "_handle", "is", "not", "Non...
Waits `timeout` seconds for the process to finish.
[ "Waits", "`", "timeout", "`", "seconds", "for", "the", "process", "to", "finish", "." ]
[ "''' Waits `timeout` seconds for the process to finish. '''", "# re-raise as `TimeoutError` to keep things consistent" ]
[ { "param": "self", "type": null }, { "param": "timeout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "timeout", "type": null, "docstring": null, "docstring_tokens"...
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
kill
<not_specific>
def kill(self): ''' Kills the associated process by sending a signal. ''' if not self.alive(): logger.debug('process is already dead, not sending signal') return assert self._handle is not None, '[internal] process handle is null' self._handle.kill()
Kills the associated process by sending a signal.
Kills the associated process by sending a signal.
[ "Kills", "the", "associated", "process", "by", "sending", "a", "signal", "." ]
def kill(self): if not self.alive(): logger.debug('process is already dead, not sending signal') return assert self._handle is not None, '[internal] process handle is null' self._handle.kill()
[ "def", "kill", "(", "self", ")", ":", "if", "not", "self", ".", "alive", "(", ")", ":", "logger", ".", "debug", "(", "'process is already dead, not sending signal'", ")", "return", "assert", "self", ".", "_handle", "is", "not", "None", ",", "'[internal] proc...
Kills the associated process by sending a signal.
[ "Kills", "the", "associated", "process", "by", "sending", "a", "signal", "." ]
[ "''' Kills the associated process by sending a signal. '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
4eead4439c9bd286d8ce4faf08ccdb99179acdd6
mrmansano/sublime-ycmd
lib/process/process.py
[ "MIT" ]
Python
pid
<not_specific>
def pid(self): ''' Returns the process ID if running, or `None` otherwise. ''' if not self.alive(): logger.debug('process not alive, no pid') return None return self._handle.pid
Returns the process ID if running, or `None` otherwise.
Returns the process ID if running, or `None` otherwise.
[ "Returns", "the", "process", "ID", "if", "running", "or", "`", "None", "`", "otherwise", "." ]
def pid(self): if not self.alive(): logger.debug('process not alive, no pid') return None return self._handle.pid
[ "def", "pid", "(", "self", ")", ":", "if", "not", "self", ".", "alive", "(", ")", ":", "logger", ".", "debug", "(", "'process not alive, no pid'", ")", "return", "None", "return", "self", ".", "_handle", ".", "pid" ]
Returns the process ID if running, or `None` otherwise.
[ "Returns", "the", "process", "ID", "if", "running", "or", "`", "None", "`", "otherwise", "." ]
[ "''' Returns the process ID if running, or `None` otherwise. '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
9d3f25c73cc592c4f53ec33f45e930a59cd92865
mrmansano/sublime-ycmd
lib/util/lock.py
[ "MIT" ]
Python
lock_guard
<not_specific>
def lock_guard(lock=None): ''' Locking decorator. Calls the decorated function with the `lock` held, and releases when done. If `lock` is omitted, and a class method is passed in, the decorated method will attempt to use the instance-specific `self._lock` variable. If the instance has no lock,...
Locking decorator. Calls the decorated function with the `lock` held, and releases when done. If `lock` is omitted, and a class method is passed in, the decorated method will attempt to use the instance-specific `self._lock` variable. If the instance has no lock, or if a static function is decora...
Locking decorator. Calls the decorated function with the `lock` held, and releases when done. If `lock` is omitted, and a class method is passed in, the decorated method will attempt to use the instance-specific `self._lock` variable. If the instance has no lock, or if a static function is decorated, a unique `threadi...
[ "Locking", "decorator", ".", "Calls", "the", "decorated", "function", "with", "the", "`", "lock", "`", "held", "and", "releases", "when", "done", ".", "If", "`", "lock", "`", "is", "omitted", "and", "a", "class", "method", "is", "passed", "in", "the", ...
def lock_guard(lock=None): _lock = lock if lock is not None else threading.RLock() if not hasattr(_lock, '__enter__') or not hasattr(_lock, '__exit__'): raise TypeError('lock must support context management: %r' % (_lock)) def lock_guard_function(fn): if hasattr(fn, '__self__'): ...
[ "def", "lock_guard", "(", "lock", "=", "None", ")", ":", "_lock", "=", "lock", "if", "lock", "is", "not", "None", "else", "threading", ".", "RLock", "(", ")", "if", "not", "hasattr", "(", "_lock", ",", "'__enter__'", ")", "or", "not", "hasattr", "(",...
Locking decorator.
[ "Locking", "decorator", "." ]
[ "'''\n Locking decorator.\n\n Calls the decorated function with the `lock` held, and releases when done.\n\n If `lock` is omitted, and a class method is passed in, the decorated method\n will attempt to use the instance-specific `self._lock` variable. If the\n instance has no lock, or if a static fun...
[ { "param": "lock", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "lock", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e794ec0a4b84110bf4cfe442ef69d62eb12a32aa
mrmansano/sublime-ycmd
lib/task/worker.py
[ "MIT" ]
Python
run
null
def run(self): ''' Starts the worker thread, running an infinite loop waiting for jobs. This should be run on an alternate thread, as it will block. ''' task_queue = self.pool.queue # type: queue.Queue logger.debug('task worker starting: %r', self) while True...
Starts the worker thread, running an infinite loop waiting for jobs. This should be run on an alternate thread, as it will block.
Starts the worker thread, running an infinite loop waiting for jobs. This should be run on an alternate thread, as it will block.
[ "Starts", "the", "worker", "thread", "running", "an", "infinite", "loop", "waiting", "for", "jobs", ".", "This", "should", "be", "run", "on", "an", "alternate", "thread", "as", "it", "will", "block", "." ]
def run(self): task_queue = self.pool.queue logger.debug('task worker starting: %r', self) while True: task = task_queue.get(block=True) if task is not None: try: task.run() except Exception as e: ...
[ "def", "run", "(", "self", ")", ":", "task_queue", "=", "self", ".", "pool", ".", "queue", "logger", ".", "debug", "(", "'task worker starting: %r'", ",", "self", ")", "while", "True", ":", "task", "=", "task_queue", ".", "get", "(", "block", "=", "Tru...
Starts the worker thread, running an infinite loop waiting for jobs.
[ "Starts", "the", "worker", "thread", "running", "an", "infinite", "loop", "waiting", "for", "jobs", "." ]
[ "'''\n Starts the worker thread, running an infinite loop waiting for jobs.\n\n This should be run on an alternate thread, as it will block.\n '''", "# type: queue.Queue", "# explicitly specify `block`, in case the queue has custom settings", "# type: Task", "# NOTE : Tasks should catch...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e794ec0a4b84110bf4cfe442ef69d62eb12a32aa
mrmansano/sublime-ycmd
lib/task/worker.py
[ "MIT" ]
Python
join
<not_specific>
def join(self, timeout=None): ''' Joins the underlying thread for this worker. If `timeout` is omitted, this will block indefinitely until the thread has exited. If `timeout` is provided, it should be the maximum number of seconds to wait until returning. If the thread i...
Joins the underlying thread for this worker. If `timeout` is omitted, this will block indefinitely until the thread has exited. If `timeout` is provided, it should be the maximum number of seconds to wait until returning. If the thread is still alive after the timeout e...
Joins the underlying thread for this worker. If `timeout` is omitted, this will block indefinitely until the thread has exited. If `timeout` is provided, it should be the maximum number of seconds to wait until returning. If the thread is still alive after the timeout expires, a `TimeoutError` will be raised.
[ "Joins", "the", "underlying", "thread", "for", "this", "worker", ".", "If", "`", "timeout", "`", "is", "omitted", "this", "will", "block", "indefinitely", "until", "the", "thread", "has", "exited", ".", "If", "`", "timeout", "`", "is", "provided", "it", ...
def join(self, timeout=None): handle = self._handle if not handle: return handle.join(timeout=timeout) if handle.is_alive(): timeout_desc = ( ' after %rs' % (timeout) if timeout is not None else '' ) raise TimeoutErro...
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "handle", "=", "self", ".", "_handle", "if", "not", "handle", ":", "return", "handle", ".", "join", "(", "timeout", "=", "timeout", ")", "if", "handle", ".", "is_alive", "(", ")", "...
Joins the underlying thread for this worker.
[ "Joins", "the", "underlying", "thread", "for", "this", "worker", "." ]
[ "'''\n Joins the underlying thread for this worker.\n\n If `timeout` is omitted, this will block indefinitely until the thread\n has exited.\n If `timeout` is provided, it should be the maximum number of seconds to\n wait until returning. If the thread is still alive after the tim...
[ { "param": "self", "type": null }, { "param": "timeout", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "timeout", "type": null, "docstring": null, "docstring_tokens"...
e794ec0a4b84110bf4cfe442ef69d62eb12a32aa
mrmansano/sublime-ycmd
lib/task/worker.py
[ "MIT" ]
Python
clear
null
def clear(self): ''' Clears the locally held reference to the task pool and thread handle. ''' self._pool = None self._handle = None
Clears the locally held reference to the task pool and thread handle.
Clears the locally held reference to the task pool and thread handle.
[ "Clears", "the", "locally", "held", "reference", "to", "the", "task", "pool", "and", "thread", "handle", "." ]
def clear(self): self._pool = None self._handle = None
[ "def", "clear", "(", "self", ")", ":", "self", ".", "_pool", "=", "None", "self", ".", "_handle", "=", "None" ]
Clears the locally held reference to the task pool and thread handle.
[ "Clears", "the", "locally", "held", "reference", "to", "the", "task", "pool", "and", "thread", "handle", "." ]
[ "'''\n Clears the locally held reference to the task pool and thread handle.\n '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e794ec0a4b84110bf4cfe442ef69d62eb12a32aa
mrmansano/sublime-ycmd
lib/task/worker.py
[ "MIT" ]
Python
handle
<not_specific>
def handle(self, handle): ''' Sets the thread handle for the worker. ''' if handle is None: # clear state self._handle = None return if handle is not None and not isinstance(handle, threading.Thread): raise TypeError( ...
Sets the thread handle for the worker.
Sets the thread handle for the worker.
[ "Sets", "the", "thread", "handle", "for", "the", "worker", "." ]
def handle(self, handle): if handle is None: self._handle = None return if handle is not None and not isinstance(handle, threading.Thread): raise TypeError( 'thread handle must be a threading.Thread: %r' % (handle) ) self._handle = ...
[ "def", "handle", "(", "self", ",", "handle", ")", ":", "if", "handle", "is", "None", ":", "self", ".", "_handle", "=", "None", "return", "if", "handle", "is", "not", "None", "and", "not", "isinstance", "(", "handle", ",", "threading", ".", "Thread", ...
Sets the thread handle for the worker.
[ "Sets", "the", "thread", "handle", "for", "the", "worker", "." ]
[ "'''\n Sets the thread handle for the worker.\n '''", "# clear state" ]
[ { "param": "self", "type": null }, { "param": "handle", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "handle", "type": null, "docstring": null, "docstring_tokens":...
e794ec0a4b84110bf4cfe442ef69d62eb12a32aa
mrmansano/sublime-ycmd
lib/task/worker.py
[ "MIT" ]
Python
name
<not_specific>
def name(self): ''' Retrieves the name from the thread handle, if available. ''' if self._handle: return self._handle.name return None
Retrieves the name from the thread handle, if available.
Retrieves the name from the thread handle, if available.
[ "Retrieves", "the", "name", "from", "the", "thread", "handle", "if", "available", "." ]
def name(self): if self._handle: return self._handle.name return None
[ "def", "name", "(", "self", ")", ":", "if", "self", ".", "_handle", ":", "return", "self", ".", "_handle", ".", "name", "return", "None" ]
Retrieves the name from the thread handle, if available.
[ "Retrieves", "the", "name", "from", "the", "thread", "handle", "if", "available", "." ]
[ "'''\n Retrieves the name from the thread handle, if available.\n '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
e794ec0a4b84110bf4cfe442ef69d62eb12a32aa
mrmansano/sublime-ycmd
lib/task/worker.py
[ "MIT" ]
Python
name
null
def name(self, name): ''' Sets the name of the held thread handle. ''' if self._handle: self._handle.name = name # else, meh, whatever
Sets the name of the held thread handle.
Sets the name of the held thread handle.
[ "Sets", "the", "name", "of", "the", "held", "thread", "handle", "." ]
def name(self, name): if self._handle: self._handle.name = name
[ "def", "name", "(", "self", ",", "name", ")", ":", "if", "self", ".", "_handle", ":", "self", ".", "_handle", ".", "name", "=", "name" ]
Sets the name of the held thread handle.
[ "Sets", "the", "name", "of", "the", "held", "thread", "handle", "." ]
[ "'''\n Sets the name of the held thread handle.\n '''", "# else, meh, whatever" ]
[ { "param": "self", "type": null }, { "param": "name", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "name", "type": null, "docstring": null, "docstring_tokens": [...
63577480697fc3dbcb79fc5de4d9a030c212fc13
mrmansano/sublime-ycmd
lib/subl/settings.py
[ "MIT" ]
Python
parse
null
def parse(self, settings): ''' Assigns the contents of `settings` to the internal instance variables. The settings may be provided as a `dict` or as a `sublime.Settings` instance. The accepted settings are listed in the default settings file. They are extracted by this m...
Assigns the contents of `settings` to the internal instance variables. The settings may be provided as a `dict` or as a `sublime.Settings` instance. The accepted settings are listed in the default settings file. They are extracted by this method, if available, or given reasonab...
Assigns the contents of `settings` to the internal instance variables. The settings may be provided as a `dict` or as a `sublime.Settings` instance. The accepted settings are listed in the default settings file. They are extracted by this method, if available, or given reasonable defaults. After parsing, the settings...
[ "Assigns", "the", "contents", "of", "`", "settings", "`", "to", "the", "internal", "instance", "variables", ".", "The", "settings", "may", "be", "provided", "as", "a", "`", "dict", "`", "or", "as", "a", "`", "sublime", ".", "Settings", "`", "instance", ...
def parse(self, settings): if not isinstance(settings, (sublime.Settings, dict)): raise TypeError( 'settings must be sublime.Settings or dict: %r' % settings ) self._ycmd_root_directory = settings.get('ycmd_root_directory', None) self._ycmd_default_setting...
[ "def", "parse", "(", "self", ",", "settings", ")", ":", "if", "not", "isinstance", "(", "settings", ",", "(", "sublime", ".", "Settings", ",", "dict", ")", ")", ":", "raise", "TypeError", "(", "'settings must be sublime.Settings or dict: %r'", "%", "settings",...
Assigns the contents of `settings` to the internal instance variables.
[ "Assigns", "the", "contents", "of", "`", "settings", "`", "to", "the", "internal", "instance", "variables", "." ]
[ "'''\n Assigns the contents of `settings` to the internal instance variables.\n The settings may be provided as a `dict` or as a `sublime.Settings`\n instance.\n\n The accepted settings are listed in the default settings file. They are\n extracted by this method, if available, or ...
[ { "param": "self", "type": null }, { "param": "settings", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null }, { "identifier": "settings", "type": null, "docstring": null, "docstring_tokens...
63577480697fc3dbcb79fc5de4d9a030c212fc13
mrmansano/sublime-ycmd
lib/subl/settings.py
[ "MIT" ]
Python
_normalize
null
def _normalize(self): ''' Calculates and updates any values that haven't been set after parsing settings provided to the `parse` method. This will calculate things like the default settings path based on the ycmd root directory, or the python binary based on the system PATH. ...
Calculates and updates any values that haven't been set after parsing settings provided to the `parse` method. This will calculate things like the default settings path based on the ycmd root directory, or the python binary based on the system PATH.
Calculates and updates any values that haven't been set after parsing settings provided to the `parse` method. This will calculate things like the default settings path based on the ycmd root directory, or the python binary based on the system PATH.
[ "Calculates", "and", "updates", "any", "values", "that", "haven", "'", "t", "been", "set", "after", "parsing", "settings", "provided", "to", "the", "`", "parse", "`", "method", ".", "This", "will", "calculate", "things", "like", "the", "default", "settings",...
def _normalize(self): if self._ycmd_root_directory: resolved_ycmd_root_directory = \ resolve_abspath(self._ycmd_root_directory) if resolved_ycmd_root_directory != self._ycmd_root_directory: logger.debug( 'resolved ycmd root directory: %...
[ "def", "_normalize", "(", "self", ")", ":", "if", "self", ".", "_ycmd_root_directory", ":", "resolved_ycmd_root_directory", "=", "resolve_abspath", "(", "self", ".", "_ycmd_root_directory", ")", "if", "resolved_ycmd_root_directory", "!=", "self", ".", "_ycmd_root_dire...
Calculates and updates any values that haven't been set after parsing settings provided to the `parse` method.
[ "Calculates", "and", "updates", "any", "values", "that", "haven", "'", "t", "been", "set", "after", "parsing", "settings", "provided", "to", "the", "`", "parse", "`", "method", "." ]
[ "'''\n Calculates and updates any values that haven't been set after parsing\n settings provided to the `parse` method.\n This will calculate things like the default settings path based on the\n ycmd root directory, or the python binary based on the system PATH.\n '''", "# assum...
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
63577480697fc3dbcb79fc5de4d9a030c212fc13
mrmansano/sublime-ycmd
lib/subl/settings.py
[ "MIT" ]
Python
ycmd_root_directory
<not_specific>
def ycmd_root_directory(self): ''' Returns the path to the ycmd root directory. If set, this will be a string. If unset, this will be `None`. ''' return self._ycmd_root_directory
Returns the path to the ycmd root directory. If set, this will be a string. If unset, this will be `None`.
Returns the path to the ycmd root directory. If set, this will be a string. If unset, this will be `None`.
[ "Returns", "the", "path", "to", "the", "ycmd", "root", "directory", ".", "If", "set", "this", "will", "be", "a", "string", ".", "If", "unset", "this", "will", "be", "`", "None", "`", "." ]
def ycmd_root_directory(self): return self._ycmd_root_directory
[ "def", "ycmd_root_directory", "(", "self", ")", ":", "return", "self", ".", "_ycmd_root_directory" ]
Returns the path to the ycmd root directory.
[ "Returns", "the", "path", "to", "the", "ycmd", "root", "directory", "." ]
[ "'''\n Returns the path to the ycmd root directory.\n If set, this will be a string. If unset, this will be `None`.\n '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }
63577480697fc3dbcb79fc5de4d9a030c212fc13
mrmansano/sublime-ycmd
lib/subl/settings.py
[ "MIT" ]
Python
ycmd_default_settings_path
<not_specific>
def ycmd_default_settings_path(self): ''' Returns the path to the ycmd default settings file. If set, this will be a string. If unset, it is calculated based on the ycmd root directory. If that fails, this will be `None`. ''' return self._ycmd_default_settings_path
Returns the path to the ycmd default settings file. If set, this will be a string. If unset, it is calculated based on the ycmd root directory. If that fails, this will be `None`.
Returns the path to the ycmd default settings file. If set, this will be a string. If unset, it is calculated based on the ycmd root directory. If that fails, this will be `None`.
[ "Returns", "the", "path", "to", "the", "ycmd", "default", "settings", "file", ".", "If", "set", "this", "will", "be", "a", "string", ".", "If", "unset", "it", "is", "calculated", "based", "on", "the", "ycmd", "root", "directory", ".", "If", "that", "fa...
def ycmd_default_settings_path(self): return self._ycmd_default_settings_path
[ "def", "ycmd_default_settings_path", "(", "self", ")", ":", "return", "self", ".", "_ycmd_default_settings_path" ]
Returns the path to the ycmd default settings file.
[ "Returns", "the", "path", "to", "the", "ycmd", "default", "settings", "file", "." ]
[ "'''\n Returns the path to the ycmd default settings file.\n If set, this will be a string. If unset, it is calculated based on the\n ycmd root directory. If that fails, this will be `None`.\n '''" ]
[ { "param": "self", "type": null } ]
{ "returns": [], "raises": [], "params": [ { "identifier": "self", "type": null, "docstring": null, "docstring_tokens": [], "default": null, "is_optional": null } ], "outlier_params": [], "others": [] }