id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
28,600
tensorflow/cleverhans
cleverhans/attacks/bapp.py
initialize
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = np.random.uniform(clip_min, clip_max, size=shape) success = dec...
python
def initialize(decision_function, sample, shape, clip_min, clip_max): """ Efficient Implementation of BlendedUniformNoiseAttack in Foolbox. """ success = 0 num_evals = 0 # Find a misclassified random noise. while True: random_noise = np.random.uniform(clip_min, clip_max, size=shape) success = dec...
[ "def", "initialize", "(", "decision_function", ",", "sample", ",", "shape", ",", "clip_min", ",", "clip_max", ")", ":", "success", "=", "0", "num_evals", "=", "0", "# Find a misclassified random noise.", "while", "True", ":", "random_noise", "=", "np", ".", "r...
Efficient Implementation of BlendedUniformNoiseAttack in Foolbox.
[ "Efficient", "Implementation", "of", "BlendedUniformNoiseAttack", "in", "Foolbox", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L471-L501
28,601
tensorflow/cleverhans
cleverhans/attacks/bapp.py
geometric_progression_for_stepsize
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current...
python
def geometric_progression_for_stepsize(x, update, dist, decision_function, current_iteration): """ Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary. """ epsilon = dist / np.sqrt(current...
[ "def", "geometric_progression_for_stepsize", "(", "x", ",", "update", ",", "dist", ",", "decision_function", ",", "current_iteration", ")", ":", "epsilon", "=", "dist", "/", "np", ".", "sqrt", "(", "current_iteration", ")", "while", "True", ":", "updated", "="...
Geometric progression to search for stepsize. Keep decreasing stepsize by half until reaching the desired side of the boundary.
[ "Geometric", "progression", "to", "search", "for", "stepsize", ".", "Keep", "decreasing", "stepsize", "by", "half", "until", "reaching", "the", "desired", "side", "of", "the", "boundary", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L504-L519
28,602
tensorflow/cleverhans
cleverhans/attacks/bapp.py
select_delta
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta...
python
def select_delta(dist_post_update, current_iteration, clip_max, clip_min, d, theta, constraint): """ Choose the delta at the scale of distance between x and perturbed sample. """ if current_iteration == 1: delta = 0.1 * (clip_max - clip_min) else: if constraint == 'l2': delta...
[ "def", "select_delta", "(", "dist_post_update", ",", "current_iteration", ",", "clip_max", ",", "clip_min", ",", "d", ",", "theta", ",", "constraint", ")", ":", "if", "current_iteration", "==", "1", ":", "delta", "=", "0.1", "*", "(", "clip_max", "-", "cli...
Choose the delta at the scale of distance between x and perturbed sample.
[ "Choose", "the", "delta", "at", "the", "scale", "of", "distance", "between", "x", "and", "perturbed", "sample", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/bapp.py#L522-L536
28,603
tensorflow/cleverhans
cleverhans/attacks/fast_feature_adversaries.py
FastFeatureAdversaries.attack_single_step
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the...
python
def attack_single_step(self, x, eta, g_feat): """ TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the...
[ "def", "attack_single_step", "(", "self", ",", "x", ",", "eta", ",", "g_feat", ")", ":", "adv_x", "=", "x", "+", "eta", "a_feat", "=", "self", ".", "model", ".", "fprop", "(", "adv_x", ")", "[", "self", ".", "layer", "]", "# feat.shape = (batch, c) or ...
TensorFlow implementation of the Fast Feature Gradient. This is a single step attack similar to Fast Gradient Method that attacks an internal representation. :param x: the input placeholder :param eta: A tensor the same shape as x that holds the perturbation. :param g_feat: model's internal tensor ...
[ "TensorFlow", "implementation", "of", "the", "Fast", "Feature", "Gradient", ".", "This", "is", "a", "single", "step", "attack", "similar", "to", "Fast", "Gradient", "Method", "that", "attacks", "an", "internal", "representation", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_feature_adversaries.py#L88-L129
28,604
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
block35
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_...
python
def block35(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 35x35 resnet block.""" with tf.variable_scope(scope, 'Block35', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 32, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch_...
[ "def", "block35", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'Block35'", ",...
Builds the 35x35 resnet block.
[ "Builds", "the", "35x35", "resnet", "block", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L35-L54
28,605
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
block17
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch...
python
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None): """Builds the 17x17 resnet block.""" with tf.variable_scope(scope, 'Block17', [net], reuse=reuse): with tf.variable_scope('Branch_0'): tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1') with tf.variable_scope('Branch...
[ "def", "block17", "(", "net", ",", "scale", "=", "1.0", ",", "activation_fn", "=", "tf", ".", "nn", ".", "relu", ",", "scope", "=", "None", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ",", "'Block17'", ",...
Builds the 17x17 resnet block.
[ "Builds", "the", "17x17", "resnet", "block", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L57-L74
28,606
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
inception_resnet_v2
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_classes=None): """Creates the Inception R...
python
def inception_resnet_v2(inputs, nb_classes=1001, is_training=True, dropout_keep_prob=0.8, reuse=None, scope='InceptionResnetV2', create_aux_logits=True, num_classes=None): """Creates the Inception R...
[ "def", "inception_resnet_v2", "(", "inputs", ",", "nb_classes", "=", "1001", ",", "is_training", "=", "True", ",", "dropout_keep_prob", "=", "0.8", ",", "reuse", "=", "None", ",", "scope", "=", "'InceptionResnetV2'", ",", "create_aux_logits", "=", "True", ",",...
Creates the Inception Resnet V2 model. Args: inputs: a 4-D tensor of size [batch_size, height, width, 3]. nb_classes: number of predicted classes. is_training: whether is training or not. dropout_keep_prob: float, the fraction to keep before final layer. reuse: whether or not the network and its ...
[ "Creates", "the", "Inception", "Resnet", "V2", "model", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L288-L352
28,607
tensorflow/cleverhans
examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py
inception_resnet_v2_arg_scope
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. ...
python
def inception_resnet_v2_arg_scope(weight_decay=0.00004, batch_norm_decay=0.9997, batch_norm_epsilon=0.001): """Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. ...
[ "def", "inception_resnet_v2_arg_scope", "(", "weight_decay", "=", "0.00004", ",", "batch_norm_decay", "=", "0.9997", ",", "batch_norm_epsilon", "=", "0.001", ")", ":", "# Set weight_decay for weights in conv2d and fully_connected layers.", "with", "slim", ".", "arg_scope", ...
Returns the scope with the default parameters for inception_resnet_v2. Args: weight_decay: the weight decay for weights variables. batch_norm_decay: decay for the moving average of batch_norm momentums. batch_norm_epsilon: small float added to variance to avoid dividing by zero. Returns: a arg_sco...
[ "Returns", "the", "scope", "with", "the", "default", "parameters", "for", "inception_resnet_v2", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dev_toolkit/sample_defenses/ens_adv_inception_resnet_v2/inception_resnet_v2.py#L358-L384
28,608
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
main
def main(args): """Validate all submissions and copy them into place""" random.seed() temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) validator = SubmissionValidator( source_dir=args.source_dir, target_dir=args.target_dir, temp_dir=temp_dir, do_c...
python
def main(args): """Validate all submissions and copy them into place""" random.seed() temp_dir = tempfile.mkdtemp() logging.info('Created temporary directory: %s', temp_dir) validator = SubmissionValidator( source_dir=args.source_dir, target_dir=args.target_dir, temp_dir=temp_dir, do_c...
[ "def", "main", "(", "args", ")", ":", "random", ".", "seed", "(", ")", "temp_dir", "=", "tempfile", ".", "mkdtemp", "(", ")", "logging", ".", "info", "(", "'Created temporary directory: %s'", ",", "temp_dir", ")", "validator", "=", "SubmissionValidator", "("...
Validate all submissions and copy them into place
[ "Validate", "all", "submissions", "and", "copy", "them", "into", "place" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L229-L243
28,609
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
ValidationStats._update_stat
def _update_stat(self, submission_type, increase_success, increase_fail): """Common method to update submission statistics.""" stat = self.stats.get(submission_type, (0, 0)) stat = (stat[0] + increase_success, stat[1] + increase_fail) self.stats[submission_type] = stat
python
def _update_stat(self, submission_type, increase_success, increase_fail): """Common method to update submission statistics.""" stat = self.stats.get(submission_type, (0, 0)) stat = (stat[0] + increase_success, stat[1] + increase_fail) self.stats[submission_type] = stat
[ "def", "_update_stat", "(", "self", ",", "submission_type", ",", "increase_success", ",", "increase_fail", ")", ":", "stat", "=", "self", ".", "stats", ".", "get", "(", "submission_type", ",", "(", "0", ",", "0", ")", ")", "stat", "=", "(", "stat", "["...
Common method to update submission statistics.
[ "Common", "method", "to", "update", "submission", "statistics", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L64-L68
28,610
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
ValidationStats.log_stats
def log_stats(self): """Print statistics into log.""" logging.info('Validation statistics: ') for k, v in iteritems(self.stats): logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1])
python
def log_stats(self): """Print statistics into log.""" logging.info('Validation statistics: ') for k, v in iteritems(self.stats): logging.info('%s - %d valid out of %d total submissions', k, v[0], v[0] + v[1])
[ "def", "log_stats", "(", "self", ")", ":", "logging", ".", "info", "(", "'Validation statistics: '", ")", "for", "k", ",", "v", "in", "iteritems", "(", "self", ".", "stats", ")", ":", "logging", ".", "info", "(", "'%s - %d valid out of %d total submissions'", ...
Print statistics into log.
[ "Print", "statistics", "into", "log", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L78-L83
28,611
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.copy_submission_locally
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_d...
python
def copy_submission_locally(self, cloud_path): """Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to """ local_path = os.path.join(self.download_d...
[ "def", "copy_submission_locally", "(", "self", ",", "cloud_path", ")", ":", "local_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "download_dir", ",", "os", ".", "path", ".", "basename", "(", "cloud_path", ")", ")", "cmd", "=", "[", "'gs...
Copies submission from Google Cloud Storage to local directory. Args: cloud_path: path of the submission in Google Cloud Storage Returns: name of the local file where submission is copied to
[ "Copies", "submission", "from", "Google", "Cloud", "Storage", "to", "local", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L119-L133
28,612
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.copy_submission_to_destination
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be...
python
def copy_submission_to_destination(self, src_filename, dst_subdir, submission_id): """Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be...
[ "def", "copy_submission_to_destination", "(", "self", ",", "src_filename", ",", "dst_subdir", ",", "submission_id", ")", ":", "extension", "=", "[", "e", "for", "e", "in", "ALLOWED_EXTENSIONS", "if", "src_filename", ".", "endswith", "(", "e", ")", "]", "if", ...
Copies submission to target directory. Args: src_filename: source filename of the submission dst_subdir: subdirectory of the target directory where submission should be copied to submission_id: ID of the submission, will be used as a new submission filename (before extension)
[ "Copies", "submission", "to", "target", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L135-L157
28,613
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.validate_and_copy_one_submission
def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file """ if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(s...
python
def validate_and_copy_one_submission(self, submission_path): """Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file """ if os.path.exists(self.download_dir): shutil.rmtree(self.download_dir) os.makedirs(s...
[ "def", "validate_and_copy_one_submission", "(", "self", ",", "submission_path", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "download_dir", ")", ":", "shutil", ".", "rmtree", "(", "self", ".", "download_dir", ")", "os", ".", "makedi...
Validates one submission and copies it to target directory. Args: submission_path: path in Google Cloud Storage of the submission file
[ "Validates", "one", "submission", "and", "copies", "it", "to", "target", "directory", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L159-L190
28,614
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.save_id_to_path_mapping
def save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """ if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer...
python
def save_id_to_path_mapping(self): """Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory. """ if not self.id_to_path_mapping: return with open(self.local_id_to_path_mapping_file, 'w') as f: writer = csv.writer(f) writer...
[ "def", "save_id_to_path_mapping", "(", "self", ")", ":", "if", "not", "self", ".", "id_to_path_mapping", ":", "return", "with", "open", "(", "self", ".", "local_id_to_path_mapping_file", ",", "'w'", ")", "as", "f", ":", "writer", "=", "csv", ".", "writer", ...
Saves mapping from submission IDs to original filenames. This mapping is saved as CSV file into target directory.
[ "Saves", "mapping", "from", "submission", "IDs", "to", "original", "filenames", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L192-L207
28,615
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py
SubmissionValidator.run
def run(self): """Runs validation of all submissions.""" cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ ...
python
def run(self): """Runs validation of all submissions.""" cmd = ['gsutil', 'ls', os.path.join(self.source_dir, '**')] try: files_list = subprocess.check_output(cmd).split('\n') except subprocess.CalledProcessError: logging.error('Can''t read source directory') all_submissions = [ ...
[ "def", "run", "(", "self", ")", ":", "cmd", "=", "[", "'gsutil'", ",", "'ls'", ",", "os", ".", "path", ".", "join", "(", "self", ".", "source_dir", ",", "'**'", ")", "]", "try", ":", "files_list", "=", "subprocess", ".", "check_output", "(", "cmd",...
Runs validation of all submissions.
[ "Runs", "validation", "of", "all", "submissions", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/validation_tool/validate_and_copy_submissions.py#L209-L226
28,616
tensorflow/cleverhans
scripts/plot_success_fail_curve.py
main
def main(argv=None): """Takes the path to a directory with reports and renders success fail plots.""" report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.x...
python
def main(argv=None): """Takes the path to a directory with reports and renders success fail plots.""" report_paths = argv[1:] fail_names = FLAGS.fail_names.split(',') for report_path in report_paths: plot_report_from_path(report_path, label=report_path, fail_names=fail_names) pyplot.legend() pyplot.x...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "report_paths", "=", "argv", "[", "1", ":", "]", "fail_names", "=", "FLAGS", ".", "fail_names", ".", "split", "(", "','", ")", "for", "report_path", "in", "report_paths", ":", "plot_report_from_path", "(...
Takes the path to a directory with reports and renders success fail plots.
[ "Takes", "the", "path", "to", "a", "directory", "with", "reports", "and", "renders", "success", "fail", "plots", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/scripts/plot_success_fail_curve.py#L25-L38
28,617
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
is_unclaimed
def is_unclaimed(work): """Returns True if work piece is unclaimed.""" if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): ...
python
def is_unclaimed(work): """Returns True if work piece is unclaimed.""" if work['is_completed']: return False cutoff_time = time.time() - MAX_PROCESSING_TIME if (work['claimed_worker_id'] and work['claimed_worker_start_time'] is not None and work['claimed_worker_start_time'] >= cutoff_time): ...
[ "def", "is_unclaimed", "(", "work", ")", ":", "if", "work", "[", "'is_completed'", "]", ":", "return", "False", "cutoff_time", "=", "time", ".", "time", "(", ")", "-", "MAX_PROCESSING_TIME", "if", "(", "work", "[", "'claimed_worker_id'", "]", "and", "work"...
Returns True if work piece is unclaimed.
[ "Returns", "True", "if", "work", "piece", "is", "unclaimed", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L46-L55
28,618
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.write_all_to_datastore
def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains ...
python
def write_all_to_datastore(self): """Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains ...
[ "def", "write_all_to_datastore", "(", "self", ")", ":", "client", "=", "self", ".", "_datastore_client", "with", "client", ".", "no_transact_batch", "(", ")", "as", "batch", ":", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", "....
Writes all work pieces into datastore. Each work piece is identified by ID. This method writes/updates only those work pieces which IDs are stored in this class. For examples, if this class has only work pieces with IDs '1' ... '100' and datastore already contains work pieces with IDs '50' ... '200' t...
[ "Writes", "all", "work", "pieces", "into", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L150-L168
28,619
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.read_all_from_datastore
def read_all_from_datastore(self): """Reads all work pieces from the datastore.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat...
python
def read_all_from_datastore(self): """Reads all work pieces from the datastore.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) for entity in client.query_fetch(kind=KIND_WORK, ancestor=parent_key): work_id = entity.key.flat...
[ "def", "read_all_from_datastore", "(", "self", ")", ":", "self", ".", "_work", "=", "{", "}", "client", "=", "self", ".", "_datastore_client", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self", ".", "_work_type_entity_id", ")", "for...
Reads all work pieces from the datastore.
[ "Reads", "all", "work", "pieces", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L170-L177
28,620
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase._read_undone_shard_from_datastore
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if sh...
python
def _read_undone_shard_from_datastore(self, shard_id=None): """Reads undone worke pieces which are assigned to shard with given id.""" self._work = {} client = self._datastore_client parent_key = client.key(KIND_WORK_TYPE, self._work_type_entity_id) filters = [('is_completed', '=', False)] if sh...
[ "def", "_read_undone_shard_from_datastore", "(", "self", ",", "shard_id", "=", "None", ")", ":", "self", ".", "_work", "=", "{", "}", "client", "=", "self", ".", "_datastore_client", "parent_key", "=", "client", ".", "key", "(", "KIND_WORK_TYPE", ",", "self"...
Reads undone worke pieces which are assigned to shard with given id.
[ "Reads", "undone", "worke", "pieces", "which", "are", "assigned", "to", "shard", "with", "given", "id", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L179-L192
28,621
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.read_undone_from_datastore
def read_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) a...
python
def read_undone_from_datastore(self, shard_id=None, num_shards=None): """Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) a...
[ "def", "read_undone_from_datastore", "(", "self", ",", "shard_id", "=", "None", ",", "num_shards", "=", "None", ")", ":", "if", "shard_id", "is", "not", "None", ":", "shards_list", "=", "[", "(", "i", "+", "shard_id", ")", "%", "num_shards", "for", "i", ...
Reads undone work from the datastore. If shard_id and num_shards are specified then this method will attempt to read undone work for shard with id shard_id. If no undone work was found then it will try to read shard (shard_id+1) and so on until either found shard with undone work or all shards are read...
[ "Reads", "undone", "work", "from", "the", "datastore", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L194-L219
28,622
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.try_pick_piece_of_work
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_...
python
def try_pick_piece_of_work(self, worker_id, submission_id=None): """Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_...
[ "def", "try_pick_piece_of_work", "(", "self", ",", "worker_id", ",", "submission_id", "=", "None", ")", ":", "client", "=", "self", ".", "_datastore_client", "unclaimed_work_ids", "=", "None", "if", "submission_id", ":", "unclaimed_work_ids", "=", "[", "k", "for...
Tries pick next unclaimed piece of work to do. Attempt to claim work piece is done using Cloud Datastore transaction, so only one worker can claim any work piece at a time. Args: worker_id: ID of current worker submission_id: if not None then this method will try to pick piece of work ...
[ "Tries", "pick", "next", "unclaimed", "piece", "of", "work", "to", "do", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L221-L261
28,623
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.update_work_as_completed
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with addi...
python
def update_work_as_completed(self, worker_id, work_id, other_values=None, error=None): """Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with addi...
[ "def", "update_work_as_completed", "(", "self", ",", "worker_id", ",", "work_id", ",", "other_values", "=", "None", ",", "error", "=", "None", ")", ":", "client", "=", "self", ".", "_datastore_client", "try", ":", "with", "client", ".", "transaction", "(", ...
Updates work piece in datastore as completed. Args: worker_id: ID of the worker which did the work work_id: ID of the work which was done other_values: dictionary with additonal values which should be saved with the work piece error: if not None then error occurred during computatio...
[ "Updates", "work", "piece", "in", "datastore", "as", "completed", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L263-L294
28,624
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
WorkPiecesBase.compute_work_statistics
def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class.""" result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_er...
python
def compute_work_statistics(self): """Computes statistics from all work pieces stored in this class.""" result = {} for v in itervalues(self.work): submission_id = v['submission_id'] if submission_id not in result: result[submission_id] = { 'completed': 0, 'num_er...
[ "def", "compute_work_statistics", "(", "self", ")", ":", "result", "=", "{", "}", "for", "v", "in", "itervalues", "(", "self", ".", "work", ")", ":", "submission_id", "=", "v", "[", "'submission_id'", "]", "if", "submission_id", "not", "in", "result", ":...
Computes statistics from all work pieces stored in this class.
[ "Computes", "statistics", "from", "all", "work", "pieces", "stored", "in", "this", "class", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L296-L326
28,625
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
AttackWorkPieces.init_from_adversarial_batches
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): w...
python
def init_from_adversarial_batches(self, adv_batches): """Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data """ for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)): w...
[ "def", "init_from_adversarial_batches", "(", "self", ",", "adv_batches", ")", ":", "for", "idx", ",", "(", "adv_batch_id", ",", "adv_batch_val", ")", "in", "enumerate", "(", "iteritems", "(", "adv_batches", ")", ")", ":", "work_id", "=", "ATTACK_WORK_ID_PATTERN"...
Initializes work pieces from adversarial batches. Args: adv_batches: dict with adversarial batches, could be obtained as AversarialBatches.data
[ "Initializes", "work", "pieces", "from", "adversarial", "batches", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L349-L367
28,626
tensorflow/cleverhans
examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py
DefenseWorkPieces.init_from_class_batches
def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None ...
python
def init_from_class_batches(self, class_batches, num_shards=None): """Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None ...
[ "def", "init_from_class_batches", "(", "self", ",", "class_batches", ",", "num_shards", "=", "None", ")", ":", "shards_for_submissions", "=", "{", "}", "shard_idx", "=", "0", "for", "idx", ",", "(", "batch_id", ",", "batch_val", ")", "in", "enumerate", "(", ...
Initializes work pieces from classification batches. Args: class_batches: dict with classification batches, could be obtained as ClassificationBatches.data num_shards: number of shards to split data into, if None then no sharding is done.
[ "Initializes", "work", "pieces", "from", "classification", "batches", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/eval_infra/code/eval_lib/work_data.py#L379-L411
28,627
tensorflow/cleverhans
cleverhans/attacks/fast_gradient_method.py
FastGradientMethod.generate
def generate(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.g...
python
def generate(self, x, **kwargs): """ Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params` """ # Parse and save attack-specific parameters assert self.parse_params(**kwargs) labels, _nb_classes = self.g...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "# Parse and save attack-specific parameters", "assert", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ",", "_nb_classes", "=", "self", ".", "get_or_guess_label...
Returns the graph for Fast Gradient Method adversarial examples. :param x: The model's symbolic inputs. :param kwargs: See `parse_params`
[ "Returns", "the", "graph", "for", "Fast", "Gradient", "Method", "adversarial", "examples", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/fast_gradient_method.py#L40-L61
28,628
tensorflow/cleverhans
cleverhans/experimental/certification/nn.py
load_network_from_checkpoint
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the netwo...
python
def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the netwo...
[ "def", "load_network_from_checkpoint", "(", "checkpoint", ",", "model_json", ",", "input_shape", "=", "None", ")", ":", "# Load checkpoint", "reader", "=", "tf", ".", "train", ".", "load_checkpoint", "(", "checkpoint", ")", "variable_map", "=", "reader", ".", "g...
Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of the network list of dictionary items for each layer containing 'type', 'weight_var...
[ "Function", "to", "read", "the", "weights", "from", "checkpoint", "based", "on", "json", "description", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/nn.py#L161-L226
28,629
tensorflow/cleverhans
cleverhans/experimental/certification/nn.py
NeuralNetwork.forward_pass
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer h...
python
def forward_pass(self, vector, layer_index, is_transpose=False, is_abs=False): """Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer h...
[ "def", "forward_pass", "(", "self", ",", "vector", ",", "layer_index", ",", "is_transpose", "=", "False", ",", "is_abs", "=", "False", ")", ":", "if", "(", "layer_index", "<", "0", "or", "layer_index", ">", "self", ".", "num_hidden_layers", ")", ":", "ra...
Performs forward pass through the layer weights at layer_index. Args: vector: vector that has to be passed through in forward pass layer_index: index of the layer is_transpose: whether the weights of the layer have to be transposed is_abs: whether to take the absolute value of the weights ...
[ "Performs", "forward", "pass", "through", "the", "layer", "weights", "at", "layer_index", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/nn.py#L111-L159
28,630
tensorflow/cleverhans
cleverhans/devtools/version.py
dev_version
def dev_version(): """ Returns a hexdigest of all the python files in the module. """ md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(conten...
python
def dev_version(): """ Returns a hexdigest of all the python files in the module. """ md5_hash = hashlib.md5() py_files = sorted(list_files(suffix=".py")) if not py_files: return '' for filename in py_files: with open(filename, 'rb') as fobj: content = fobj.read() md5_hash.update(conten...
[ "def", "dev_version", "(", ")", ":", "md5_hash", "=", "hashlib", ".", "md5", "(", ")", "py_files", "=", "sorted", "(", "list_files", "(", "suffix", "=", "\".py\"", ")", ")", "if", "not", "py_files", ":", "return", "''", "for", "filename", "in", "py_fil...
Returns a hexdigest of all the python files in the module.
[ "Returns", "a", "hexdigest", "of", "all", "the", "python", "files", "in", "the", "module", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/devtools/version.py#L11-L24
28,631
tensorflow/cleverhans
cleverhans/experimental/certification/utils.py
initialize_dual
def initialize_dual(neural_net_params_object, init_dual_file=None, random_init_variance=0.01, init_nu=200.0): """Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to fil...
python
def initialize_dual(neural_net_params_object, init_dual_file=None, random_init_variance=0.01, init_nu=200.0): """Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to fil...
[ "def", "initialize_dual", "(", "neural_net_params_object", ",", "init_dual_file", "=", "None", ",", "random_init_variance", "=", "0.01", ",", "init_nu", "=", "200.0", ")", ":", "lambda_pos", "=", "[", "]", "lambda_neg", "=", "[", "]", "lambda_quad", "=", "[", ...
Function to initialize the dual variables of the class. Args: neural_net_params_object: Object with the neural net weights, biases and types init_dual_file: Path to file containing dual variables, if the path is empty, perform random initialization Expects numpy dictionary with lambda...
[ "Function", "to", "initialize", "the", "dual", "variables", "of", "the", "class", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L22-L93
28,632
tensorflow/cleverhans
cleverhans/experimental/certification/utils.py
minimum_eigen_vector
def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn): """Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns pr...
python
def minimum_eigen_vector(x, num_steps, learning_rate, vector_prod_fn): """Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns pr...
[ "def", "minimum_eigen_vector", "(", "x", ",", "num_steps", ",", "learning_rate", ",", "vector_prod_fn", ")", ":", "x", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "x", ")", "for", "_", "in", "range", "(", "num_steps", ")", ":", "x", "=", "eig_one_s...
Computes eigenvector which corresponds to minimum eigenvalue. Args: x: initial value of eigenvector. num_steps: number of optimization steps. learning_rate: learning rate. vector_prod_fn: function which takes x and returns product H*x. Returns: approximate value of eigenvector. This functio...
[ "Computes", "eigenvector", "which", "corresponds", "to", "minimum", "eigenvalue", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L162-L181
28,633
tensorflow/cleverhans
cleverhans/experimental/certification/utils.py
tf_lanczos_smallest_eigval
def tf_lanczos_smallest_eigval(vector_prod_fn, matrix_dim, initial_vector, num_iter=1000, max_iter=1000, collapse_tol=1e-9, dtype=tf.f...
python
def tf_lanczos_smallest_eigval(vector_prod_fn, matrix_dim, initial_vector, num_iter=1000, max_iter=1000, collapse_tol=1e-9, dtype=tf.f...
[ "def", "tf_lanczos_smallest_eigval", "(", "vector_prod_fn", ",", "matrix_dim", ",", "initial_vector", ",", "num_iter", "=", "1000", ",", "max_iter", "=", "1000", ",", "collapse_tol", "=", "1e-9", ",", "dtype", "=", "tf", ".", "float32", ")", ":", "# alpha will...
Computes smallest eigenvector and eigenvalue using Lanczos in pure TF. This function computes smallest eigenvector and eigenvalue of the matrix which is implicitly specified by `vector_prod_fn`. `vector_prod_fn` is a function which takes `x` and returns a product of matrix in consideration and `x`. Computati...
[ "Computes", "smallest", "eigenvector", "and", "eigenvalue", "using", "Lanczos", "in", "pure", "TF", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/experimental/certification/utils.py#L184-L278
28,634
tensorflow/cleverhans
cleverhans/attacks/carlini_wagner_l2.py
CarliniWagnerL2.generate
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ 'Cannot...
python
def generate(self, x, **kwargs): """ Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params` """ assert self.sess is not None, \ 'Cannot...
[ "def", "generate", "(", "self", ",", "x", ",", "*", "*", "kwargs", ")", ":", "assert", "self", ".", "sess", "is", "not", "None", ",", "'Cannot use `generate` when no `sess` was provided'", "self", ".", "parse_params", "(", "*", "*", "kwargs", ")", "labels", ...
Return a tensor that constructs adversarial examples for the given input. Generate uses tf.py_func in order to operate over tensors. :param x: A tensor with the inputs. :param kwargs: See `parse_params`
[ "Return", "a", "tensor", "that", "constructs", "adversarial", "examples", "for", "the", "given", "input", ".", "Generate", "uses", "tf", ".", "py_func", "in", "order", "to", "operate", "over", "tensors", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L58-L85
28,635
tensorflow/cleverhans
cleverhans/attacks/carlini_wagner_l2.py
CWL2.attack
def attack(self, imgs, targets): """ Perform the L_2 attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels """ r = [] for i in range(0, len(imgs), sel...
python
def attack(self, imgs, targets): """ Perform the L_2 attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels """ r = [] for i in range(0, len(imgs), sel...
[ "def", "attack", "(", "self", ",", "imgs", ",", "targets", ")", ":", "r", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "imgs", ")", ",", "self", ".", "batch_size", ")", ":", "_logger", ".", "debug", "(", "(", "\"Running ...
Perform the L_2 attack on the given instance for the given targets. If self.targeted is true, then the targets represents the target labels If self.targeted is false, then targets are the original class labels
[ "Perform", "the", "L_2", "attack", "on", "the", "given", "instance", "for", "the", "given", "targets", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/attacks/carlini_wagner_l2.py#L276-L291
28,636
tensorflow/cleverhans
examples/RL-attack/train.py
maybe_load_model
def maybe_load_model(savedir, container): """Load model if present at the specified path.""" if savedir is None: return state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip')) if container is not None: logger.log("Attempting to download model from Azure") found_model = container....
python
def maybe_load_model(savedir, container): """Load model if present at the specified path.""" if savedir is None: return state_path = os.path.join(os.path.join(savedir, 'training_state.pkl.zip')) if container is not None: logger.log("Attempting to download model from Azure") found_model = container....
[ "def", "maybe_load_model", "(", "savedir", ",", "container", ")", ":", "if", "savedir", "is", "None", ":", "return", "state_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "join", "(", "savedir", ",", "'training_state.pkl.zip'", ...
Load model if present at the specified path.
[ "Load", "model", "if", "present", "at", "the", "specified", "path", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/RL-attack/train.py#L130-L149
28,637
tensorflow/cleverhans
cleverhans_tutorials/__init__.py
check_installation
def check_installation(cur_file): """Warn user if running cleverhans from a different directory than tutorial.""" cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0] ch_dir = os.path.split(cleverhans.__path__[0])[0] if cur_dir != ch_dir: warnings.warn("It appears that you have at least tw...
python
def check_installation(cur_file): """Warn user if running cleverhans from a different directory than tutorial.""" cur_dir = os.path.split(os.path.dirname(os.path.abspath(cur_file)))[0] ch_dir = os.path.split(cleverhans.__path__[0])[0] if cur_dir != ch_dir: warnings.warn("It appears that you have at least tw...
[ "def", "check_installation", "(", "cur_file", ")", ":", "cur_dir", "=", "os", ".", "path", ".", "split", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "cur_file", ")", ")", ")", "[", "0", "]", "ch_dir", "=", ...
Warn user if running cleverhans from a different directory than tutorial.
[ "Warn", "user", "if", "running", "cleverhans", "from", "a", "different", "directory", "than", "tutorial", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans_tutorials/__init__.py#L13-L24
28,638
tensorflow/cleverhans
examples/nips17_adversarial_competition/dataset/download_images.py
get_image
def get_image(row, output_dir): """Downloads the image that corresponds to the given row. Prints a notification if the download fails.""" if not download_image(image_id=row[0], url=row[1], x1=float(row[2]), y1=float(row[3]), ...
python
def get_image(row, output_dir): """Downloads the image that corresponds to the given row. Prints a notification if the download fails.""" if not download_image(image_id=row[0], url=row[1], x1=float(row[2]), y1=float(row[3]), ...
[ "def", "get_image", "(", "row", ",", "output_dir", ")", ":", "if", "not", "download_image", "(", "image_id", "=", "row", "[", "0", "]", ",", "url", "=", "row", "[", "1", "]", ",", "x1", "=", "float", "(", "row", "[", "2", "]", ")", ",", "y1", ...
Downloads the image that corresponds to the given row. Prints a notification if the download fails.
[ "Downloads", "the", "image", "that", "corresponds", "to", "the", "given", "row", ".", "Prints", "a", "notification", "if", "the", "download", "fails", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L57-L67
28,639
tensorflow/cleverhans
examples/nips17_adversarial_competition/dataset/download_images.py
download_image
def download_image(image_id, url, x1, y1, x2, y2, output_dir): """Downloads one image, crops it, resizes it and saves it locally.""" output_filename = os.path.join(output_dir, image_id + '.png') if os.path.exists(output_filename): # Don't download image if it's already there return True try: # Downl...
python
def download_image(image_id, url, x1, y1, x2, y2, output_dir): """Downloads one image, crops it, resizes it and saves it locally.""" output_filename = os.path.join(output_dir, image_id + '.png') if os.path.exists(output_filename): # Don't download image if it's already there return True try: # Downl...
[ "def", "download_image", "(", "image_id", ",", "url", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "output_dir", ")", ":", "output_filename", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "image_id", "+", "'.png'", ")", "if", "os",...
Downloads one image, crops it, resizes it and saves it locally.
[ "Downloads", "one", "image", "crops", "it", "resizes", "it", "and", "saves", "it", "locally", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/nips17_adversarial_competition/dataset/download_images.py#L70-L92
28,640
tensorflow/cleverhans
examples/robust_vision_benchmark/cleverhans_attack_example/utils.py
py_func_grad
def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None): """Custom py_func with gradient support """ # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) g = tf.get_default_graph() with g.gradie...
python
def py_func_grad(func, inp, Tout, stateful=True, name=None, grad=None): """Custom py_func with gradient support """ # Need to generate a unique name to avoid duplicates: rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8)) tf.RegisterGradient(rnd_name)(grad) g = tf.get_default_graph() with g.gradie...
[ "def", "py_func_grad", "(", "func", ",", "inp", ",", "Tout", ",", "stateful", "=", "True", ",", "name", "=", "None", ",", "grad", "=", "None", ")", ":", "# Need to generate a unique name to avoid duplicates:", "rnd_name", "=", "'PyFuncGrad'", "+", "str", "(", ...
Custom py_func with gradient support
[ "Custom", "py_func", "with", "gradient", "support" ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/examples/robust_vision_benchmark/cleverhans_attack_example/utils.py#L25-L36
28,641
tensorflow/cleverhans
cleverhans/plot/pyplot_image.py
get_logits_over_interval
def get_logits_over_interval(sess, model, x_data, fgsm_params, min_epsilon=-10., max_epsilon=10., num_points=21): """Get logits when the input is perturbed in an interval in adv direction. Args: sess: Tf session model: Model for which we wish to...
python
def get_logits_over_interval(sess, model, x_data, fgsm_params, min_epsilon=-10., max_epsilon=10., num_points=21): """Get logits when the input is perturbed in an interval in adv direction. Args: sess: Tf session model: Model for which we wish to...
[ "def", "get_logits_over_interval", "(", "sess", ",", "model", ",", "x_data", ",", "fgsm_params", ",", "min_epsilon", "=", "-", "10.", ",", "max_epsilon", "=", "10.", ",", "num_points", "=", "21", ")", ":", "# Get the height, width and number of channels", "height"...
Get logits when the input is perturbed in an interval in adv direction. Args: sess: Tf session model: Model for which we wish to get logits. x_data: Numpy array corresponding to single data. point of shape [height, width, channels]. fgsm_params: Parameters for generating adversa...
[ "Get", "logits", "when", "the", "input", "is", "perturbed", "in", "an", "interval", "in", "adv", "direction", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L84-L137
28,642
tensorflow/cleverhans
cleverhans/plot/pyplot_image.py
linear_extrapolation_plot
def linear_extrapolation_plot(log_prob_adv_array, y, file_name, min_epsilon=-10, max_epsilon=10, num_points=21): """Generate linear extrapolation plot. Args: log_prob_adv_array: Numpy array containing log probabilities y: Tf placeholder for th...
python
def linear_extrapolation_plot(log_prob_adv_array, y, file_name, min_epsilon=-10, max_epsilon=10, num_points=21): """Generate linear extrapolation plot. Args: log_prob_adv_array: Numpy array containing log probabilities y: Tf placeholder for th...
[ "def", "linear_extrapolation_plot", "(", "log_prob_adv_array", ",", "y", ",", "file_name", ",", "min_epsilon", "=", "-", "10", ",", "max_epsilon", "=", "10", ",", "num_points", "=", "21", ")", ":", "import", "matplotlib", "matplotlib", ".", "use", "(", "'Agg...
Generate linear extrapolation plot. Args: log_prob_adv_array: Numpy array containing log probabilities y: Tf placeholder for the labels file_name: Plot filename min_epsilon: Minimum value of epsilon over the interval max_epsilon: Maximum value of epsilon over the interval num_poin...
[ "Generate", "linear", "extrapolation", "plot", "." ]
97488e215760547b81afc53f5e5de8ba7da5bd98
https://github.com/tensorflow/cleverhans/blob/97488e215760547b81afc53f5e5de8ba7da5bd98/cleverhans/plot/pyplot_image.py#L139-L182
28,643
backtrader/backtrader
contrib/utils/iqfeed-to-influxdb.py
IQFeedTool._send_cmd
def _send_cmd(self, cmd: str): """Encode IQFeed API messages.""" self._sock.sendall(cmd.encode(encoding='latin-1', errors='strict'))
python
def _send_cmd(self, cmd: str): """Encode IQFeed API messages.""" self._sock.sendall(cmd.encode(encoding='latin-1', errors='strict'))
[ "def", "_send_cmd", "(", "self", ",", "cmd", ":", "str", ")", ":", "self", ".", "_sock", ".", "sendall", "(", "cmd", ".", "encode", "(", "encoding", "=", "'latin-1'", ",", "errors", "=", "'strict'", ")", ")" ]
Encode IQFeed API messages.
[ "Encode", "IQFeed", "API", "messages", "." ]
59ee9521f9887c2a1030c6f1db8c918a5816fd64
https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L59-L61
28,644
backtrader/backtrader
contrib/utils/iqfeed-to-influxdb.py
IQFeedTool.iq_query
def iq_query(self, message: str): """Send data query to IQFeed API.""" end_msg = '!ENDMSG!' recv_buffer = 4096 # Send the historical data request message and buffer the data self._send_cmd(message) chunk = "" data = "" while True: chunk = sel...
python
def iq_query(self, message: str): """Send data query to IQFeed API.""" end_msg = '!ENDMSG!' recv_buffer = 4096 # Send the historical data request message and buffer the data self._send_cmd(message) chunk = "" data = "" while True: chunk = sel...
[ "def", "iq_query", "(", "self", ",", "message", ":", "str", ")", ":", "end_msg", "=", "'!ENDMSG!'", "recv_buffer", "=", "4096", "# Send the historical data request message and buffer the data", "self", ".", "_send_cmd", "(", "message", ")", "chunk", "=", "\"\"", "...
Send data query to IQFeed API.
[ "Send", "data", "query", "to", "IQFeed", "API", "." ]
59ee9521f9887c2a1030c6f1db8c918a5816fd64
https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L63-L90
28,645
backtrader/backtrader
contrib/utils/iqfeed-to-influxdb.py
IQFeedTool.get_historical_minute_data
def get_historical_minute_data(self, ticker: str): """Request historical 5 minute data from DTN.""" start = self._start stop = self._stop if len(stop) > 4: stop = stop[:4] if len(start) > 4: start = start[:4] for year in range(int(start), int(st...
python
def get_historical_minute_data(self, ticker: str): """Request historical 5 minute data from DTN.""" start = self._start stop = self._stop if len(stop) > 4: stop = stop[:4] if len(start) > 4: start = start[:4] for year in range(int(start), int(st...
[ "def", "get_historical_minute_data", "(", "self", ",", "ticker", ":", "str", ")", ":", "start", "=", "self", ".", "_start", "stop", "=", "self", ".", "_stop", "if", "len", "(", "stop", ")", ">", "4", ":", "stop", "=", "stop", "[", ":", "4", "]", ...
Request historical 5 minute data from DTN.
[ "Request", "historical", "5", "minute", "data", "from", "DTN", "." ]
59ee9521f9887c2a1030c6f1db8c918a5816fd64
https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L92-L118
28,646
backtrader/backtrader
contrib/utils/iqfeed-to-influxdb.py
IQFeedTool.add_data_to_df
def add_data_to_df(self, data: np.array): """Build Pandas Dataframe in memory""" col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi'] data = np.array(data).reshape(-1, len(col_names) + 1) df = pd.DataFrame(data=data[:, 1:], index=data[:, 0], co...
python
def add_data_to_df(self, data: np.array): """Build Pandas Dataframe in memory""" col_names = ['high_p', 'low_p', 'open_p', 'close_p', 'volume', 'oi'] data = np.array(data).reshape(-1, len(col_names) + 1) df = pd.DataFrame(data=data[:, 1:], index=data[:, 0], co...
[ "def", "add_data_to_df", "(", "self", ",", "data", ":", "np", ".", "array", ")", ":", "col_names", "=", "[", "'high_p'", ",", "'low_p'", ",", "'open_p'", ",", "'close_p'", ",", "'volume'", ",", "'oi'", "]", "data", "=", "np", ".", "array", "(", "data...
Build Pandas Dataframe in memory
[ "Build", "Pandas", "Dataframe", "in", "memory" ]
59ee9521f9887c2a1030c6f1db8c918a5816fd64
https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L120-L142
28,647
backtrader/backtrader
contrib/utils/iqfeed-to-influxdb.py
IQFeedTool.get_tickers_from_file
def get_tickers_from_file(self, filename): """Load ticker list from txt file""" if not os.path.exists(filename): log.error("Ticker List file does not exist: %s", filename) tickers = [] with io.open(filename, 'r') as fd: for ticker in fd: tickers.a...
python
def get_tickers_from_file(self, filename): """Load ticker list from txt file""" if not os.path.exists(filename): log.error("Ticker List file does not exist: %s", filename) tickers = [] with io.open(filename, 'r') as fd: for ticker in fd: tickers.a...
[ "def", "get_tickers_from_file", "(", "self", ",", "filename", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "log", ".", "error", "(", "\"Ticker List file does not exist: %s\"", ",", "filename", ")", "tickers", "=", "[", ...
Load ticker list from txt file
[ "Load", "ticker", "list", "from", "txt", "file" ]
59ee9521f9887c2a1030c6f1db8c918a5816fd64
https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/iqfeed-to-influxdb.py#L144-L153
28,648
backtrader/backtrader
contrib/utils/influxdb-import.py
InfluxDBTool.write_dataframe_to_idb
def write_dataframe_to_idb(self, ticker): """Write Pandas Dataframe to InfluxDB database""" cachepath = self._cache cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker)) if not os.path.exists(cachefile): log.warn('Import file does not exist: %s' % (cache...
python
def write_dataframe_to_idb(self, ticker): """Write Pandas Dataframe to InfluxDB database""" cachepath = self._cache cachefile = ('%s/%s-1M.csv.gz' % (cachepath, ticker)) if not os.path.exists(cachefile): log.warn('Import file does not exist: %s' % (cache...
[ "def", "write_dataframe_to_idb", "(", "self", ",", "ticker", ")", ":", "cachepath", "=", "self", ".", "_cache", "cachefile", "=", "(", "'%s/%s-1M.csv.gz'", "%", "(", "cachepath", ",", "ticker", ")", ")", "if", "not", "os", ".", "path", ".", "exists", "("...
Write Pandas Dataframe to InfluxDB database
[ "Write", "Pandas", "Dataframe", "to", "InfluxDB", "database" ]
59ee9521f9887c2a1030c6f1db8c918a5816fd64
https://github.com/backtrader/backtrader/blob/59ee9521f9887c2a1030c6f1db8c918a5816fd64/contrib/utils/influxdb-import.py#L29-L49
28,649
AirtestProject/Airtest
playground/win_ide.py
WindowsInIDE.connect
def connect(self, **kwargs): """ Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None """ self.app = self._app.connect(**kwargs) try: self._top_window = self.app.top_window().wrapper_object...
python
def connect(self, **kwargs): """ Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None """ self.app = self._app.connect(**kwargs) try: self._top_window = self.app.top_window().wrapper_object...
[ "def", "connect", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "app", "=", "self", ".", "_app", ".", "connect", "(", "*", "*", "kwargs", ")", "try", ":", "self", ".", "_top_window", "=", "self", ".", "app", ".", "top_window", "(",...
Connect to window and set it foreground Args: **kwargs: optional arguments Returns: None
[ "Connect", "to", "window", "and", "set", "it", "foreground" ]
21583da2698a601cd632228228fc16d41f60a517
https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/win_ide.py#L19-L35
28,650
AirtestProject/Airtest
playground/win_ide.py
WindowsInIDE.get_rect
def get_rect(self): """ Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom) """ if self.handle: left, top, right, bottom = win32gui.GetWindowRect(self.handle) return RECT(left, top, right, bottom) else: ...
python
def get_rect(self): """ Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom) """ if self.handle: left, top, right, bottom = win32gui.GetWindowRect(self.handle) return RECT(left, top, right, bottom) else: ...
[ "def", "get_rect", "(", "self", ")", ":", "if", "self", ".", "handle", ":", "left", ",", "top", ",", "right", ",", "bottom", "=", "win32gui", ".", "GetWindowRect", "(", "self", ".", "handle", ")", "return", "RECT", "(", "left", ",", "top", ",", "ri...
Get rectangle of app or desktop resolution Returns: RECT(left, top, right, bottom)
[ "Get", "rectangle", "of", "app", "or", "desktop", "resolution" ]
21583da2698a601cd632228228fc16d41f60a517
https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/win_ide.py#L37-L51
28,651
AirtestProject/Airtest
playground/win_ide.py
WindowsInIDE.snapshot
def snapshot(self, filename="tmp.png"): """ Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot Returns: display the screenshot """ if not filename: filename = "tm...
python
def snapshot(self, filename="tmp.png"): """ Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot Returns: display the screenshot """ if not filename: filename = "tm...
[ "def", "snapshot", "(", "self", ",", "filename", "=", "\"tmp.png\"", ")", ":", "if", "not", "filename", ":", "filename", "=", "\"tmp.png\"", "if", "self", ".", "handle", ":", "try", ":", "screenshot", "(", "filename", ",", "self", ".", "handle", ")", "...
Take a screenshot and save it to `tmp.png` filename by default Args: filename: name of file where to store the screenshot Returns: display the screenshot
[ "Take", "a", "screenshot", "and", "save", "it", "to", "tmp", ".", "png", "filename", "by", "default" ]
21583da2698a601cd632228228fc16d41f60a517
https://github.com/AirtestProject/Airtest/blob/21583da2698a601cd632228228fc16d41f60a517/playground/win_ide.py#L53-L78
28,652
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_SimpleDecoder
def _SimpleDecoder(wire_type, decode_value): """Return a constructor for a decoder for fields of a particular type. Args: wire_type: The field's wire type. decode_value: A function which decodes an individual value, e.g. _DecodeVarint() """ def SpecificDecoder(field_number, is_repeated, ...
python
def _SimpleDecoder(wire_type, decode_value): """Return a constructor for a decoder for fields of a particular type. Args: wire_type: The field's wire type. decode_value: A function which decodes an individual value, e.g. _DecodeVarint() """ def SpecificDecoder(field_number, is_repeated, ...
[ "def", "_SimpleDecoder", "(", "wire_type", ",", "decode_value", ")", ":", "def", "SpecificDecoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ",", "key", ",", "new_default", ")", ":", "if", "is_packed", ":", "local_DecodeVarint", "=", "_DecodeVa...
Return a constructor for a decoder for fields of a particular type. Args: wire_type: The field's wire type. decode_value: A function which decodes an individual value, e.g. _DecodeVarint()
[ "Return", "a", "constructor", "for", "a", "decoder", "for", "fields", "of", "a", "particular", "type", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L190-L246
28,653
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_ModifiedDecoder
def _ModifiedDecoder(wire_type, decode_value, modify_value): """Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usually modify_value is ZigZagDecode. """ # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but # not enough to make a significan...
python
def _ModifiedDecoder(wire_type, decode_value, modify_value): """Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usually modify_value is ZigZagDecode. """ # Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but # not enough to make a significan...
[ "def", "_ModifiedDecoder", "(", "wire_type", ",", "decode_value", ",", "modify_value", ")", ":", "# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but", "# not enough to make a significant difference.", "def", "InnerDecode", "(", "buffer", ",", "pos", ")"...
Like SimpleDecoder but additionally invokes modify_value on every value before storing it. Usually modify_value is ZigZagDecode.
[ "Like", "SimpleDecoder", "but", "additionally", "invokes", "modify_value", "on", "every", "value", "before", "storing", "it", ".", "Usually", "modify_value", "is", "ZigZagDecode", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L249-L260
28,654
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_StructPackDecoder
def _StructPackDecoder(wire_type, format): """Return a constructor for a decoder for a fixed-width field. Args: wire_type: The field's wire type. format: The format string to pass to struct.unpack(). """ value_size = struct.calcsize(format) local_unpack = struct.unpack # Reusing _SimpleDeco...
python
def _StructPackDecoder(wire_type, format): """Return a constructor for a decoder for a fixed-width field. Args: wire_type: The field's wire type. format: The format string to pass to struct.unpack(). """ value_size = struct.calcsize(format) local_unpack = struct.unpack # Reusing _SimpleDeco...
[ "def", "_StructPackDecoder", "(", "wire_type", ",", "format", ")", ":", "value_size", "=", "struct", ".", "calcsize", "(", "format", ")", "local_unpack", "=", "struct", ".", "unpack", "# Reusing _SimpleDecoder is slightly slower than copying a bunch of code, but", "# not ...
Return a constructor for a decoder for a fixed-width field. Args: wire_type: The field's wire type. format: The format string to pass to struct.unpack().
[ "Return", "a", "constructor", "for", "a", "decoder", "for", "a", "fixed", "-", "width", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L263-L285
28,655
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_FloatDecoder
def _FloatDecoder(): """Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values. """ local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign # bit, ...
python
def _FloatDecoder(): """Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values. """ local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 32-bit value in little-endian byte order. Bit 1 is the sign # bit, ...
[ "def", "_FloatDecoder", "(", ")", ":", "local_unpack", "=", "struct", ".", "unpack", "def", "InnerDecode", "(", "buffer", ",", "pos", ")", ":", "# We expect a 32-bit value in little-endian byte order. Bit 1 is the sign", "# bit, bits 2-9 represent the exponent, and bits 10-32 ...
Returns a decoder for a float field. This code works around a bug in struct.unpack for non-finite 32-bit floating-point values.
[ "Returns", "a", "decoder", "for", "a", "float", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L288-L320
28,656
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_DoubleDecoder
def _DoubleDecoder(): """Returns a decoder for a double field. This code works around a bug in struct.unpack for not-a-number. """ local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 64-bit value in little-endian byte order. Bit 1 is the sign # bit, bits 2-12 represent the exp...
python
def _DoubleDecoder(): """Returns a decoder for a double field. This code works around a bug in struct.unpack for not-a-number. """ local_unpack = struct.unpack def InnerDecode(buffer, pos): # We expect a 64-bit value in little-endian byte order. Bit 1 is the sign # bit, bits 2-12 represent the exp...
[ "def", "_DoubleDecoder", "(", ")", ":", "local_unpack", "=", "struct", ".", "unpack", "def", "InnerDecode", "(", "buffer", ",", "pos", ")", ":", "# We expect a 64-bit value in little-endian byte order. Bit 1 is the sign", "# bit, bits 2-12 represent the exponent, and bits 13-6...
Returns a decoder for a double field. This code works around a bug in struct.unpack for not-a-number.
[ "Returns", "a", "decoder", "for", "a", "double", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L323-L350
28,657
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
StringDecoder
def StringDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a string field.""" local_DecodeVarint = _DecodeVarint local_unicode = six.text_type def _ConvertToUnicode(byte_str): try: return local_unicode(byte_str, 'utf-8') except UnicodeDecodeError as e: ...
python
def StringDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a string field.""" local_DecodeVarint = _DecodeVarint local_unicode = six.text_type def _ConvertToUnicode(byte_str): try: return local_unicode(byte_str, 'utf-8') except UnicodeDecodeError as e: ...
[ "def", "StringDecoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ",", "key", ",", "new_default", ")", ":", "local_DecodeVarint", "=", "_DecodeVarint", "local_unicode", "=", "six", ".", "text_type", "def", "_ConvertToUnicode", "(", "byte_str", ")"...
Returns a decoder for a string field.
[ "Returns", "a", "decoder", "for", "a", "string", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L461-L504
28,658
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
BytesDecoder
def BytesDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a bytes field.""" local_DecodeVarint = _DecodeVarint assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) ...
python
def BytesDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a bytes field.""" local_DecodeVarint = _DecodeVarint assert not is_packed if is_repeated: tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED) ...
[ "def", "BytesDecoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ",", "key", ",", "new_default", ")", ":", "local_DecodeVarint", "=", "_DecodeVarint", "assert", "not", "is_packed", "if", "is_repeated", ":", "tag_bytes", "=", "encoder", ".", "Tag...
Returns a decoder for a bytes field.
[ "Returns", "a", "decoder", "for", "a", "bytes", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L507-L541
28,659
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
GroupDecoder
def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a group field.""" end_tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_END_GROUP) end_tag_len = len(end_tag_bytes) assert not is_packed if is_repeated: tag...
python
def GroupDecoder(field_number, is_repeated, is_packed, key, new_default): """Returns a decoder for a group field.""" end_tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_END_GROUP) end_tag_len = len(end_tag_bytes) assert not is_packed if is_repeated: tag...
[ "def", "GroupDecoder", "(", "field_number", ",", "is_repeated", ",", "is_packed", ",", "key", ",", "new_default", ")", ":", "end_tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_number", ",", "wire_format", ".", "WIRETYPE_END_GROUP", ")", "end_tag_len", ...
Returns a decoder for a group field.
[ "Returns", "a", "decoder", "for", "a", "group", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L544-L588
28,660
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
MapDecoder
def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field.""" key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarin...
python
def MapDecoder(field_descriptor, new_default, is_message_map): """Returns a decoder for a map field.""" key = field_descriptor tag_bytes = encoder.TagBytes(field_descriptor.number, wire_format.WIRETYPE_LENGTH_DELIMITED) tag_len = len(tag_bytes) local_DecodeVarint = _DecodeVarin...
[ "def", "MapDecoder", "(", "field_descriptor", ",", "new_default", ",", "is_message_map", ")", ":", "key", "=", "field_descriptor", "tag_bytes", "=", "encoder", ".", "TagBytes", "(", "field_descriptor", ".", "number", ",", "wire_format", ".", "WIRETYPE_LENGTH_DELIMIT...
Returns a decoder for a map field.
[ "Returns", "a", "decoder", "for", "a", "map", "field", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L719-L759
28,661
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_SkipVarint
def _SkipVarint(buffer, pos, end): """Skip a varint value. Returns the new position.""" # Previously ord(buffer[pos]) raised IndexError when pos is out of range. # With this code, ord(b'') raises TypeError. Both are handled in # python_message.py to generate a 'Truncated message' error. while ord(buffer[pos...
python
def _SkipVarint(buffer, pos, end): """Skip a varint value. Returns the new position.""" # Previously ord(buffer[pos]) raised IndexError when pos is out of range. # With this code, ord(b'') raises TypeError. Both are handled in # python_message.py to generate a 'Truncated message' error. while ord(buffer[pos...
[ "def", "_SkipVarint", "(", "buffer", ",", "pos", ",", "end", ")", ":", "# Previously ord(buffer[pos]) raised IndexError when pos is out of range.", "# With this code, ord(b'') raises TypeError. Both are handled in", "# python_message.py to generate a 'Truncated message' error.", "while", ...
Skip a varint value. Returns the new position.
[ "Skip", "a", "varint", "value", ".", "Returns", "the", "new", "position", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L765-L775
28,662
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_SkipLengthDelimited
def _SkipLengthDelimited(buffer, pos, end): """Skip a length-delimited value. Returns the new position.""" (size, pos) = _DecodeVarint(buffer, pos) pos += size if pos > end: raise _DecodeError('Truncated message.') return pos
python
def _SkipLengthDelimited(buffer, pos, end): """Skip a length-delimited value. Returns the new position.""" (size, pos) = _DecodeVarint(buffer, pos) pos += size if pos > end: raise _DecodeError('Truncated message.') return pos
[ "def", "_SkipLengthDelimited", "(", "buffer", ",", "pos", ",", "end", ")", ":", "(", "size", ",", "pos", ")", "=", "_DecodeVarint", "(", "buffer", ",", "pos", ")", "pos", "+=", "size", "if", "pos", ">", "end", ":", "raise", "_DecodeError", "(", "'Tru...
Skip a length-delimited value. Returns the new position.
[ "Skip", "a", "length", "-", "delimited", "value", ".", "Returns", "the", "new", "position", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L785-L792
28,663
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_SkipGroup
def _SkipGroup(buffer, pos, end): """Skip sub-group. Returns the new position.""" while 1: (tag_bytes, pos) = ReadTag(buffer, pos) new_pos = SkipField(buffer, pos, end, tag_bytes) if new_pos == -1: return pos pos = new_pos
python
def _SkipGroup(buffer, pos, end): """Skip sub-group. Returns the new position.""" while 1: (tag_bytes, pos) = ReadTag(buffer, pos) new_pos = SkipField(buffer, pos, end, tag_bytes) if new_pos == -1: return pos pos = new_pos
[ "def", "_SkipGroup", "(", "buffer", ",", "pos", ",", "end", ")", ":", "while", "1", ":", "(", "tag_bytes", ",", "pos", ")", "=", "ReadTag", "(", "buffer", ",", "pos", ")", "new_pos", "=", "SkipField", "(", "buffer", ",", "pos", ",", "end", ",", "...
Skip sub-group. Returns the new position.
[ "Skip", "sub", "-", "group", ".", "Returns", "the", "new", "position", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L794-L802
28,664
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py
_FieldSkipper
def _FieldSkipper(): """Constructs the SkipField function.""" WIRETYPE_TO_SKIPPER = [ _SkipVarint, _SkipFixed64, _SkipLengthDelimited, _SkipGroup, _EndGroup, _SkipFixed32, _RaiseInvalidWireType, _RaiseInvalidWireType, ] wiretype_mask = wire_format.TAG_TYPE_M...
python
def _FieldSkipper(): """Constructs the SkipField function.""" WIRETYPE_TO_SKIPPER = [ _SkipVarint, _SkipFixed64, _SkipLengthDelimited, _SkipGroup, _EndGroup, _SkipFixed32, _RaiseInvalidWireType, _RaiseInvalidWireType, ] wiretype_mask = wire_format.TAG_TYPE_M...
[ "def", "_FieldSkipper", "(", ")", ":", "WIRETYPE_TO_SKIPPER", "=", "[", "_SkipVarint", ",", "_SkipFixed64", ",", "_SkipLengthDelimited", ",", "_SkipGroup", ",", "_EndGroup", ",", "_SkipFixed32", ",", "_RaiseInvalidWireType", ",", "_RaiseInvalidWireType", ",", "]", "...
Constructs the SkipField function.
[ "Constructs", "the", "SkipField", "function", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/internal/decoder.py#L822-L852
28,665
apple/turicreate
src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py
DecisionTreeClassifier.predict
def predict(self, dataset, output_type='class', missing_value_action='auto'): """ A flexible and advanced prediction API. The target column is provided during :func:`~turicreate.decision_tree.create`. If the target column is in the `dataset` it will be ignored. Paramete...
python
def predict(self, dataset, output_type='class', missing_value_action='auto'): """ A flexible and advanced prediction API. The target column is provided during :func:`~turicreate.decision_tree.create`. If the target column is in the `dataset` it will be ignored. Paramete...
[ "def", "predict", "(", "self", ",", "dataset", ",", "output_type", "=", "'class'", ",", "missing_value_action", "=", "'auto'", ")", ":", "_check_categorical_option_type", "(", "'output_type'", ",", "output_type", ",", "[", "'class'", ",", "'margin'", ",", "'prob...
A flexible and advanced prediction API. The target column is provided during :func:`~turicreate.decision_tree.create`. If the target column is in the `dataset` it will be ignored. Parameters ---------- dataset : SFrame A dataset that has the same columns that ...
[ "A", "flexible", "and", "advanced", "prediction", "API", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/decision_tree_classifier.py#L210-L271
28,666
apple/turicreate
src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py
Tracker.slave_envs
def slave_envs(self): """ get enviroment variables for slaves can be passed in as args or envs """ if self.hostIP == 'dns': host = socket.gethostname() elif self.hostIP == 'ip': host = socket.gethostbyname(socket.getfqdn()) else: ...
python
def slave_envs(self): """ get enviroment variables for slaves can be passed in as args or envs """ if self.hostIP == 'dns': host = socket.gethostname() elif self.hostIP == 'ip': host = socket.gethostbyname(socket.getfqdn()) else: ...
[ "def", "slave_envs", "(", "self", ")", ":", "if", "self", ".", "hostIP", "==", "'dns'", ":", "host", "=", "socket", ".", "gethostname", "(", ")", "elif", "self", ".", "hostIP", "==", "'ip'", ":", "host", "=", "socket", ".", "gethostbyname", "(", "soc...
get enviroment variables for slaves can be passed in as args or envs
[ "get", "enviroment", "variables", "for", "slaves", "can", "be", "passed", "in", "as", "args", "or", "envs" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L144-L156
28,667
apple/turicreate
src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py
Tracker.find_share_ring
def find_share_ring(self, tree_map, parent_map, r): """ get a ring structure that tends to share nodes with the tree return a list starting from r """ nset = set(tree_map[r]) cset = nset - set([parent_map[r]]) if len(cset) == 0: return [r] rlst...
python
def find_share_ring(self, tree_map, parent_map, r): """ get a ring structure that tends to share nodes with the tree return a list starting from r """ nset = set(tree_map[r]) cset = nset - set([parent_map[r]]) if len(cset) == 0: return [r] rlst...
[ "def", "find_share_ring", "(", "self", ",", "tree_map", ",", "parent_map", ",", "r", ")", ":", "nset", "=", "set", "(", "tree_map", "[", "r", "]", ")", "cset", "=", "nset", "-", "set", "(", "[", "parent_map", "[", "r", "]", "]", ")", "if", "len",...
get a ring structure that tends to share nodes with the tree return a list starting from r
[ "get", "a", "ring", "structure", "that", "tends", "to", "share", "nodes", "with", "the", "tree", "return", "a", "list", "starting", "from", "r" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L174-L191
28,668
apple/turicreate
src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py
Tracker.get_ring
def get_ring(self, tree_map, parent_map): """ get a ring connection used to recover local data """ assert parent_map[0] == -1 rlst = self.find_share_ring(tree_map, parent_map, 0) assert len(rlst) == len(tree_map) ring_map = {} nslave = len(tree_map) ...
python
def get_ring(self, tree_map, parent_map): """ get a ring connection used to recover local data """ assert parent_map[0] == -1 rlst = self.find_share_ring(tree_map, parent_map, 0) assert len(rlst) == len(tree_map) ring_map = {} nslave = len(tree_map) ...
[ "def", "get_ring", "(", "self", ",", "tree_map", ",", "parent_map", ")", ":", "assert", "parent_map", "[", "0", "]", "==", "-", "1", "rlst", "=", "self", ".", "find_share_ring", "(", "tree_map", ",", "parent_map", ",", "0", ")", "assert", "len", "(", ...
get a ring connection used to recover local data
[ "get", "a", "ring", "connection", "used", "to", "recover", "local", "data" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L193-L206
28,669
apple/turicreate
src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py
Tracker.get_link_map
def get_link_map(self, nslave): """ get the link map, this is a bit hacky, call for better algorithm to place similar nodes together """ tree_map, parent_map = self.get_tree(nslave) ring_map = self.get_ring(tree_map, parent_map) rmap = {0 : 0} k = 0 ...
python
def get_link_map(self, nslave): """ get the link map, this is a bit hacky, call for better algorithm to place similar nodes together """ tree_map, parent_map = self.get_tree(nslave) ring_map = self.get_ring(tree_map, parent_map) rmap = {0 : 0} k = 0 ...
[ "def", "get_link_map", "(", "self", ",", "nslave", ")", ":", "tree_map", ",", "parent_map", "=", "self", ".", "get_tree", "(", "nslave", ")", "ring_map", "=", "self", ".", "get_ring", "(", "tree_map", ",", "parent_map", ")", "rmap", "=", "{", "0", ":",...
get the link map, this is a bit hacky, call for better algorithm to place similar nodes together
[ "get", "the", "link", "map", "this", "is", "a", "bit", "hacky", "call", "for", "better", "algorithm", "to", "place", "similar", "nodes", "together" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/xgboost/subtree/rabit/tracker/rabit_tracker.py#L208-L233
28,670
apple/turicreate
deps/src/boost_1_68_0/tools/build/src/tools/msvc.py
maybe_rewrite_setup
def maybe_rewrite_setup(toolset, setup_script, setup_options, version, rewrite_setup='off'): """ Helper rule to generate a faster alternative to MSVC setup scripts. We used to call MSVC setup scripts directly in every action, however in newer MSVC versions (10.0+) they make long-lasting registry querie...
python
def maybe_rewrite_setup(toolset, setup_script, setup_options, version, rewrite_setup='off'): """ Helper rule to generate a faster alternative to MSVC setup scripts. We used to call MSVC setup scripts directly in every action, however in newer MSVC versions (10.0+) they make long-lasting registry querie...
[ "def", "maybe_rewrite_setup", "(", "toolset", ",", "setup_script", ",", "setup_options", ",", "version", ",", "rewrite_setup", "=", "'off'", ")", ":", "result", "=", "'\"{}\" {}'", ".", "format", "(", "setup_script", ",", "setup_options", ")", "# At the moment we ...
Helper rule to generate a faster alternative to MSVC setup scripts. We used to call MSVC setup scripts directly in every action, however in newer MSVC versions (10.0+) they make long-lasting registry queries which have a significant impact on build time.
[ "Helper", "rule", "to", "generate", "a", "faster", "alternative", "to", "MSVC", "setup", "scripts", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/tools/build/src/tools/msvc.py#L626-L682
28,671
apple/turicreate
src/unity/python/turicreate/toolkits/classifier/_classifier.py
create
def create(dataset, target, features=None, validation_set = 'auto', verbose=True): """ Automatically create a suitable classifier model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ...
python
def create(dataset, target, features=None, validation_set = 'auto', verbose=True): """ Automatically create a suitable classifier model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ...
[ "def", "create", "(", "dataset", ",", "target", ",", "features", "=", "None", ",", "validation_set", "=", "'auto'", ",", "verbose", "=", "True", ")", ":", "return", "_sl", ".", "create_classification_with_model_selector", "(", "dataset", ",", "target", ",", ...
Automatically create a suitable classifier model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ---------- dataset : SFrame Dataset for training the model. target : string ...
[ "Automatically", "create", "a", "suitable", "classifier", "model", "based", "on", "the", "provided", "training", "data", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/_classifier.py#L12-L106
28,672
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.add_column
def add_column(self, data, column_name="", inplace=False): """ Adds the specified column to this SFrame. The number of elements in the data given must match every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, return...
python
def add_column(self, data, column_name="", inplace=False): """ Adds the specified column to this SFrame. The number of elements in the data given must match every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, return...
[ "def", "add_column", "(", "self", ",", "data", ",", "column_name", "=", "\"\"", ",", "inplace", "=", "False", ")", ":", "# Check type for pandas dataframe or SArray?", "if", "not", "isinstance", "(", "data", ",", "SArray", ")", ":", "raise", "TypeError", "(", ...
Adds the specified column to this SFrame. The number of elements in the data given must match every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the curr...
[ "Adds", "the", "specified", "column", "to", "this", "SFrame", ".", "The", "number", "of", "elements", "in", "the", "data", "given", "must", "match", "every", "other", "column", "of", "the", "SFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L62-L101
28,673
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.add_columns
def add_columns(self, data, column_names=None, inplace=False): """ Adds columns to the SFrame. The number of elements in all columns must match every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFr...
python
def add_columns(self, data, column_names=None, inplace=False): """ Adds columns to the SFrame. The number of elements in all columns must match every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFr...
[ "def", "add_columns", "(", "self", ",", "data", ",", "column_names", "=", "None", ",", "inplace", "=", "False", ")", ":", "datalist", "=", "data", "if", "isinstance", "(", "data", ",", "SFrame", ")", ":", "other", "=", "data", "datalist", "=", "[", "...
Adds columns to the SFrame. The number of elements in all columns must match every other column of the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFram...
[ "Adds", "columns", "to", "the", "SFrame", ".", "The", "number", "of", "elements", "in", "all", "columns", "must", "match", "every", "other", "column", "of", "the", "SFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L104-L154
28,674
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.remove_column
def remove_column(self, column_name, inplace=False): """ Removes the column with the given name from the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current ...
python
def remove_column(self, column_name, inplace=False): """ Removes the column with the given name from the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current ...
[ "def", "remove_column", "(", "self", ",", "column_name", ",", "inplace", "=", "False", ")", ":", "if", "column_name", "not", "in", "self", ".", "column_names", "(", ")", ":", "raise", "KeyError", "(", "'Cannot find column %s'", "%", "column_name", ")", "if",...
Removes the column with the given name from the SFrame. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- ...
[ "Removes", "the", "column", "with", "the", "given", "name", "from", "the", "SFrame", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L157-L195
28,675
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.swap_columns
def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Swaps the columns with the given names. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current ...
python
def swap_columns(self, column_name_1, column_name_2, inplace=False): """ Swaps the columns with the given names. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current ...
[ "def", "swap_columns", "(", "self", ",", "column_name_1", ",", "column_name_2", ",", "inplace", "=", "False", ")", ":", "if", "inplace", ":", "self", ".", "__is_dirty__", "=", "True", "with", "cython_context", "(", ")", ":", "if", "self", ".", "_is_vertex_...
Swaps the columns with the given names. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True, this operation modifies the current SFrame, returning self. Parameters ---------- column_name_1 ...
[ "Swaps", "the", "columns", "with", "the", "given", "names", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L211-L243
28,676
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.rename
def rename(self, names, inplace=False): """ Rename the columns using the 'names' dict. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the current ...
python
def rename(self, names, inplace=False): """ Rename the columns using the 'names' dict. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the current ...
[ "def", "rename", "(", "self", ",", "names", ",", "inplace", "=", "False", ")", ":", "if", "(", "type", "(", "names", ")", "is", "not", "dict", ")", ":", "raise", "TypeError", "(", "'names must be a dictionary: oldname -> newname'", ")", "if", "inplace", ":...
Rename the columns using the 'names' dict. This changes the names of the columns given as the keys and replaces them with the names given as the values. If inplace == False (default) this operation does not modify the current SFrame, returning a new SFrame. If inplace == True,...
[ "Rename", "the", "columns", "using", "the", "names", "dict", ".", "This", "changes", "the", "names", "of", "the", "columns", "given", "as", "the", "keys", "and", "replaces", "them", "with", "the", "names", "given", "as", "the", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L245-L279
28,677
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.num_rows
def num_rows(self): """ Returns the number of rows. Returns ------- out : int Number of rows in the SFrame. """ if self._is_vertex_frame(): return self.__graph__.summary()['num_vertices'] elif self._is_edge_frame(): ret...
python
def num_rows(self): """ Returns the number of rows. Returns ------- out : int Number of rows in the SFrame. """ if self._is_vertex_frame(): return self.__graph__.summary()['num_vertices'] elif self._is_edge_frame(): ret...
[ "def", "num_rows", "(", "self", ")", ":", "if", "self", ".", "_is_vertex_frame", "(", ")", ":", "return", "self", ".", "__graph__", ".", "summary", "(", ")", "[", "'num_vertices'", "]", "elif", "self", ".", "_is_edge_frame", "(", ")", ":", "return", "s...
Returns the number of rows. Returns ------- out : int Number of rows in the SFrame.
[ "Returns", "the", "number", "of", "rows", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L321-L333
28,678
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.column_names
def column_names(self): """ Returns the column names. Returns ------- out : list[string] Column names of the SFrame. """ if self._is_vertex_frame(): return self.__graph__.__proxy__.get_vertex_fields() elif self._is_edge_frame(): ...
python
def column_names(self): """ Returns the column names. Returns ------- out : list[string] Column names of the SFrame. """ if self._is_vertex_frame(): return self.__graph__.__proxy__.get_vertex_fields() elif self._is_edge_frame(): ...
[ "def", "column_names", "(", "self", ")", ":", "if", "self", ".", "_is_vertex_frame", "(", ")", ":", "return", "self", ".", "__graph__", ".", "__proxy__", ".", "get_vertex_fields", "(", ")", "elif", "self", ".", "_is_edge_frame", "(", ")", ":", "return", ...
Returns the column names. Returns ------- out : list[string] Column names of the SFrame.
[ "Returns", "the", "column", "names", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L346-L358
28,679
apple/turicreate
src/unity/python/turicreate/data_structures/gframe.py
GFrame.column_types
def column_types(self): """ Returns the column types. Returns ------- out : list[type] Column types of the SFrame. """ if self.__type__ == VERTEX_GFRAME: return self.__graph__.__proxy__.get_vertex_field_types() elif self.__type__ =...
python
def column_types(self): """ Returns the column types. Returns ------- out : list[type] Column types of the SFrame. """ if self.__type__ == VERTEX_GFRAME: return self.__graph__.__proxy__.get_vertex_field_types() elif self.__type__ =...
[ "def", "column_types", "(", "self", ")", ":", "if", "self", ".", "__type__", "==", "VERTEX_GFRAME", ":", "return", "self", ".", "__graph__", ".", "__proxy__", ".", "get_vertex_field_types", "(", ")", "elif", "self", ".", "__type__", "==", "EDGE_GFRAME", ":",...
Returns the column types. Returns ------- out : list[type] Column types of the SFrame.
[ "Returns", "the", "column", "types", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/data_structures/gframe.py#L360-L372
28,680
apple/turicreate
src/unity/python/turicreate/toolkits/regression/_regression.py
create
def create(dataset, target, features=None, validation_set = 'auto', verbose=True): """ Automatically create a suitable regression model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ...
python
def create(dataset, target, features=None, validation_set = 'auto', verbose=True): """ Automatically create a suitable regression model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ...
[ "def", "create", "(", "dataset", ",", "target", ",", "features", "=", "None", ",", "validation_set", "=", "'auto'", ",", "verbose", "=", "True", ")", ":", "dataset", ",", "validation_set", "=", "_validate_data", "(", "dataset", ",", "target", ",", "feature...
Automatically create a suitable regression model based on the provided training data. To use specific options of a desired model, use the ``create`` function of the corresponding model. Parameters ---------- dataset : SFrame Dataset for training the model. target : str The...
[ "Automatically", "create", "a", "suitable", "regression", "model", "based", "on", "the", "provided", "training", "data", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/regression/_regression.py#L14-L116
28,681
apple/turicreate
src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py
removable
def removable(self, node): ''' node is removable only if all of its children are as well. ''' throw_away = [] for child in self.children(node): throw_away.append(self.visit(child)) if self.mode == 'exclusive': return all(throw_away) elif self.mode == 'inclusive': ret...
python
def removable(self, node): ''' node is removable only if all of its children are as well. ''' throw_away = [] for child in self.children(node): throw_away.append(self.visit(child)) if self.mode == 'exclusive': return all(throw_away) elif self.mode == 'inclusive': ret...
[ "def", "removable", "(", "self", ",", "node", ")", ":", "throw_away", "=", "[", "]", "for", "child", "in", "self", ".", "children", "(", "node", ")", ":", "throw_away", ".", "append", "(", "self", ".", "visit", "(", "child", ")", ")", "if", "self",...
node is removable only if all of its children are as well.
[ "node", "is", "removable", "only", "if", "all", "of", "its", "children", "are", "as", "well", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py#L17-L30
28,682
apple/turicreate
src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py
PruneVisitor.reduce
def reduce(self, body): ''' remove nodes from a list ''' i = 0 while i < len(body): stmnt = body[i] if self.visit(stmnt): body.pop(i) else: i += 1
python
def reduce(self, body): ''' remove nodes from a list ''' i = 0 while i < len(body): stmnt = body[i] if self.visit(stmnt): body.pop(i) else: i += 1
[ "def", "reduce", "(", "self", ",", "body", ")", ":", "i", "=", "0", "while", "i", "<", "len", "(", "body", ")", ":", "stmnt", "=", "body", "[", "i", "]", "if", "self", ".", "visit", "(", "stmnt", ")", ":", "body", ".", "pop", "(", "i", ")",...
remove nodes from a list
[ "remove", "nodes", "from", "a", "list" ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/meta/asttools/mutators/prune_mutator.py#L52-L62
28,683
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py
SymbolDatabase.RegisterMessage
def RegisterMessage(self, message): """Registers the given message type in the local database. Calls to GetSymbol() and GetMessages() will return messages registered here. Args: message: a message.Message, to be registered. Returns: The provided message. """ desc = message.DESCRI...
python
def RegisterMessage(self, message): """Registers the given message type in the local database. Calls to GetSymbol() and GetMessages() will return messages registered here. Args: message: a message.Message, to be registered. Returns: The provided message. """ desc = message.DESCRI...
[ "def", "RegisterMessage", "(", "self", ",", "message", ")", ":", "desc", "=", "message", ".", "DESCRIPTOR", "self", ".", "_classes", "[", "desc", ".", "full_name", "]", "=", "message", "self", ".", "pool", ".", "AddDescriptor", "(", "desc", ")", "return"...
Registers the given message type in the local database. Calls to GetSymbol() and GetMessages() will return messages registered here. Args: message: a message.Message, to be registered. Returns: The provided message.
[ "Registers", "the", "given", "message", "type", "in", "the", "local", "database", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py#L68-L83
28,684
apple/turicreate
src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py
SymbolDatabase.GetMessages
def GetMessages(self, files): # TODO(amauryfa): Fix the differences with MessageFactory. """Gets all registered messages from a specified file. Only messages already created and registered will be returned; (this is the case for imported _pb2 modules) But unlike MessageFactory, this version also re...
python
def GetMessages(self, files): # TODO(amauryfa): Fix the differences with MessageFactory. """Gets all registered messages from a specified file. Only messages already created and registered will be returned; (this is the case for imported _pb2 modules) But unlike MessageFactory, this version also re...
[ "def", "GetMessages", "(", "self", ",", "files", ")", ":", "# TODO(amauryfa): Fix the differences with MessageFactory.", "def", "_GetAllMessageNames", "(", "desc", ")", ":", "\"\"\"Walk a message Descriptor and recursively yields all message names.\"\"\"", "yield", "desc", ".", ...
Gets all registered messages from a specified file. Only messages already created and registered will be returned; (this is the case for imported _pb2 modules) But unlike MessageFactory, this version also returns already defined nested messages, but does not register any message extensions. Args: ...
[ "Gets", "all", "registered", "messages", "from", "a", "specified", "file", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/deps/protobuf/python/google/protobuf/symbol_database.py#L137-L173
28,685
apple/turicreate
src/unity/python/turicreate/toolkits/evaluation.py
_check_prob_and_prob_vector
def _check_prob_and_prob_vector(predictions): """ Check that the predictionsa are either probabilities of prob-vectors. """ from .._deps import numpy ptype = predictions.dtype import array if ptype not in [float, numpy.ndarray, array.array, int]: err_msg = "Input `predictions` must...
python
def _check_prob_and_prob_vector(predictions): """ Check that the predictionsa are either probabilities of prob-vectors. """ from .._deps import numpy ptype = predictions.dtype import array if ptype not in [float, numpy.ndarray, array.array, int]: err_msg = "Input `predictions` must...
[ "def", "_check_prob_and_prob_vector", "(", "predictions", ")", ":", "from", ".", ".", "_deps", "import", "numpy", "ptype", "=", "predictions", ".", "dtype", "import", "array", "if", "ptype", "not", "in", "[", "float", ",", "numpy", ".", "ndarray", ",", "ar...
Check that the predictionsa are either probabilities of prob-vectors.
[ "Check", "that", "the", "predictionsa", "are", "either", "probabilities", "of", "prob", "-", "vectors", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/evaluation.py#L36-L48
28,686
apple/turicreate
src/unity/python/turicreate/toolkits/evaluation.py
_supervised_evaluation_error_checking
def _supervised_evaluation_error_checking(targets, predictions): """ Perform basic error checking for the evaluation metrics. Check types and sizes of the inputs. """ _raise_error_if_not_sarray(targets, "targets") _raise_error_if_not_sarray(predictions, "predictions") if (len(targets) != len...
python
def _supervised_evaluation_error_checking(targets, predictions): """ Perform basic error checking for the evaluation metrics. Check types and sizes of the inputs. """ _raise_error_if_not_sarray(targets, "targets") _raise_error_if_not_sarray(predictions, "predictions") if (len(targets) != len...
[ "def", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", ":", "_raise_error_if_not_sarray", "(", "targets", ",", "\"targets\"", ")", "_raise_error_if_not_sarray", "(", "predictions", ",", "\"predictions\"", ")", "if", "(", "len", "(", "...
Perform basic error checking for the evaluation metrics. Check types and sizes of the inputs.
[ "Perform", "basic", "error", "checking", "for", "the", "evaluation", "metrics", ".", "Check", "types", "and", "sizes", "of", "the", "inputs", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/evaluation.py#L50-L59
28,687
apple/turicreate
src/unity/python/turicreate/toolkits/evaluation.py
max_error
def max_error(targets, predictions): r""" Compute the maximum absolute deviation between two SArrays. Parameters ---------- targets : SArray[float or int] An Sarray of ground truth target values. predictions : SArray[float or int] The prediction that corresponds to each target ...
python
def max_error(targets, predictions): r""" Compute the maximum absolute deviation between two SArrays. Parameters ---------- targets : SArray[float or int] An Sarray of ground truth target values. predictions : SArray[float or int] The prediction that corresponds to each target ...
[ "def", "max_error", "(", "targets", ",", "predictions", ")", ":", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", "return", "_turicreate", ".", "extensions", ".", "_supervised_streaming_evaluator", "(", "targets", ",", "predictions", ...
r""" Compute the maximum absolute deviation between two SArrays. Parameters ---------- targets : SArray[float or int] An Sarray of ground truth target values. predictions : SArray[float or int] The prediction that corresponds to each target value. This vector must have the ...
[ "r", "Compute", "the", "maximum", "absolute", "deviation", "between", "two", "SArrays", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/evaluation.py#L248-L288
28,688
apple/turicreate
src/unity/python/turicreate/toolkits/evaluation.py
rmse
def rmse(targets, predictions): r""" Compute the root mean squared error between two SArrays. Parameters ---------- targets : SArray[float or int] An Sarray of ground truth target values. predictions : SArray[float or int] The prediction that corresponds to each target value. ...
python
def rmse(targets, predictions): r""" Compute the root mean squared error between two SArrays. Parameters ---------- targets : SArray[float or int] An Sarray of ground truth target values. predictions : SArray[float or int] The prediction that corresponds to each target value. ...
[ "def", "rmse", "(", "targets", ",", "predictions", ")", ":", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", "return", "_turicreate", ".", "extensions", ".", "_supervised_streaming_evaluator", "(", "targets", ",", "predictions", ",", ...
r""" Compute the root mean squared error between two SArrays. Parameters ---------- targets : SArray[float or int] An Sarray of ground truth target values. predictions : SArray[float or int] The prediction that corresponds to each target value. This vector must have the sam...
[ "r", "Compute", "the", "root", "mean", "squared", "error", "between", "two", "SArrays", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/evaluation.py#L290-L336
28,689
apple/turicreate
src/unity/python/turicreate/toolkits/evaluation.py
confusion_matrix
def confusion_matrix(targets, predictions): r""" Compute the confusion matrix for classifier predictions. Parameters ---------- targets : SArray Ground truth class labels (cannot be of type float). predictions : SArray The prediction that corresponds to each target value. ...
python
def confusion_matrix(targets, predictions): r""" Compute the confusion matrix for classifier predictions. Parameters ---------- targets : SArray Ground truth class labels (cannot be of type float). predictions : SArray The prediction that corresponds to each target value. ...
[ "def", "confusion_matrix", "(", "targets", ",", "predictions", ")", ":", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", "_check_same_type_not_float", "(", "targets", ",", "predictions", ")", "return", "_turicreate", ".", "extensions", ...
r""" Compute the confusion matrix for classifier predictions. Parameters ---------- targets : SArray Ground truth class labels (cannot be of type float). predictions : SArray The prediction that corresponds to each target value. This vector must have the same length as ``ta...
[ "r", "Compute", "the", "confusion", "matrix", "for", "classifier", "predictions", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/evaluation.py#L337-L372
28,690
apple/turicreate
src/unity/python/turicreate/toolkits/evaluation.py
auc
def auc(targets, predictions, average='macro', index_map=None): r""" Compute the area under the ROC curve for the given targets and predictions. Parameters ---------- targets : SArray An SArray containing the observed values. For binary classification, the alpha-numerically first ca...
python
def auc(targets, predictions, average='macro', index_map=None): r""" Compute the area under the ROC curve for the given targets and predictions. Parameters ---------- targets : SArray An SArray containing the observed values. For binary classification, the alpha-numerically first ca...
[ "def", "auc", "(", "targets", ",", "predictions", ",", "average", "=", "'macro'", ",", "index_map", "=", "None", ")", ":", "_supervised_evaluation_error_checking", "(", "targets", ",", "predictions", ")", "_check_categorical_option_type", "(", "'average'", ",", "a...
r""" Compute the area under the ROC curve for the given targets and predictions. Parameters ---------- targets : SArray An SArray containing the observed values. For binary classification, the alpha-numerically first category is considered the reference category. prediction...
[ "r", "Compute", "the", "area", "under", "the", "ROC", "curve", "for", "the", "given", "targets", "and", "predictions", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/evaluation.py#L1150-L1269
28,691
apple/turicreate
deps/src/boost_1_68_0/status/boost_check_library.py
check_library.get_library_meta
def get_library_meta(self): ''' Fetches the meta data for the current library. The data could be in the superlib meta data file. If we can't find the data None is returned. ''' parent_dir = os.path.dirname(self.library_dir) if self.test_file_exists(os.path.join(self.libra...
python
def get_library_meta(self): ''' Fetches the meta data for the current library. The data could be in the superlib meta data file. If we can't find the data None is returned. ''' parent_dir = os.path.dirname(self.library_dir) if self.test_file_exists(os.path.join(self.libra...
[ "def", "get_library_meta", "(", "self", ")", ":", "parent_dir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "library_dir", ")", "if", "self", ".", "test_file_exists", "(", "os", ".", "path", ".", "join", "(", "self", ".", "library_dir", "...
Fetches the meta data for the current library. The data could be in the superlib meta data file. If we can't find the data None is returned.
[ "Fetches", "the", "meta", "data", "for", "the", "current", "library", ".", "The", "data", "could", "be", "in", "the", "superlib", "meta", "data", "file", ".", "If", "we", "can", "t", "find", "the", "data", "None", "is", "returned", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/deps/src/boost_1_68_0/status/boost_check_library.py#L182-L205
28,692
apple/turicreate
src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree.py
convert
def convert(model, feature_names = None, target = 'target', force_32bit_float = True): """ Convert a trained XGBoost model to Core ML format. Parameters ---------- decision_tree : Booster A trained XGboost tree model. feature_names: [str] | str Names of input features that will...
python
def convert(model, feature_names = None, target = 'target', force_32bit_float = True): """ Convert a trained XGBoost model to Core ML format. Parameters ---------- decision_tree : Booster A trained XGboost tree model. feature_names: [str] | str Names of input features that will...
[ "def", "convert", "(", "model", ",", "feature_names", "=", "None", ",", "target", "=", "'target'", ",", "force_32bit_float", "=", "True", ")", ":", "return", "_MLModel", "(", "_convert_tree_ensemble", "(", "model", ",", "feature_names", ",", "target", ",", "...
Convert a trained XGBoost model to Core ML format. Parameters ---------- decision_tree : Booster A trained XGboost tree model. feature_names: [str] | str Names of input features that will be exposed in the Core ML model interface. Can be set to one of the following: ...
[ "Convert", "a", "trained", "XGBoost", "model", "to", "Core", "ML", "format", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/external/coremltools_wrap/coremltools/coremltools/converters/xgboost/_tree.py#L9-L51
28,693
apple/turicreate
src/unity/python/turicreate/toolkits/_feature_engineering/_feature_engineering.py
Transformer.fit
def fit(self, data): """ Fit a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted version of the object) See Also -------- tra...
python
def fit(self, data): """ Fit a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted version of the object) See Also -------- tra...
[ "def", "fit", "(", "self", ",", "data", ")", ":", "_raise_error_if_not_sframe", "(", "data", ",", "\"data\"", ")", "self", ".", "__proxy__", ".", "fit", "(", "data", ")", "return", "self" ]
Fit a transformer using the SFrame `data`. Parameters ---------- data : SFrame The data used to fit the transformer. Returns ------- self (A fitted version of the object) See Also -------- transform, fit_transform Examples ...
[ "Fit", "a", "transformer", "using", "the", "SFrame", "data", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_feature_engineering/_feature_engineering.py#L236-L262
28,694
apple/turicreate
src/unity/python/turicreate/toolkits/_tree_model_mixin.py
TreeModelMixin.extract_features
def extract_features(self, dataset, missing_value_action='auto'): """ For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used...
python
def extract_features(self, dataset, missing_value_action='auto'): """ For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used...
[ "def", "extract_features", "(", "self", ",", "dataset", ",", "missing_value_action", "=", "'auto'", ")", ":", "_raise_error_if_not_sframe", "(", "dataset", ",", "\"dataset\"", ")", "if", "missing_value_action", "==", "'auto'", ":", "missing_value_action", "=", "sele...
For each example in the dataset, extract the leaf indices of each tree as features. For multiclass classification, each leaf index contains #num_class numbers. The returned feature vectors can be used as input to train another supervised learning model such as a :py:cla...
[ "For", "each", "example", "in", "the", "dataset", "extract", "the", "leaf", "indices", "of", "each", "tree", "as", "features", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_tree_model_mixin.py#L65-L120
28,695
apple/turicreate
src/unity/python/turicreate/toolkits/_tree_model_mixin.py
TreeModelMixin._extract_features_with_missing
def _extract_features_with_missing(self, dataset, tree_id = 0, missing_value_action = 'auto'): """ Extract features along with all the missing features associated with a dataset. Parameters ---------- dataset: bool Dataset on which to make predict...
python
def _extract_features_with_missing(self, dataset, tree_id = 0, missing_value_action = 'auto'): """ Extract features along with all the missing features associated with a dataset. Parameters ---------- dataset: bool Dataset on which to make predict...
[ "def", "_extract_features_with_missing", "(", "self", ",", "dataset", ",", "tree_id", "=", "0", ",", "missing_value_action", "=", "'auto'", ")", ":", "# Extract the features from only one tree.", "sf", "=", "dataset", "sf", "[", "'leaf_id'", "]", "=", "self", ".",...
Extract features along with all the missing features associated with a dataset. Parameters ---------- dataset: bool Dataset on which to make predictions. missing_value_action: str, optional Action to perform when missing values are encountered. This can ...
[ "Extract", "features", "along", "with", "all", "the", "missing", "features", "associated", "with", "a", "dataset", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/_tree_model_mixin.py#L122-L189
28,696
apple/turicreate
src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py
_sort_topk_votes
def _sort_topk_votes(x, k): """ Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes. """ y = sorted(x.items(), key=lambda x: x[1], reverse=True)[:k] return [{'class': i[0], 'votes': i[1]} for i in y]
python
def _sort_topk_votes(x, k): """ Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes. """ y = sorted(x.items(), key=lambda x: x[1], reverse=True)[:k] return [{'class': i[0], 'votes': i[1]} for i in y]
[ "def", "_sort_topk_votes", "(", "x", ",", "k", ")", ":", "y", "=", "sorted", "(", "x", ".", "items", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", "[", "1", "]", ",", "reverse", "=", "True", ")", "[", ":", "k", "]", "return", "[", "{"...
Sort a dictionary of classes and corresponding vote totals according to the votes, then truncate to the highest 'k' classes.
[ "Sort", "a", "dictionary", "of", "classes", "and", "corresponding", "vote", "totals", "according", "to", "the", "votes", "then", "truncate", "to", "the", "highest", "k", "classes", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py#L33-L39
28,697
apple/turicreate
src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py
_construct_auto_distance
def _construct_auto_distance(features, column_types): """ Construct a composite distance function for a set of features, based on the types of those features. NOTE: This function is very similar to `:func:_nearest_neighbors.choose_auto_distance`. The function is separate because the auto-distan...
python
def _construct_auto_distance(features, column_types): """ Construct a composite distance function for a set of features, based on the types of those features. NOTE: This function is very similar to `:func:_nearest_neighbors.choose_auto_distance`. The function is separate because the auto-distan...
[ "def", "_construct_auto_distance", "(", "features", ",", "column_types", ")", ":", "## Put input features into buckets based on type.", "numeric_ftrs", "=", "[", "]", "string_ftrs", "=", "[", "]", "dict_ftrs", "=", "[", "]", "for", "ftr", "in", "features", ":", "t...
Construct a composite distance function for a set of features, based on the types of those features. NOTE: This function is very similar to `:func:_nearest_neighbors.choose_auto_distance`. The function is separate because the auto-distance logic different than for each nearest neighbors-based toolk...
[ "Construct", "a", "composite", "distance", "function", "for", "a", "set", "of", "features", "based", "on", "the", "types", "of", "those", "features", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py#L42-L108
28,698
apple/turicreate
src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py
NearestNeighborClassifier._load_version
def _load_version(cls, state, version): """ A function to load a previously saved NearestNeighborClassifier model. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writ...
python
def _load_version(cls, state, version): """ A function to load a previously saved NearestNeighborClassifier model. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writ...
[ "def", "_load_version", "(", "cls", ",", "state", ",", "version", ")", ":", "assert", "(", "version", "==", "cls", ".", "_PYTHON_NN_CLASSIFIER_MODEL_VERSION", ")", "knn_model", "=", "_tc", ".", "nearest_neighbors", ".", "NearestNeighborsModel", "(", "state", "["...
A function to load a previously saved NearestNeighborClassifier model. Parameters ---------- unpickler : GLUnpickler A GLUnpickler file handler. version : int Version number maintained by the class writer.
[ "A", "function", "to", "load", "a", "previously", "saved", "NearestNeighborClassifier", "model", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py#L353-L369
28,699
apple/turicreate
src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py
NearestNeighborClassifier.evaluate
def evaluate(self, dataset, metric='auto', max_neighbors=10, radius=None): """ Evaluate the model's predictive accuracy. This is done by predicting the target class for instances in a new dataset and comparing to known target values. Parameters ---------- dataset...
python
def evaluate(self, dataset, metric='auto', max_neighbors=10, radius=None): """ Evaluate the model's predictive accuracy. This is done by predicting the target class for instances in a new dataset and comparing to known target values. Parameters ---------- dataset...
[ "def", "evaluate", "(", "self", ",", "dataset", ",", "metric", "=", "'auto'", ",", "max_neighbors", "=", "10", ",", "radius", "=", "None", ")", ":", "## Validate the metric name", "_raise_error_evaluation_metric_is_valid", "(", "metric", ",", "[", "'auto'", ",",...
Evaluate the model's predictive accuracy. This is done by predicting the target class for instances in a new dataset and comparing to known target values. Parameters ---------- dataset : SFrame Dataset of new observations. Must include columns with the same ...
[ "Evaluate", "the", "model", "s", "predictive", "accuracy", ".", "This", "is", "done", "by", "predicting", "the", "target", "class", "for", "instances", "in", "a", "new", "dataset", "and", "comparing", "to", "known", "target", "values", "." ]
74514c3f99e25b46f22c6e02977fe3da69221c2e
https://github.com/apple/turicreate/blob/74514c3f99e25b46f22c6e02977fe3da69221c2e/src/unity/python/turicreate/toolkits/classifier/nearest_neighbor_classifier.py#L734-L847