Search is not available for this dataset
text
stringlengths
75
104k
def set_runtime_config(name, value): """ Configures system behavior at runtime. These configuration values are also read from environment variables at program startup if available. See :py:func:`turicreate.config.get_runtime_config()` to get the current values for each variable. Note that defau...
def load_sgraph(filename, format='binary', delimiter='auto'): """ Load SGraph from text file or previously saved SGraph binary. Parameters ---------- filename : string Location of the file. Can be a local path or a remote URL. format : {'binary', 'snap', 'csv', 'tsv'}, optional ...
def _vertex_list_to_dataframe(ls, id_column_name): """ Convert a list of vertices into dataframe. """ assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) df = pd.DataFrame({id_column_name: [v....
def _vertex_list_to_sframe(ls, id_column_name): """ Convert a list of vertices into an SFrame. """ sf = SFrame() if type(ls) == list: cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) sf[id_column_name] = [v.vid for v in ls] for c in cols: sf[c] = [v.att...
def _edge_list_to_dataframe(ls, src_column_name, dst_column_name): """ Convert a list of edges into dataframe. """ assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.' cols = reduce(set.union, (set(e.attr.keys()) for e in ls)) df = pd.DataFrame({ ...
def _edge_list_to_sframe(ls, src_column_name, dst_column_name): """ Convert a list of edges into an SFrame. """ sf = SFrame() if type(ls) == list: cols = reduce(set.union, (set(v.attr.keys()) for v in ls)) sf[src_column_name] = [e.src_vid for e in ls] sf[dst_column_name] = [...
def _dataframe_to_vertex_list(df): """ Convert dataframe into list of vertices, assuming that vertex ids are stored in _VID_COLUMN. """ cols = df.columns if len(cols): assert _VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _VID_COLUMN df = df[cols].T ret = [V...
def _dataframe_to_edge_list(df): """ Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN respectively. """ cols = df.columns if len(cols): assert _SRC_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _SRC...
def _vertex_data_to_sframe(data, vid_field): """ Convert data into a vertex data sframe. Using vid_field to identify the id column. The returned sframe will have id column name '__id'. """ if isinstance(data, SFrame): # '__id' already in the sframe, and it is ok to not specify vid_field ...
def _edge_data_to_sframe(data, src_field, dst_field): """ Convert data into an edge data sframe. Using src_field and dst_field to identify the source and target id column. The returned sframe will have id column name '__src_id', '__dst_id' """ if isinstance(data, SFrame): # '__src_vid' a...
def get_vertices(self, ids=[], fields={}, format='sframe'): """ get_vertices(self, ids=list(), fields={}, format='sframe') Return a collection of vertices and their attributes. Parameters ---------- ids : list [int | float | str] or SArray List of vertex IDs...
def get_edges(self, src_ids=[], dst_ids=[], fields={}, format='sframe'): """ get_edges(self, src_ids=list(), dst_ids=list(), fields={}, format='sframe') Return a collection of edges and their attributes. This function is used to find edges by vertex IDs, filter on edge attributes, or lis...
def add_vertices(self, vertices, vid_field=None): """ Add vertices to the SGraph. Vertices should be input as a list of :class:`~turicreate.Vertex` objects, an :class:`~turicreate.SFrame`, or a pandas DataFrame. If vertices are specified by SFrame or DataFrame, ``vid_field`` spec...
def add_edges(self, edges, src_field=None, dst_field=None): """ Add edges to the SGraph. Edges should be input as a list of :class:`~turicreate.Edge` objects, an :class:`~turicreate.SFrame`, or a Pandas DataFrame. If the new edges are in an SFrame or DataFrame, then ``src_field``...
def select_fields(self, fields): """ Return a new SGraph with only the selected fields. Other fields are discarded, while fields that do not exist in the SGraph are ignored. Parameters ---------- fields : string | list [string] A single field name or a list o...
def triple_apply(self, triple_apply_fn, mutated_fields, input_fields=None): ''' Apply a transform function to each edge and its associated source and target vertices in parallel. Each edge is visited once and in parallel. Modification to vertex data is protected by lock. The effect on th...
def save(self, filename, format='auto'): """ Save the SGraph to disk. If the graph is saved in binary format, the graph can be re-loaded using the :py:func:`load_sgraph` method. Alternatively, the SGraph can be saved in JSON format for a human-readable and portable representation...
def get_neighborhood(self, ids, radius=1, full_subgraph=True): """ Retrieve the graph neighborhood around a set of vertices, ignoring edge directions. Note that setting radius greater than two often results in a time-consuming query for a very large subgraph. Parameters ...
def create(dataset, target, features=None, max_iterations=10, validation_set='auto', class_weights = None, max_depth=6, step_size=0.3, min_loss_reduction=0.0, min_child_weight=0.1, row_subsample=1.0, column_subsample=1.0, verbose=True, ...
def classify(self, dataset, missing_value_action='auto'): """ Return a classification, for each example in the ``dataset``, using the trained boosted trees model. The output SFrame contains predictions as class labels (0 or 1) and probabilities associated with the the example. P...
def export_coreml(self, filename): """ Export the model in Core ML format. Parameters ---------- filename: str A valid filename where the model can be saved. Examples -------- >>> model.export_coreml("MyModel.mlmodel") """ from ...
def _get(self, field): """ Return the value for the queried field. Get the value of a given field. The list of all queryable fields is documented in the beginning of the model class. >>> out = m._get('graph') Parameters ---------- field : string ...
def _describe_fields(cls): """ Return a dictionary for the class fields description. Fields should NOT be wrapped by _precomputed_field, if necessary """ dispatch_table = { 'ShortestPathModel': 'sssp', 'GraphColoringModel': 'graph_coloring', 'P...
def _get_summary_struct(self): """ Returns a structured description of the model, including (where relevant) the schema of the training data, description of the training data, training statistics, and model hyperparameters. Returns ------- sections : list (of lis...
def _raise_error_if_not_of_type(arg, expected_type, arg_name=None): """ Check if the input is of expected type. Parameters ---------- arg : Input argument. expected_type : A type OR a list of types that the argument is expected to be. arg_name : The n...
def waveform_to_examples(data, sample_rate): """Converts audio waveform into an array of examples for VGGish. Args: data: np.array of either one dimension (mono) or two dimensions (multi-channel, with the outer dimension representing channels). Each sample is generally expected to lie in the range ...
def wavfile_to_examples(wav_file): """Convenience wrapper around waveform_to_examples() for a common WAV format. Args: wav_file: String path to a file, or a file-like object. The file is assumed to contain WAV audio data with signed 16-bit PCM samples. Returns: See waveform_to_examples. """ from...
def expand_no_defaults (property_sets): """ Expand the given build request by combining all property_sets which don't specify conflicting non-free features. """ assert is_iterable_typed(property_sets, property_set.PropertySet) # First make all features and subfeatures explicit expanded_prope...
def __x_product (property_sets): """ Return the cross-product of all elements of property_sets, less any that would contain conflicting values for single-valued features. """ assert is_iterable_typed(property_sets, property_set.PropertySet) x_product_seen = set() return __x_product_aux (prop...
def __x_product_aux (property_sets, seen_features): """Returns non-conflicting combinations of property sets. property_sets is a list of PropertySet instances. seen_features is a set of Property instances. Returns a tuple of: - list of lists of Property instances, such that within each list, no tw...
def looks_like_implicit_value(v): """Returns true if 'v' is either implicit value, or the part before the first '-' symbol is implicit value.""" assert isinstance(v, basestring) if feature.is_implicit_value(v): return 1 else: split = v.split("-") if feature.is_implicit_value(...
def from_command_line(command_line): """Takes the command line tokens (such as taken from ARGV rule) and constructs build request from it. Returns a list of two lists. First is the set of targets specified in the command line, and second is the set of requested build properties.""" assert is_iterabl...
def regex_to_error_msg(regex): """Format a human-readable error message from a regex""" return re.sub('([^\\\\])[()]', '\\1', regex) \ .replace('[ \t]*$', '') \ .replace('^', '') \ .replace('$', '') \ .replace('[ \t]*', ' ') \ .replace('[ \t]+', ' ') \ .replace('[...
def random_chars(number): """Generate random characters""" char_map = { k: v for k, v in chars.CHARS.iteritems() if not format_character(k).startswith('\\x') } char_num = sum(char_map.values()) return ( format_character(nth_char(char_map, random.randint(0, char_num - 1))) ...
def templates_in(path): """Enumerate the templates found in path""" ext = '.cpp' return ( Template(f[0:-len(ext)], load_file(os.path.join(path, f))) for f in os.listdir(path) if f.endswith(ext) )
def nth_char(char_map, index): """Returns the nth character of a character->occurrence map""" for char in char_map: if index < char_map[char]: return char index = index - char_map[char] return None
def format_character(char): """Returns the C-formatting of the character""" if \ char in string.ascii_letters \ or char in string.digits \ or char in [ '_', '.', ':', ';', ' ', '!', '?', '+', '-', '/', '=', '<', '>', '$', '(', ')', '@', '~', '`', '|', '#',...
def write_file(filename, content): """Create the file with the given content""" print 'Generating {0}'.format(filename) with open(filename, 'wb') as out_f: out_f.write(content)
def out_filename(template, n_val, mode): """Determine the output filename""" return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier)
def main(): """The main function of the script""" desc = 'Generate files to benchmark' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='src', help='The directory containing the templates' ) parser.add_argume...
def convert_from(self, base): """Convert a BOOST_METAPARSE_STRING mode document into one with this mode""" if self.identifier == 'bmp': return base elif self.identifier == 'man': result = [] prefix = 'BOOST_METAPARSE_STRING("' while True: ...
def instantiate(self, value_of_n): """Instantiates the template""" template = Cheetah.Template.Template( self.content, searchList={'n': value_of_n} ) template.random_string = random_string return str(template)
def range(self): """Returns the range for N""" match = self._match(in_comment( 'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+' 'step[ \t]+([0-9]+)' )) return range( int(match.group(1)), int(match.group(2)), int(match.group(...
def _match(self, regex): """Find the first line matching regex and return the match object""" cregex = re.compile(regex) for line in self.content.splitlines(): match = cregex.match(line) if match: return match raise Exception('No "{0}" line in {1}....
def add_model(self, spec): """ Add a protobuf spec or :py:class:`models.MLModel` instance to the pipeline. All input features of this model must either match the input_features of the pipeline, or match the outputs of a previous model. Parameters ---------- spec...
def GetVersion(): """Gets the version from google/protobuf/__init__.py Do not import google.protobuf.__init__ directly, because an installed protobuf library may be loaded instead.""" with open(os.path.join('google', 'protobuf', '__init__.py')) as version_file: exec(version_file.read(), globals()) ret...
def generate_proto(source, require = True): """Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output already exists and is newer than the input.""" if not require and not os.path.exists(source): return output = source.replace(".proto", "_pb2.py").rep...
def _validate_row_label(label, column_type_map): """ Validate a row label column. Parameters ---------- label : str Name of the row label column. column_type_map : dict[str, type] Dictionary mapping the name of each column in an SFrame to the type of the values in the c...
def _robust_column_name(base_name, column_names): """ Generate a new column name that is guaranteed not to conflict with an existing set of column names. Parameters ---------- base_name : str The base of the new column name. Usually this does not conflict with the existing colum...
def _select_valid_features(dataset, features, valid_feature_types, target_column=None): """ Utility function for selecting columns of only valid feature types. Parameters ---------- dataset: SFrame The input SFrame containing columns of potential features. fe...
def _check_elements_equal(lst): """ Returns true if all of the elements in the list are equal. """ assert isinstance(lst, list), "Input value must be a list." return not lst or lst.count(lst[0]) == len(lst)
def _validate_lists(sa, allowed_types=[str], require_same_type=True, require_equal_length=False, num_to_check=10): """ For a list-typed SArray, check whether the first elements are lists that - contain only the provided types - all have the same lengths (optionally) Parameters ...
def _summarize_accessible_fields(field_descriptions, width=40, section_title='Accessible fields'): """ Create a summary string for the accessible fields in a model. Unlike `_toolkit_repr_print`, this function does not look up the values of the fields, it just formats the...
def _is_valid_datatype(datatype_instance): """ Returns true if datatype_instance is a valid datatype object and false otherwise. """ # Remap so we can still use the python types for the simple cases global _simple_type_remap if datatype_instance in _simple_type_remap: return True #...
def _normalize_datatype(datatype_instance): """ Translates a user specified datatype to an instance of the ones defined above. Valid data types are passed through, and the following type specifications are translated to the proper instances: str, "String" -> String() int, "Int64" -> Int64() ...
def convert(model, feature_names, target): """Convert a boosted tree model to protobuf format. Parameters ---------- decision_tree : GradientBoostingClassifier A trained scikit-learn tree model. feature_names: [str] Name of the input columns. target: str Name of the ou...
def get_symbols(node, ctx_types=(ast.Load, ast.Store)): ''' Returns all symbols defined in an ast node. if ctx_types is given, then restrict the symbols to ones with that context. :param node: ast node :param ctx_types: type or tuple of types that may be found assigned to the `ctx` attrib...
def order (self, objects): """ Given a list of objects, reorder them so that the constains specified by 'add_pair' are satisfied. The algorithm was adopted from an awk script by Nikita Youshchenko (yoush at cs dot msu dot su) """ # The algorithm used is the s...
def __eliminate_unused_constraits (self, objects): """ Eliminate constraints which mention objects not in 'objects'. In graph-theory terms, this is finding subgraph induced by ordered vertices. """ result = [] for c in self.constraints_: if c [0] in ob...
def __has_no_dependents (self, obj, constraints): """ Returns true if there's no constraint in 'constraints' where 'obj' comes second. """ failed = False while constraints and not failed: c = constraints [0] if c [1] == obj: failed = T...
def path_order (x, y): """ Helper for as_path, below. Orders properties with the implicit ones first, and within the two sections in alphabetical order of feature name. """ if x == y: return 0 xg = get_grist (x) yg = get_grist (y) if yg and not xg: return -1 ...
def refine (properties, requirements): """ Refines 'properties' by overriding any non-free properties for which a different value is specified in 'requirements'. Conditional requirements are just added without modification. Returns the resulting list of properties. """ assert is_iter...
def translate_paths (properties, path): """ Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-specific form, and will be translated into normalized form. """ assert is_iterable_typed(properties, Property) result = [] ...
def translate_indirect(properties, context_module): """Assumes that all feature values that start with '@' are names of rules, used in 'context-module'. Such rules can be either local to the module or global. Qualified local rules with the name of the module.""" assert is_iterable_typed(properties, ...
def validate (properties): """ Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. """ if isinstance(properties, Property): properties = [properties] assert is_iterable_typed(properties, Property) for p in properties...
def split_conditional (property): """ If 'property' is conditional property, returns condition and the property, e.g <variant>debug,<toolset>gcc:<inlining>full will become <variant>debug,<toolset>gcc <inlining>full. Otherwise, returns empty string. """ assert isinstance(prope...
def select (features, properties): """ Selects properties which correspond to any of the given features. """ assert is_iterable_typed(properties, basestring) result = [] # add any missing angle brackets features = add_grist (features) return [p for p in properties if get_grist(p) in featur...
def evaluate_conditionals_in_context (properties, context): """ Removes all conditional properties which conditions are not met For those with met conditions, removes the condition. Properies in conditions are looked up in 'context' """ if __debug__: from .property_set import Propert...
def change (properties, feature, value = None): """ Returns a modified version of properties with all values of the given feature replaced by the given value. If 'value' is None the feature will be removed. """ assert is_iterable_typed(properties, basestring) assert isinstance(feature, b...
def __validate1 (property): """ Exit with error if property is not valid. """ assert isinstance(property, Property) msg = None if not property.feature.free: feature.validate_value_string (property.feature, property.value)
def remove(attributes, properties): """Returns a property sets which include all the elements in 'properties' that do not have attributes listed in 'attributes'.""" if isinstance(attributes, basestring): attributes = [attributes] assert is_iterable_typed(attributes, basestring) assert is_ite...
def take(attributes, properties): """Returns a property set which include all properties in 'properties' that have any of 'attributes'.""" assert is_iterable_typed(attributes, basestring) assert is_iterable_typed(properties, basestring) result = [] for e in properties: if b2.util.set.int...
def insert (self, properties, value): """ Associate value with properties. """ assert is_iterable_typed(properties, basestring) assert isinstance(value, basestring) self.__properties.append(properties) self.__values.append(value)
def benchmark_command(cmd, progress): """Benchmark one command execution""" full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd) print '{0:6.2f}% Running {1}'.format(100.0 * progress, full_cmd) (_, err) = subprocess.Popen( ['/bin/sh', '-c', full_cmd], stdin=subprocess.PIPE, ...
def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ''): """Benchmark one file""" time_sum = 0 mem_sum = 0 for nth_run in xrange(0, iter_count): (time_spent, mem_used) = benchmark_command( '{0} -std=c++11 {1} -...
def compiler_info(compiler): """Determine the name + version of the compiler""" (out, err) = subprocess.Popen( ['/bin/sh', '-c', '{0} -v'.format(compiler)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ).communicate('') gcc_clang = re.compile('(g...
def files_in_dir(path, extension): """Enumartes the files in path with the given extension""" ends = '.{0}'.format(extension) return (f for f in os.listdir(path) if f.endswith(ends))
def format_time(seconds): """Format a duration""" minute = 60 hour = minute * 60 day = hour * 24 week = day * 7 result = [] for name, dur in [ ('week', week), ('day', day), ('hour', hour), ('minute', minute), ('second', 1) ]: if seconds > dur: ...
def benchmark(src_dir, compiler, include_dirs, iter_count): """Do the benchmarking""" files = list(files_in_dir(src_dir, 'cpp')) random.shuffle(files) has_string_templates = True string_template_file_cnt = sum(1 for file in files if 'bmp' in file) file_count = len(files) + string_template_file_...
def plot(values, mode_names, title, (xlabel, ylabel), out_file): """Plot a diagram""" matplotlib.pyplot.clf() for mode, mode_name in mode_names.iteritems(): vals = values[mode] matplotlib.pyplot.plot( [x for x, _ in vals], [y for _, y in vals], label=mode_...
def configs_in(src_dir): """Enumerate all configs in src_dir""" for filename in files_in_dir(src_dir, 'json'): with open(os.path.join(src_dir, filename), 'rb') as in_f: yield json.load(in_f)
def join_images(img_files, out_file): """Join the list of images into the out file""" images = [PIL.Image.open(f) for f in img_files] joined = PIL.Image.new( 'RGB', (sum(i.size[0] for i in images), max(i.size[1] for i in images)) ) left = 0 for img in images: joined.paste...
def plot_temp_diagrams(config, results, temp_dir): """Plot temporary diagrams""" display_name = { 'time': 'Compilation time (s)', 'memory': 'Compiler memory usage (MB)', } files = config['files'] img_files = [] if any('slt' in result for result in results) and 'bmp' in files.va...
def plot_diagram(config, results, images_dir, out_filename): """Plot one diagram""" img_files = plot_temp_diagrams(config, results, images_dir) join_images(img_files, out_filename) for img_file in img_files: os.remove(img_file)
def plot_diagrams(results, configs, compiler, out_dir): """Plot all diagrams specified by the configs""" compiler_fn = make_filename(compiler) total = psutil.virtual_memory().total # pylint:disable=I0011,E1101 memory = int(math.ceil(byte_to_gb(total))) images_dir = os.path.join(out_dir, 'images') ...
def main(): """The main function of the script""" desc = 'Benchmark the files generated by generate.py' parser = argparse.ArgumentParser(description=desc) parser.add_argument( '--src', dest='src_dir', default='generated', help='The directory containing the sources to benc...
def load_model(location): """ Load any Turi Create model that was previously saved. This function assumes the model (can be any model) was previously saved in Turi Create model format with model.save(filename). Parameters ---------- location : string Location of the model to load. ...
def _get_default_options_wrapper(unity_server_model_name, module_name='', python_class_name='', sdk_model = False): """ Internal function to return a get_default_options function. Parameters ---------- u...
def reset (): """ Clear the module state. This is mainly for testing purposes. Note that this must be called _after_ resetting the module 'feature'. """ global __had_unspecified_value, __had_value, __declared_subfeature global __init_loc global __all_signatures, __debug_configuration, __show...
def check_init_parameters(toolset, requirement, *args): """ The rule for checking toolset parameters. Trailing parameters should all be parameter name/value pairs. The rule will check that each parameter either has a value in each invocation or has no value in each invocation. Also, the rule ...
def get_invocation_command_nodefault( toolset, tool, user_provided_command=[], additional_paths=[], path_last=False): """ A helper rule to get the command to invoke some tool. If 'user-provided-command' is not given, tries to find binary named 'tool' in PATH and in the passed 'additional...
def get_invocation_command(toolset, tool, user_provided_command = [], additional_paths = [], path_last = False): """ Same as get_invocation_command_nodefault, except that if no tool is found, returns either the user-provided-command, if present, or the 'tool' parameter. """ ...
def get_absolute_tool_path(command): """ Given an invocation command, return the absolute path to the command. This works even if commnad has not path element and is present in PATH. """ assert isinstance(command, basestring) if os.path.dirname(command): return os.path.di...
def find_tool(name, additional_paths = [], path_last = False): """ Attempts to find tool (binary) named 'name' in PATH and in 'additional-paths'. If found in path, returns 'name'. If found in additional paths, returns full name. If the tool is found in several directories, returns the fir...
def check_tool_aux(command): """ Checks if 'command' can be found either in path or is a full name to an existing file. """ assert isinstance(command, basestring) dirname = os.path.dirname(command) if dirname: if os.path.exists(command): return command # Both NT a...
def check_tool(command): """ Checks that a tool can be invoked by 'command'. If command is not an absolute path, checks if it can be found in 'path'. If comand is absolute path, check that it exists. Returns 'command' if ok and empty string otherwise. """ assert is_iterable_typed(com...
def handle_options(tool, condition, command, options): """ Handle common options for toolset, specifically sets the following flag variables: - CONFIG_COMMAND to 'command' - OPTIOns for compile to the value of <compileflags> in options - OPTIONS for compile.c to the value of <cflags>...
def get_program_files_dir(): """ returns the location of the "program files" directory on a windows platform """ ProgramFiles = bjam.variable("ProgramFiles") if ProgramFiles: ProgramFiles = ' '.join(ProgramFiles) else: ProgramFiles = "c:\\Program Files" return ProgramFile...
def variable_setting_command(variable, value): """ Returns the command needed to set an environment variable on the current platform. The variable setting persists through all following commands and is visible in the environment seen by subsequently executed commands. In other words,...
def path_variable_setting_command(variable, paths): """ Returns a command to sets a named shell path variable to the given NATIVE paths on the current platform. """ assert isinstance(variable, basestring) assert is_iterable_typed(paths, basestring) sep = os.path.pathsep return va...