docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bigquery load -S|--source <source> -D|--destination <table> <other_args> Args: args: the arguments following '%bigquery load'. schema: a JSON schema for the destination table. Returns: A mes...
def _load_cell(args, schema): name = args['destination'] table = _get_table(name) if not table: table = datalab.bigquery.Table(name) if table.exists(): if args['mode'] == 'create': raise Exception('%s already exists; use --append or --overwrite' % name) elif schema: table.create(json.loa...
436,648
Construct a query output object where the result is a dataframe Args: start_row: the row of the table at which to start the export (default 0). max_rows: an upper limit on the number of rows to export (default None). use_cache: whether to use cached results or not (default True).
def dataframe(start_row=0, max_rows=None, use_cache=True): output = QueryOutput() output._output_type = 'dataframe' output._dataframe_start_row = start_row output._dataframe_max_rows = max_rows output._use_cache = use_cache return output
436,654
Initializes the ResourceDescriptors based on the specified filters. Args: filter_string: An optional filter expression describing the resource descriptors to be returned. context: An optional Context object to use instead of the global default.
def __init__(self, filter_string=None, context=None): self._client = _utils.make_client(context) self._filter_string = filter_string self._descriptors = None
436,656
Start a TensorBoard instance. Args: logdir: the logdir to run TensorBoard on. Raises: Exception if the instance cannot be started.
def start(logdir): if logdir.startswith('gs://'): # Check user does have access. TensorBoard will start successfully regardless # the user has read permissions or not so we check permissions here to # give user alerts if needed. datalab.storage._api.Api.verify_permitted_to_read(logdir) ...
436,658
Shut down a specific process. Args: pid: the pid of the process to shutdown.
def stop(pid): if psutil.pid_exists(pid): try: p = psutil.Process(pid) p.kill() except Exception: pass
436,659
To restore inception model variables from the checkpoint file. Some variables might be missing in the checkpoint file, so it only loads the ones that are avialable, assuming the rest would be initialized later. Args: checkpoint_path: Path to the checkpoint file for the Inception graph.
def restore_from_checkpoint(self, checkpoint_path): import tensorflow as tf # Get all variables to restore. Exclude Logits and AuxLogits because they # depend on the input data and we do not need to intialize them from # checkpoint. all_vars = tf.contrib.slim.get_variables_to_restore( e...
436,667
Get the embeddings for a given JPEG image. Args: batch_image_bytes: As if returned from [ff.read() for ff in file_list]. Returns: The Inception embeddings (bottleneck layer output)
def calculate_embedding(self, batch_image_bytes): return self.tf_session.run( self.embedding, feed_dict={self.input_jpeg: batch_image_bytes})
436,668
Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float.
def loss(logits, labels): labels = tf.to_int64(labels) cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits( logits=logits, labels=labels, name='xentropy') return tf.reduce_mean(cross_entropy, name='xentropy_mean')
436,675
Calculates the loss from the logits and the labels. Args: logits: Logits tensor, float - [batch_size, NUM_CLASSES]. labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float.
def training(loss_op): global_step = tf.Variable(0, name='global_step', trainable=False) with tf.name_scope('train'): optimizer = tf.train.AdamOptimizer(epsilon=0.001) train_op = optimizer.minimize(loss_op, global_step) return train_op, global_step
436,676
Builds a prediction graph and xports the model. Args: last_checkpoint: Path to the latest checkpoint file from training. output_dir: Path to the folder to be used to output the model.
def export(self, last_checkpoint, output_dir): logging.info('Exporting prediction graph to %s', output_dir) with tf.Session(graph=tf.Graph()) as sess: # Build and save prediction meta graph and trained variable values. inputs, outputs = self.build_prediction_graph() signature_def_map = { ...
436,686
Repackage an CloudML package and copy it to a staging dir. Args: package_root_dir: the root dir to install package from. Usually you can get the path from inside your module using a relative path to __file__. setup_py: the path to setup.py. output_tar_path: the GCS path of the output tarball pack...
def package_and_copy(package_root_dir, setup_py, output_tar_path): if not output_tar_path.startswith('gs://'): raise ValueError('output_tar_path needs to be a GCS path.') if not os.path.isfile(setup_py): raise ValueError('Supplied file "%s" does not exist.' % setup_py) dest_setup_py = os.path.join(pac...
436,689
Define pipeline arguments. Args: code: the Python code to execute that defines the arguments.
def _arguments(code, module): arg_parser = CommandParser.create('') try: # Define our special argument 'types' and add them to the environment. builtins = {'source': _table, 'datestring': _datestring} env = {} env.update(builtins) # Execute the cell which should be one or more calls to arg()...
436,698
Split a hybrid %%sql cell into the Python code and the queries. Populates a module with the queries. Args: cell: the contents of the %%sql cell. module: the module that the contents will populate. Returns: The default (last) query for the module.
def _split_cell(cell, module): lines = cell.split('\n') code = None last_def = -1 name = None define_wild_re = re.compile('^DEFINE\s+.*$', re.IGNORECASE) define_re = re.compile('^DEFINE\s+QUERY\s+([A-Z]\w*)\s*?(.*)$', re.IGNORECASE) select_re = re.compile('^SELECT\s*.*$', re.IGNORECASE) standard_sql_...
436,699
Builds the experiment function for learn_runner.run. Args: args: the command line args Returns: A function that returns a tf.learn experiment object.
def get_experiment_fn(args): def get_experiment(output_dir): # Merge schema, input features, and transforms. train_config = util.merge_metadata(args.preprocess_output_dir, args.transforms_file) # Get the model to train. estimator = util.get_estimator(output_...
436,702
Implements the stackdriver cell magic for ipython notebooks. Args: line: the contents of the storage line. Returns: The results of executing the cell.
def sd(line, cell=None): parser = google.datalab.utils.commands.CommandParser(prog='%sd', description=( 'Execute various Stackdriver related operations. Use "%sd ' '<stackdriver_product> -h" for help on a specific Stackdriver product.')) # %%sd monitoring _create_monitoring_subparser(parser) ret...
436,705
Copy the contents of src_dir into the folder dest_dir. Args: src_dir: gsc or local path. dest_dir: gcs or local path.
def recursive_copy(src_dir, dest_dir): file_io.recursive_create_dir(dest_dir) for file_name in file_io.list_directory(src_dir): old_path = os.path.join(src_dir, file_name) new_path = os.path.join(dest_dir, file_name) if file_io.is_directory(old_path): recursive_copy(old_path, new_path) el...
436,712
Makes prediction graph that takes json input. Args: args: command line args keep_target: If ture, target column is returned in prediction graph. Target column must also exist in input data assets_extra: other fiels to copy to the output folder job_dir: root job folder features: features d...
def make_export_strategy( args, keep_target, assets_extra, features, schema, stats): target_name = feature_transforms.get_target_name(features) csv_header = [col['name'] for col in schema] if not keep_target: csv_header.remove(target_name) def export_fn(es...
436,714
Reads a vocab file if it exists. Args: args: command line flags column_name: name of column to that has a vocab file. Returns: List of vocab words or [] if the vocab file is not found.
def read_vocab(args, column_name): vocab_path = os.path.join(args.analysis, feature_transforms.VOCAB_ANALYSIS_FILE % column_name) if not file_io.file_exists(vocab_path): return [] vocab, _ = feature_transforms.read_vocab_file(vocab_path) return vocab
436,716
Builds the experiment function for learn_runner.run. Args: args: the command line args Returns: A function that returns a tf.learn experiment object.
def get_experiment_fn(args): def get_experiment(output_dir): # Read schema, input features, and transforms. schema_path_with_target = os.path.join(args.analysis, feature_transforms.SCHEMA_FILE) features_path = os.path.join(args.analysis, ...
436,719
Try reading specified number of lines from the CSV object. Args: max_lines: max number of lines to read. If None, the whole file is read headers: a list of strings as column names. If None, it will use "col0, col1..." Returns: A pandas DataFrame with the schema inferred from the data. Rais...
def browse(self, max_lines=None, headers=None): if self.path.startswith('gs://'): lines = CsvFile._read_gcs_lines(self.path, max_lines) else: lines = CsvFile._read_local_lines(self.path, max_lines) if len(lines) == 0: return pd.DataFrame(columns=headers) columns_size = len(next(cs...
436,727
Get an item from a dictionary, handling nested lookups with dotted notation. Args: env: the environment (dictionary) to use to look up the name. name: the name to look up, in dotted notation. default: the value to return if the name if not found. Returns: The result of looking up the name, if foun...
def get_item(env, name, default=None): # TODO: handle attributes for key in name.split('.'): if isinstance(env, dict) and key in env: env = env[key] elif isinstance(env, types.ModuleType) and key in env.__dict__: env = env.__dict__[key] else: return default return env
436,730
Create a View from this Query. Args: view_name: the name of the View either as a string or a 3-part tuple (projectid, datasetid, name). Returns: A View for the Query.
def to_view(self, view_name): # Do the import here to avoid circular dependencies at top-level. from . import _view return _view.View(view_name, self._context).create(self._sql)
436,752
Add a cell only argument. Args: name: name of the argument. No need to start with "-" or "--". help: the help string of the argument. required: Whether it is required in cell content.
def add_cell_argument(self, name, help, required=False): for action in self._actions: if action.dest == name: raise ValueError('Arg "%s" was added by add_argument already.' % name) self._cell_args[name] = {'required': required, 'help': help}
436,758
Initializes an instance of a Job. Args: job_id: the BigQuery job ID corresponding to this job. context: a Context object providing project_id and credentials.
def __init__(self, job_id, context): super(GCPJob, self).__init__(job_id) if context is None: context = google.datalab.Context.default() self._context = context self._api = self._create_api(context)
436,760
Initializes an instance of a Summary. Args: path: a path or a list of paths to directories which hold TensorFlow events files. Can be local path or GCS paths. Wild cards allowed.
def __init__(self, paths): if isinstance(paths, six.string_types): self._paths = [paths] else: self._paths = paths
436,764
Get all events as pandas DataFrames given a list of names. Args: event_names: A list of events to get. Returns: A list with the same length and order as event_names. Each element is a dictionary {dir1: DataFrame1, dir2: DataFrame2, ...}. Multiple directories may contain events wi...
def get_events(self, event_names): if isinstance(event_names, six.string_types): event_names = [event_names] all_events = self.list_events() dirs_to_look = set() for event, dirs in six.iteritems(all_events): if event in event_names: dirs_to_look.update(dirs) ret_events = ...
436,767
Plots a list of events. Each event (a dir+event_name) is represetented as a line in the graph. Args: event_names: A list of events to plot. Each event_name may correspond to multiple events, each in a different directory. x_axis: whether to use step or time as x axis.
def plot(self, event_names, x_axis='step'): if isinstance(event_names, six.string_types): event_names = [event_names] events_list = self.get_events(event_names) for event_name, dir_event_dict in zip(event_names, events_list): for dir, df in six.iteritems(dir_event_dict): label = e...
436,768
Get a query argument to a cell magic. The query is specified with args['query']. We look that up and if it is a BQ query object, just return it. If it is a string, build a query object out of it and return that Args: args: the dictionary of magic arguments. cell: the cell contents which can be variabl...
def _get_query_argument(args, cell, env): sql_arg = args.get('query', None) if sql_arg is None: # Assume we have inline SQL in the cell if not isinstance(cell, basestring): raise Exception('Expected a --query argument or inline SQL') return bigquery.Query(cell, env=env) item = google.datalab...
436,780
Implements the BigQuery sample magic for sampling queries The supported sytanx is: %%bq sample <args> [<inline SQL>] Args: args: the optional arguments following '%%bq sample'. cell_body: optional contents of the cell Returns: The results of executing the sampling query, or a profile of the s...
def _sample_cell(args, cell_body): env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {} parameters = config.get('parameters') or [] if parameters: jsonschema.validate({'parameters': parameters}, BigQuerySchema.QUERY_P...
436,782
Implements the BigQuery cell magic used to dry run BQ queries. The supported syntax is: %%bq dryrun [-q|--sql <query identifier>] [<YAML or JSON cell_body or inline SQL>] Args: args: the argument following '%bq dryrun'. cell_body: optional contents of the cell interpreted as YAML or JSON. Returns...
def _dryrun_cell(args, cell_body): query = _get_query_argument(args, cell_body, google.datalab.utils.commands.notebook_environment()) if args['verbose']: print(query.sql) context = google.datalab.utils._utils._construct_context_for_args(args) result = query.dry_run(context=context) return bigquery._q...
436,783
Implements the Bigquery udf cell magic for ipython notebooks. The supported syntax is: %%bq udf --name <var> --language <lang> // @param <name> <type> // @returns <type> // @import <gcs_path> <js function> Args: args: the optional arguments following '%%bq udf'. cell_body: the UDF declaration (i...
def _udf_cell(args, cell_body): udf_name = args['name'] if not udf_name: raise Exception('Declaration must be of the form %%bq udf --name <variable name>') # Parse out parameters, return type, and imports param_pattern = r'^\s*\/\/\s*@param\s+([<>\w]+)\s+([<>\w,\s]+)\s*$' returns_pattern = r'^\s*\/\/\...
436,784
Implements the BigQuery datasource cell magic for ipython notebooks. The supported syntax is %%bq datasource --name <var> --paths <url> [--format <CSV|JSON>] <schema> Args: args: the optional arguments following '%%bq datasource' cell_body: the datasource's schema in json/yaml
def _datasource_cell(args, cell_body): name = args['name'] paths = args['paths'] data_format = (args['format'] or 'CSV').lower() compressed = args['compressed'] or False # Get the source schema from the cell body record = google.datalab.utils.commands.parse_config( cell_body, google.datalab.utils....
436,785
Implements the BigQuery cell magic for used to build SQL objects. The supported syntax is: %%bq query <args> [<inline SQL>] Args: args: the optional arguments following '%%bql query'. cell_body: the contents of the cell
def _query_cell(args, cell_body): name = args['name'] udfs = args['udfs'] datasources = args['datasources'] subqueries = args['subqueries'] # Finally build the query object query = bigquery.Query(cell_body, env=IPython.get_ipython().user_ns, udfs=udfs, data_sources=datasources, ...
436,786
Implements the BigQuery cell magic used to execute BQ queries. The supported syntax is: %%bq execute <args> [<inline SQL>] Args: args: the optional arguments following '%%bq execute'. cell_body: optional contents of the cell Returns: QueryResultsTable containing query result
def _execute_cell(args, cell_body): env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {} parameters = config.get('parameters') or [] if parameters: jsonschema.validate({'parameters': parameters}, BigQuerySchema.QUERY_P...
436,787
Given a variable or table name, get a Table if it exists. Args: name: the name of the Table or a variable referencing the Table. Returns: The Table, if found.
def _get_table(name): # If name is a variable referencing a table, use that. item = google.datalab.utils.commands.get_notebook_item(name) if isinstance(item, bigquery.Table): return item # Else treat this as a BQ table name and return the (cached) table if it exists. try: return _existing_table_cac...
436,788
Implements the BigQuery dataset magic subcommand used to operate on datasets The supported syntax is: %bq datasets <command> <args> Commands: {list, create, delete} Args: args: the optional arguments following '%bq datasets command'.
def _dataset_line(args): if args['command'] == 'list': filter_ = args['filter'] if args['filter'] else '*' context = google.datalab.Context.default() if args['project']: context = google.datalab.Context(args['project'], context.credentials) return _render_list([str(dataset) for dataset in big...
436,790
Implements the BigQuery table magic subcommand used to operate on tables The supported syntax is: %%bq tables <command> <args> Commands: {list, create, delete, describe, view} Args: args: the optional arguments following '%%bq tables command'. cell_body: optional contents of the cell interprete...
def _table_cell(args, cell_body): if args['command'] == 'list': filter_ = args['filter'] if args['filter'] else '*' if args['dataset']: if args['project'] is None: datasets = [bigquery.Dataset(args['dataset'])] else: context = google.datalab.Context(args['project'], ...
436,791
Implements the BigQuery extract magic used to extract query or table data to GCS. The supported syntax is: %bq extract <args> Args: args: the arguments following '%bigquery extract'.
def _extract_cell(args, cell_body): env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {} parameters = config.get('parameters') if args['table']: table = google.datalab.bigquery.Query.resolve_parameters(args['table'], ...
436,792
Implements the BigQuery load magic used to load data from GCS to a table. The supported syntax is: %bq load <optional args> Args: args: the arguments following '%bq load'. cell_body: optional contents of the cell interpreted as YAML or JSON. Returns: A message about whether the load succeed...
def _load_cell(args, cell_body): env = google.datalab.utils.commands.notebook_environment() config = google.datalab.utils.commands.parse_config(cell_body, env, False) or {} parameters = config.get('parameters') or [] if parameters: jsonschema.validate({'parameters': parameters}, BigQuerySchema.QUERY_PAR...
436,793
Implements the pipeline subcommand in the %%bq magic. Args: args: the arguments following '%%bq pipeline'. cell_body: Cell contents.
def _pipeline_cell(args, cell_body): name = args.get('name') if name is None: raise Exception('Pipeline name was not specified.') import google.datalab.utils as utils bq_pipeline_config = utils.commands.parse_config( cell_body, utils.commands.notebook_environment()) try: a...
436,795
Return a table viewer. This includes a static rendering of the first page of the table, that gets replaced by the charting code in environments where Javascript is executable and BQ is available. Args: table: the table to view. rows_per_page: how many rows to display at one time. fields: an arra...
def _table_viewer(table, rows_per_page=25, fields=None): # TODO(gram): rework this to use google.datalab.utils.commands.chart_html if not table.exists(): raise Exception('Table %s does not exist' % table.full_name) if not table.is_listable(): return "Done" _HTML_TEMPLATE = u if fields is None:...
436,798
Creates a BigQuery SQL UDF javascript object. Args: inputs: a list of (name, type) tuples representing the schema of input. outputs: a list of (name, type) tuples representing the schema of the output. name: the name of the function implementation: a javascript function defining the UDF log...
def _build_js(inputs, outputs, name, implementation, support_code): # Construct a comma-separated list of input field names # For example, field1,field2,... input_fields = json.dumps([f[0] for f in inputs]) # Construct a json representation of the output schema # For example, [{'name':'field1'...
436,802
Returns a sampling query for the SQL object. Args: sql: the SQL object to sample fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sampling is not specified. sampling: an optional sampling strategy to appl...
def sampling_query(sql, fields=None, count=5, sampling=None): if sampling is None: sampling = Sampling.default(count=count, fields=fields) return sampling(sql)
436,803
Plots an overview in a list of dataframes Args: data: a dictionary with key the name, and value the dataframe.
def plot(self, data): import IPython if not isinstance(data, dict) or not all(isinstance(v, pd.DataFrame) for v in data.values()): raise ValueError('Expect a dictionary where the values are all dataframes.') gfsg = GenericFeatureStatisticsGenerator() data = [{'name': k, 'table': self._remo...
436,805
Plots a detail view of data. Args: data: a Pandas dataframe. height: the height of the output.
def plot(self, data, height=1000, render_large_data=False): import IPython if not isinstance(data, pd.DataFrame): raise ValueError('Expect a DataFrame.') if (len(data) > 10000 and not render_large_data): raise ValueError('Facets dive may not work well with more than 10000 rows. ' + ...
436,806
Creates a feature statistics proto from a set of pandas dataframes. Args: dataframes: A list of dicts describing tables for each dataset for the proto. Each entry contains a 'table' field of the dataframe of the data and a 'name' field to identify the dataset in the proto. ...
def ProtoFromDataFrames(self, dataframes): datasets = [] for dataframe in dataframes: table = dataframe['table'] table_entries = {} for col in table: table_entries[col] = self.NdarrayToEntry(table[col]) datasets.append({ 'entries': table_entries, 'size': ...
436,808
Converts a Numpy dtype to a converter method if applicable. The converter method takes in a numpy array of objects of the provided dtype and returns a numpy array of the numbers backing that object for statistical analysis. Returns None if no converter is necessary. Args: dtype: ...
def DtypeToNumberConverter(self, dtype): if np.issubdtype(dtype, np.datetime64): def DatetimesToNumbers(dt_list): return np.array([pd.Timestamp(dt).value for dt in dt_list]) return DatetimesToNumbers elif np.issubdtype(dtype, np.timedelta64): def TimedetlasToNumbers(td_list): ...
436,810
Fills in the histogram with quantile information from the provided array. Args: hist: A Histogram proto message to fill in. nums: A list of numbers to create a quantiles histogram from.
def _PopulateQuantilesHistogram(self, hist, nums): if not nums: return num_quantile_buckets = 10 quantiles_to_get = [ x * 100 / num_quantile_buckets for x in range(num_quantile_buckets + 1) ] quantiles = np.percentile(nums, quantiles_to_get) hist.type = self.histogram_proto.QU...
436,813
Initializes an instance of a Dataset. Args: name: the name of the dataset, as a string or (project_id, dataset_id) tuple. context: an optional Context object providing project_id and credentials. If a specific project id or credentials are unspecified, the default ones configured at the globa...
def __init__(self, name, context=None): if context is None: context = google.datalab.Context.default() self._context = context self._api = _api.Api(context) self._name_parts = _utils.parse_dataset_name(name, self._api.project_id) self._full_name = '%s.%s' % self._name_parts self._info...
436,814
Read the csv files. Args: examples: string tensor train_config: training config keep_target: if true, the target column is expected to exist and it is returned in the features dict. Returns: Dict of feature_name to tensor. Target feature is in the dict.
def parse_example_tensor(examples, train_config, keep_target): csv_header = [] if keep_target: csv_header = train_config['csv_header'] else: csv_header = [name for name in train_config['csv_header'] if name != train_config['target_column']] # record_defaults are used by tf.decode_...
436,818
Returns a tf learn estimator. We only support {DNN, Linear}Regressor and {DNN, Linear}Classifier. This is controlled by the values of model_type in the args. Args: output_dir: Modes are saved into outputdir/train train_config: our training config args: command line parameters Returns: TF lean...
def get_estimator(output_dir, train_config, args): # Check the requested mode fits the preprocessed data. target_name = train_config['target_column'] if is_classification_model(args.model_type) and target_name not in \ train_config['categorical_columns']: raise ValueError('When using a classific...
436,820
Perform some transformations after reading in the input tensors. Args: features: dict of feature_name to tensor target: tensor train_config: our training config object preprocess_output_dir: folder should contain the vocab files. model_type: the tf model type. Raises: ValueError: if wrong ...
def preprocess_input(features, target, train_config, preprocess_output_dir, model_type): target_name = train_config['target_column'] key_name = train_config['key_column'] # Do the numerical transforms. # Numerical transforms supported for regression/classification # 1) num -> do noth...
436,821
Scale a tensor to scale_min to scale_max. Args: tensor: input tensor. Should be a numerical tensor. range_min: min expected value for this feature/tensor. range_max: max expected Value. scale_min: new expected min value. scale_max: new expected max value. Returns: scaled tensor.
def _scale_tensor(tensor, range_min, range_max, scale_min, scale_max): if range_min == range_max: return tensor float_tensor = tf.to_float(tensor) scaled_tensor = tf.divide((tf.subtract(float_tensor, range_min) * tf.constant(float(scale_max - scale_min))), ...
436,822
Loads the vocabulary file as a list of strings. Args: preprocess_output_dir: Should contain the file CATEGORICAL_ANALYSIS % name. name: name of the csv column. Returns: List of strings. Raises: ValueError: if file is missing.
def get_vocabulary(preprocess_output_dir, name): vocab_file = os.path.join(preprocess_output_dir, CATEGORICAL_ANALYSIS % name) if not file_io.file_exists(vocab_file): raise ValueError('File %s not found in %s' % (CATEGORICAL_ANALYSIS % name, preprocess_output_dir)) labels = python_por...
436,824
Perform some checks that the trainig config is correct. Args: train_config: train config as produced by merge_metadata() Raises: ValueError: if columns look wrong.
def validate_metadata(train_config): # Make sure we have a default for every column if len(train_config['csv_header']) != len(train_config['csv_defaults']): raise ValueError('Unequal number of columns in input features file and ' 'schema file.') # Check there are no missing columns. ...
436,826
Initialize the Projects object. Args: credentials: the credentials for the account.
def __init__(self, credentials=None): if credentials is None: credentials = _utils.get_credentials() self._api = _api.Api(credentials)
436,828
Iterate over SAM aligments with buffer, position-sorted paired-end Args: alignments (iterator of SAM/BAM alignments): the alignments to wrap max_buffer_size (int): maxmal numer of alignments to keep in memory. primary_only (bool): for each read, consider only the primary line (S...
def pair_SAM_alignments_with_buffer( alignments, max_buffer_size=30000000, primary_only=False): almnt_buffer = {} ambiguous_pairing_counter = 0 for almnt in alignments: if not almnt.paired_end: raise ValueError( "Sequence of paired-end alignm...
437,385
AppendEntries RPC — replicate log entries / heartbeat Args: destination — destination id Request params: term — leader’s term leader_id — so follower can redirect clients prev_log_index — index of log entry immediately preceding new ones prev_...
async def append_entries(self, destination=None): # Send AppendEntries RPC to destination if specified or broadcast to everyone destination_list = [destination] if destination else self.state.cluster for destination in destination_list: data = { 'type': 'app...
437,961
RequestVote RPC — gather votes Arguments: term — candidate’s term candidate_id — candidate requesting vote last_log_index — index of candidate’s last log entry last_log_term — term of candidate’s last log entry
def request_vote(self): data = { 'type': 'request_vote', 'term': self.storage.term, 'candidate_id': self.id, 'last_log_index': self.log.last_log_index, 'last_log_term': self.log.last_log_term } self.state.broadcast(data)
437,968
Start Raft node (server) Args: address_list — 127.0.0.1:8000 [, 127.0.0.1:8001 ...] cluster — [127.0.0.1:8001, 127.0.0.1:8002, ...]
async def register(*address_list, cluster=None, loop=None): loop = loop or asyncio.get_event_loop() for address in address_list: host, port = address.rsplit(':', 1) node = Node(address=(host, int(port)), loop=loop) await node.start() for address in cluster: hos...
437,997
Sends data to destination Node Args: data — serializable object destination — <str> '127.0.0.1:8000' or <tuple> (127.0.0.1, 8000)
async def send(self, data, destination): if isinstance(destination, str): host, port = destination.split(':') destination = host, int(port) await self.requests.put({ 'data': data, 'destination': destination })
438,000
Method that exports the different structures onto different formats. Args: ----- data: Data to export. ext: One of the following: csv, excel, json, ods. fileH: Fileheader for the output files. Returns: -------- Performs the export as requested by parameter.
def exportUsufy(data, ext, fileH): if ext == "csv": usufyToCsvExport(data, fileH+"."+ext) elif ext == "gml": usufyToGmlExport(data, fileH+"."+ext) elif ext == "json": usufyToJsonExport(data, fileH+"."+ext) elif ext == "ods": usufyToOdsExport(data, fileH+"."+ext) ...
438,216
Workaround to export to a json file. Args: ----- d: Data to export. fPath: File path for the output file.
def usufyToJsonExport(d, fPath): oldData = [] try: with open (fPath) as iF: oldText = iF.read() if oldText != "": oldData = json.loads(oldText) except: # No file found, so we will create it... pass jsonText = json.dumps(oldData+d, in...
438,218
Workaround to export to a .txt file or to show the information. Args: ----- d: Data to export. fPath: File path for the output file. If None was provided, it will assume that it has to print it. Returns: -------- unicode: It sometimes returns a unicode representatio...
def usufyToTextExport(d, fPath=None): # Manual check... if d == []: return "+------------------+\n| No data found... |\n+------------------+" import pyexcel as pe import pyexcel.ext.text as text if fPath == None: isTerminal = True else: isTerminal = False try:...
438,219
Workaround to export to a CSV file. Args: ----- d: Data to export. fPath: File path for the output file.
def usufyToCsvExport(d, fPath): from pyexcel_io import get_data try: oldData = {"OSRFramework": get_data(fPath) } except: # No information has been recovered oldData = {"OSRFramework":[]} # Generating the new tabular data. tabularData = _generateTabularData(d, oldData)...
438,220
Workaround to export to a .ods file. Args: ----- d: Data to export. fPath: File path for the output file.
def usufyToOdsExport(d, fPath): from pyexcel_ods import get_data try: #oldData = get_data(fPath) # A change in the API now returns only an array of arrays if there is only one sheet. oldData = {"OSRFramework": get_data(fPath) } except: # No information has been recovered...
438,221
Workaround to export to a .xls file. Args: ----- d: Data to export. fPath: File path for the output file.
def usufyToXlsExport(d, fPath): from pyexcel_xls import get_data try: #oldData = get_data(fPath) # A change in the API now returns only an array of arrays if there is only one sheet. oldData = {"OSRFramework": get_data(fPath) } except: # No information has been recovered...
438,222
Workaround to export to a .xlsx file. Args: ----- d: Data to export. fPath: File path for the output file.
def usufyToXlsxExport(d, fPath): from pyexcel_xlsx import get_data try: #oldData = get_data(fPath) # A change in the API now returns only an array of arrays if there is only one sheet. oldData = {"OSRFramework": get_data(fPath) } except: # No information has been recover...
438,223
Workaround to export data to a .gml file. Args: ----- d: Data to export. fPath: File path for the output file.
def usufyToGmlExport(d, fPath): # Reading the previous gml file try: oldData=nx.read_gml(fPath) except UnicodeDecodeError as e: print("UnicodeDecodeError:\t" + str(e)) print("Something went wrong when reading the .gml file relating to the decoding of UNICODE.") import ti...
438,225
Workaround to export to a png file. Args: ----- d: Data to export. fPath: File path for the output file.
def usufyToPngExport(d, fPath): newGraph = _generateGraphData(d) import matplotlib.pyplot as plt # Writing the png file nx.draw(newGraph) plt.savefig(fPath)
438,226
A function that calculates the MD5 hash of a file. Args: ----- filename: Path to the file. block_size: Chunks of suitable size. Block size directly depends on the block size of your filesystem to avoid performances issues. Blocks of 4096 octets (Default NTFS). bi...
def fileToMD5(filename, block_size=256*128, binary=False): md5 = hashlib.md5() with open(filename,'rb') as f: for chunk in iter(lambda: f.read(block_size), b''): md5.update(chunk) if not binary: return md5.hexdigest() return md5.digest()
438,227
Getting all the files in a folder. Args: ----- path: The path in which looking for the files Returns: -------- list: The list of filenames found.
def getFilesFromAFolder(path): from os import listdir from os.path import isfile, join #onlyfiles = [ f for f in listdir(path) if isfile(join(path,f)) ] onlyFiles = [] for f in listdir(path): if isfile(join(path, f)): onlyFiles.append(f) return onlyFiles
438,229
Method that launches the URI in the default browser of the system This function temporally deactivates the standard ouptut and errors to prevent the system to show unwanted messages. This method is based on this question from Stackoverflow. https://stackoverflow.com/questions/2323080/how-can-i-disable-...
def urisToBrowser(uris=[], autoraise=True): # Cloning stdout (1) and stderr (2) savout1 = os.dup(1) savout2 = os.dup(2) # Closing them os.close(1) os.close(2) os.open(os.devnull, os.O_RDWR) try: for uri in uris: # Opening the Tor URI using onion.cab proxy ...
438,230
Method that collects the URI from a list of entities and opens them Args: ----- res: A list containing several i3visio entities.
def openResultsInBrowser(res): print(emphasis("\n\tOpening URIs in the default web browser...")) urisToBrowser(["https://github.com/i3visio/osrframework"], autoraise=False) # Waiting 2 seconds to confirm that the browser is opened and prevent the OS from opening several windows time.sleep(2) ...
438,231
Function that colorizes a message. Args: ----- text: The string to be colorized. messageType: Possible options include "ERROR", "WARNING", "SUCCESS", "INFO" or "BOLD". Returns: -------- string: Colorized if the option is correct, including a tag at the end ...
def colorize(text, messageType=None): formattedText = str(text) # Set colors if "ERROR" in messageType: formattedText = colorama.Fore.RED + formattedText elif "WARNING" in messageType: formattedText = colorama.Fore.YELLOW + formattedText elif "SUCCESS" in messageType: fo...
438,232
Method that receives an email an creates linked entities Args: ----- e: Email to verify. Returns: -------- Three different values: email, alias and domain in a list.
def expandEntitiesFromEmail(e): # Grabbing the email email = {} email["type"] = "i3visio.email" email["value"] = e email["attributes"] = [] # Grabbing the alias alias = {} alias["type"] = "i3visio.alias" alias["value"] = e.split("@")[0] alias["attributes"] = [] # Grabb...
438,234
Method that trie to recover the whois info from a domain. Args: ----- domain: The domain to verify. Returns: -------- dict: A dictionary containing the result as an i3visio entity with its `value`, `type` and `attributes`.
def getWhoisInfo(domain): new = [] # Grabbing the aliases try: emails = {} emails["type"] = "i3visio.alias" emails["value"] = str(domain.split(".")[0]) emails["attributes"] = [] new.append(emails) except: pass info = whois.whois(domain) if ...
438,236
Method that globally permits to generate the domains to be checked. Args: ----- tlds: List of tlds. nicks: List of aliases. nicksFile: The filepath to the aliases file. Returns: -------- list: list of domains to be checked.
def createDomains(tlds, nicks=None, nicksFile=None): domain_candidates = [] if nicks != None: for n in nicks: for t in tlds: tmp = { "domain" : n + t["tld"], "type" : t["type"], "tld": t["tld"] }...
438,237
Wrapper for being able to launch all the threads of getPageWrapper. Args: ----- domain: We receive the parameters as a dictionary. ``` { "domain" : ".com", "type" : "global" } ``` launchWhois: Whether the whois info will be launched. R...
def pool_function(domain, launchWhois=False): is_valid = True try: ipv4 = socket.gethostbyname(domain["domain"]) # Check if this ipv4 normally throws false positives if isBlackListed(ipv4): return {"platform" : str(domain), "status": "ERROR", "data": {}} #If we...
438,238
[Optionally] recursive method to scan the files in a given folder. Args: ----- uri: the URI to be scanned. listRegexp: listRegexp is an array of <RegexpObject>. Returns: ------- dict: the key is the name of the file.
def scanResource(uri = None, listRegexp = None, verbosity=1, logFolder= "./logs"): logSet.setupLogger(loggerName="osrframework.entify", verbosity=verbosity, logFolder=logFolder) logger = logging.getLogger("osrframework.entify") results = [] logger.debug("Looking for regular expressions in: " + uri...
438,243
Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The element to be searched. kwargs: Dictionary with extra p...
def check_mailfy(self, query, kwargs={}): import requests s = requests.Session() # Getting the first response to grab the csrf_token r1 = s.get('https://www.infojobs.net') # Launching the query to Instagram r2 = s.post( 'https://www.infojobs.net/ca...
438,247
Method that verifies if a domain can be safely verified. Args: ----- email: the email whose domain will be verified. Returns: -------- bool: it represents whether the domain can be verified.
def weCanCheckTheseDomains(email): # Known platform not to be working... notWorking = [ "@aol.com", "@bk.ru", "@breakthru.com", "@gmx.", "@hotmail.co", "@inbox.com", "@latinmail.com", "@libero.it", "@mail.ru", "@mail2tor.com", ...
438,251
Method that generates a list of emails. Args: ----- emails: Any premade list of emails. emailsFile: Filepath to the emails file (one per line). nicks: A list of aliases. nicksFile: Filepath to the aliases file (one per line). domains: Domains where the aliases will be te...
def grabEmails(emails=None, emailsFile=None, nicks=None, nicksFile=None, domains=EMAIL_DOMAINS, excludeDomains=[]): email_candidates = [] if emails != None: email_candidates = emails elif emailsFile != None: # Reading the emails file with open(emailsFile, "r") as iF: ...
438,252
Method to perform the email search. Args: ----- platformNames: List of names of the platforms. emails: List of numbers to be queried. Return: ------- A list of verified emails.
def processMailList(platformNames=[], emails=[]): # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="mailfy") results = [] for e in emails: for pla in platforms: # This returns a json.txt! entities = pla.getInfo(...
438,253
A wrapper for being able to launch all the threads. We will use python-emailahoy library for the verification. Args: ----- args: reception of the parameters for getPageWrapper as a tuple. Returns: -------- A dictionary representing whether the verification was ended succes...
def pool_function(args): is_valid = True try: checker = emailahoy.VerifyEmail() status, message = checker.verify_email_smtp(args, from_host='gmail.com', from_email='sample@gmail.com') if status == 250: print("\t[*] Verification of '{}' status: {}. Details:\n\t\t{}".form...
438,254
Method to perform the mail verification process. Args: ----- emails: list of emails to be verified. platforms: list of strings representing the wrappers to be used. nThreads: the number of threads to be used. Default: 16 threads. secondsBeforeTimeout: number of seconds to wait b...
def performSearch(emails=[], nThreads=16, secondsBeforeTimeout=5): # Getting starting time _startTime = time.time() def hasRunOutOfTime(oldEpoch): now = time.time() return now - oldEpoch >= secondsBeforeTimeout results = [] args = [] # Grabbing all the emails th...
438,255
Public method to recover a resource. Args: ----- url: The URL to be collected. Returns: -------- Returns a resource that has to be read, for instance, with html = self.br.read()
def recoverURL(self, url): # Configuring user agents... self.setUserAgent() # Configuring proxies if "https://" in url: self.setProxy(protocol = "https") else: self.setProxy(protocol = "http") # Giving special treatment for .onion platfo...
438,259
Method to guess the usufy path against a list of domains or subdomains. Args: ----- fDomains: A list to strings containing the domains and (optionally) a nick. fFuzzStruct: A list to strings containing the transforms to be performed. Returns: -------- di...
def fuzzUsufy(fDomains = None, fFuzzStruct = None): if fFuzzStruct == None: # Loading these structures by default fuzzingStructures = [ "http://<DOMAIN>/<USERNAME>", "http://<DOMAIN>/~<USERNAME>", "http://<DOMAIN>/?action=profile;user=<USERNAME>", ...
438,278
Main function to launch alias_generator. Args: ----- params: A list with the parameters as grabbed by the terminal. It is None when this is called by an entry_point. If it is called by osrf the data is already parsed.
def main(params=None): if params == None: parser = getParser() args = parser.parse_args(params) else: args = params print(general.title(banner.text)) extraWords = args.extra_words try: if args.name == None and args.surname1 == None and args.surname2 == None an...
438,284
Main loop for the enumeration Args: ----- params: A list with the parameters as grabbed by the terminal. It is None when this is called by an entry_point.
def main(params=None): # Grabbing the parser parser = getParser() if params != None: args = parser.parse_args(params) else: args = parser.parse_args() print(general.title(banner.text)) sayingHello = + general.LICENSE_URL + "\n" print(general.info(sayingH...
438,343
Verifying a usufy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended.
def do_usufy(self, query, **kwargs): # Trying to interact with the API Wrapper try: self.wrapperAPI = TwitterAPIWrapper() results = self.wrapperAPI.get_user(query) for r in results: # Manually appending the URL aux = {} ...
438,344
Verifying a usufy query in this platform. This might be redefined in any class inheriting from Platform. Args: ----- query: The element to be searched. Return: ------- A list of elements to be appended.
def do_searchfy(self, query, **kwargs): # Trying to interact with the API Wrapper try: results = self.wrapperAPI.search_users(query) # Manually appending the URL for r in results: aux = {} aux["type"]="i3visio.uri" ...
438,345
Extend FieldsContainer.__init__ and set the record's sources and query_params_match attribute. Args: fields -- An iterable of fields (from osrframework.thirdparties.pipl_com.lib.fields). sources -- A list of Source objects (osrframework.thirdparties.pipl_com.lib.source....
def __init__(self, fields=None, sources=None, query_params_match=None): FieldsContainer.__init__(self, fields) self.sources = sources or [] self.query_params_match = query_params_match
438,367
Method to perform searchs on a series of numbers. Args: ----- platformNames: List of names of the platforms. numbers: List of numbers to be queried. excludePlatformNames: A list of platforms not to be searched. Return: ------- A list of verified emails.
def processPhoneList(platformNames=[], numbers=[], excludePlatformNames=[]): # Grabbing the <Platform> objects platforms = platform_selection.getPlatformsByName(platformNames, mode="phonefy", excludePlatformNames=excludePlatformNames) results = [] for num in numbers: for pla in platforms: ...
438,372
Method to create the URL replacing the word in the appropriate URL. Args: ----- word: Word to be searched. mode: Mode to be executed. Return: ------- The URL to be queried.
def createURL(self, word, mode="phonefy"): try: return self.modes[mode]["url"].format(placeholder=urllib.pathname2url(word)) except: if mode == "base": if word[0] == "/": return self.baseURL+word[1:], word else: ...
438,374
Method that launches an i3Browser to collect data. Args: ----- query: The query to be performed mode: The mode to be used to build the query. Return: ------- A string containing the recovered data or None.
def launchQueryForMode(self, query=None, mode=None): # Creating the query URL for that mode qURL = self.createURL(word=query, mode=mode) i3Browser = browser.Browser() try: # Check if it needs creds if self.needsCredentials[mode]: self._ge...
438,375
Verification of whether the mode is a correct option to be used. Args: ----- mode: Mode to be executed. Return: ------- True if the mode exists in the three main folders.
def _modeIsValid(self, mode): try: # Suport for version 2 of wrappers return mode in self.modes.keys() except AttributeError as e: # Legacy for mantaining old wrappers if mode in self.isValidMode.keys(): if mode in self.isValidMode...
438,377
Method to verify if a given query is processable by the platform. The system looks for the forbidden characters in self.Forbidden list. Args: ----- query: The query to be launched. mode: To be chosen amongst mailfy, phonefy, usufy, searchfy. Return: ----...
def _isValidQuery(self, query, mode="phonefy"): try: # Suport for version 2 of wrappers validator = self.modes[mode].get("query_validator") if validator: try: compiledRegexp = re.compile( "^{expr}$".format( ...
438,379
Verifying if something was found. Args: ----- data: Data where the self.notFoundText will be searched. mode: Mode to be executed. Return: ------- True if exists.
def _somethingFound(self, data, mode="phonefy"): if data: try: for text in self.notFoundText[mode]: if text in data: return False return True except AttributeError as e: # Update to versi...
438,380
Verifying a mailfy query in this platform. This might be redefined in any class inheriting from Platform. The only condition is that any of this should return a dictionary as defined. Args: ----- query: The element to be searched. kwargs: Dictionary with extra p...
def check_mailfy(self, query, kwargs={}): data = self.launchQueryForMode(query=query, mode="mailfy") if self._somethingFound(data, mode="mailfy"): return data return None
438,381