INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a new SArray that represents a fixed frequency datetime index.
def date_range(cls,start_time,end_time,freq): ''' Returns a new SArray that represents a fixed frequency datetime index. Parameters ---------- start_time : datetime.datetime Left bound for generating dates. end_time : datetime.datetime Right bound fo...
Constructs an SArray of size with a const value.
def from_const(cls, value, size, dtype=type(None)): """ Constructs an SArray of size with a const value. Parameters ---------- value : [int | float | str | array.array | list | dict | datetime] The value to fill the SArray size : int The size of the S...
from_sequence ( start = 0 stop )
def from_sequence(cls, *args): """ from_sequence(start=0, stop) Create an SArray from sequence .. sourcecode:: python Construct an SArray of integer values from 0 to 999 >>> tc.SArray.from_sequence(1000) This is equivalent, but more efficient than...
Construct an SArray from a json file or glob of json files. The json file must contain a list of dictionaries. The returned SArray type will be of dict type
def read_json(cls, filename): """ Construct an SArray from a json file or glob of json files. The json file must contain a list of dictionaries. The returned SArray type will be of dict type Parameters ---------- filename : str The filename or glob to l...
Selects elements from either istrue or isfalse depending on the value of the condition SArray.
def where(cls, condition, istrue, isfalse, dtype=None): """ Selects elements from either istrue or isfalse depending on the value of the condition SArray. Parameters ---------- condition : SArray An SArray of values such that for each value, if non-zero, yields a...
Saves the SArray to file.
def save(self, filename, format=None): """ Saves the SArray to file. The saved SArray will be in a directory named with the `targetfile` parameter. Parameters ---------- filename : string A local path or a remote URL. If format is 'text', it will be...
If this SArray contains vectors or lists this returns a new SArray containing each individual element sliced between start and end ( exclusive ).
def vector_slice(self, start, end=None): """ If this SArray contains vectors or lists, this returns a new SArray containing each individual element sliced, between start and end (exclusive). Parameters ---------- start : int The start position of the ...
This returns an SArray with each element sliced accordingly to the slice specified. This is conceptually equivalent to:
def element_slice(self, start=None, stop=None, step=None): """ This returns an SArray with each element sliced accordingly to the slice specified. This is conceptually equivalent to: >>> g.apply(lambda x: x[start:step:stop]) The SArray must be of type list, vector, or string. ...
This returns an SArray with for each input string a dict from the unique delimited substrings to their number of occurrences within the original string.
def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]): """ This returns an SArray with, for each input string, a dict from the unique, delimited substrings to their number of occurrences within the original string. The SArray must be of type strin...
For documentation see turicreate. text_analytics. count_ngrams ().
def _count_ngrams(self, n=2, method="word", to_lower=True, ignore_space=True): """ For documentation, see turicreate.text_analytics.count_ngrams(). ..WARNING:: This function is deprecated, and will be removed in future versions of Turi Create. Please use the `text_analytics.count_words`...
Filter an SArray of dictionary type by the given keys. By default all keys that are in the provided list in keys are * excluded * from the returned SArray.
def dict_trim_by_keys(self, keys, exclude=True): """ Filter an SArray of dictionary type by the given keys. By default, all keys that are in the provided list in ``keys`` are *excluded* from the returned SArray. Parameters ---------- keys : list A col...
Filter dictionary values to a given range ( inclusive ). Trimming is only performed on values which can be compared to the bound values. Fails on SArrays whose data type is not dict.
def dict_trim_by_values(self, lower=None, upper=None): """ Filter dictionary values to a given range (inclusive). Trimming is only performed on values which can be compared to the bound values. Fails on SArrays whose data type is not ``dict``. Parameters ---------- ...
Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element s dictionary has any of the given keys. Fails on SArrays whose data type is not dict.
def dict_has_any_keys(self, keys): """ Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has any of the given keys. Fails on SArrays whose data type is not ``dict``. ...
Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element s dictionary has all of the given keys. Fails on SArrays whose data type is not dict.
def dict_has_all_keys(self, keys): """ Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the corresponding input element's dictionary has all of the given keys. Fails on SArrays whose data type is not ``dict``. ...
apply ( fn dtype = None skip_na = True seed = None )
def apply(self, fn, dtype=None, skip_na=True, seed=None): """ apply(fn, dtype=None, skip_na=True, seed=None) Transform each element of the SArray by a given function. The result SArray is of type ``dtype``. ``fn`` should be a function that returns exactly one value which can be ...
Filter this SArray by a function.
def filter(self, fn, skip_na=True, seed=None): """ Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element to true, this element is copied to the new SArray. If not, it isn't. Throws an exception if the return type of `fn` is...
Create an SArray which contains a subsample of the current SArray.
def sample(self, fraction, seed=None, exact=False): """ Create an SArray which contains a subsample of the current SArray. Parameters ---------- fraction : float Fraction of the rows to fetch. Must be between 0 and 1. if exact is False (default), the numb...
Returns an SArray with a hash of each element. seed can be used to change the hash function to allow this method to be used for random number generation.
def hash(self, seed=0): """ Returns an SArray with a hash of each element. seed can be used to change the hash function to allow this method to be used for random number generation. Parameters ---------- seed : int Defaults to 0. Can be changed to dif...
Returns an SArray with random integer values.
def random_integers(cls, size, seed=None): """ Returns an SArray with random integer values. """ if seed is None: seed = abs(hash("%0.20f" % time.time())) % (2 ** 31) return cls.from_sequence(size).hash(seed)
Get the index of the minimum numeric value in SArray.
def argmin(self): """ Get the index of the minimum numeric value in SArray. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type. Returns ------- out : int index of the minimum value of SArray See...
Mean of all the values in the SArray or mean image.
def mean(self): """ Mean of all the values in the SArray, or mean image. Returns None on an empty SArray. Raises an exception if called on an SArray with non-numeric type or non-Image type. Returns ------- out : float | turicreate.Image Mean of all v...
Create a new SArray with all the values cast to str. The string format is specified by the format parameter.
def datetime_to_str(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to str. The string format is specified by the 'format' parameter. Parameters ---------- format : str The format to output the string. Default format is "...
Create a new SArray with all the values cast to datetime. The string format is specified by the format parameter.
def str_to_datetime(self,format="%Y-%m-%dT%H:%M:%S%ZP"): """ Create a new SArray with all the values cast to datetime. The string format is specified by the 'format' parameter. Parameters ---------- format : str The string format of the input SArray. Default ...
Create a new SArray with all the values cast to: py: class: turicreate. image. Image of uniform size.
def pixel_array_to_image(self, width, height, channels, undefined_on_failure=True, allow_rounding=False): """ Create a new SArray with all the values cast to :py:class:`turicreate.image.Image` of uniform size. Parameters ---------- width: int The width of the...
Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type.
def astype(self, dtype, undefined_on_failure=False): """ Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type. Parameters ---------- dtype : {int, float, str, list, array.array, dict, datetime.dat...
Create a new SArray with each value clipped to be within the given bounds.
def clip(self, lower=float('nan'), upper=float('nan')): """ Create a new SArray with each value clipped to be within the given bounds. In this case, "clipped" means that values below the lower bound will be set to the lower bound value. Values above the upper bound will be set ...
Create new SArray with all values clipped to the given lower bound. This function can operate on numeric arrays as well as vector arrays in which case each individual element in each vector is clipped. Throws an exception if the SArray is empty or the types are non - numeric.
def clip_lower(self, threshold): """ Create new SArray with all values clipped to the given lower bound. This function can operate on numeric arrays, as well as vector arrays, in which case each individual element in each vector is clipped. Throws an exception if the SArray is em...
Get an SArray that contains the last n elements in the SArray.
def tail(self, n=10): """ Get an SArray that contains the last n elements in the SArray. Parameters ---------- n : int The number of elements to fetch Returns ------- out : SArray A new SArray which contains the last n rows of the...
Create new SArray with all missing values ( None or NaN ) filled in with the given value.
def fillna(self, value): """ Create new SArray with all missing values (None or NaN) filled in with the given value. The size of the new SArray will be the same as the original SArray. If the given value is not the same type as the values in the SArray, `fillna` will att...
Create an SArray indicating which elements are in the top k.
def is_topk(self, topk=10, reverse=False): """ Create an SArray indicating which elements are in the top k. Entries are '1' if the corresponding element in the current SArray is a part of the top k elements, and '0' if that corresponding element is not. Order is descending by de...
Summary statistics that can be calculated with one pass over the SArray.
def summary(self, background=False, sub_sketch_keys=None): """ Summary statistics that can be calculated with one pass over the SArray. Returns a turicreate.Sketch object which can be further queried for many descriptive statistics over this SArray. Many of the statistics are ap...
Return an SFrame containing counts of unique values. The resulting SFrame will be sorted in descending frequency.
def value_counts(self): """ Return an SFrame containing counts of unique values. The resulting SFrame will be sorted in descending frequency. Returns ------- out : SFrame An SFrame containing 2 columns : 'value', and 'count'. The SFrame will be so...
Append an SArray to the current SArray. Creates a new SArray with the rows from both SArrays. Both SArrays must be of the same type.
def append(self, other): """ Append an SArray to the current SArray. Creates a new SArray with the rows from both SArrays. Both SArrays must be of the same type. Parameters ---------- other : SArray Another SArray whose rows are appended to current SArray. ...
Get all unique values in the current SArray.
def unique(self): """ Get all unique values in the current SArray. Raises a TypeError if the SArray is of dictionary type. Will not necessarily preserve the order of the given SArray in the new SArray. Returns ------- out : SArray A new SArray that ...
Visualize the SArray.
def show(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Visualize the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in `turicreate.visual...
Create a Plot object representing the SArray.
def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT): """ Create a Plot object representing the SArray. Notes ----- - The plot will render either inline in a Jupyter Notebook, or in a native GUI window, depending on the value provided in ...
Length of each element in the current SArray.
def item_length(self): """ Length of each element in the current SArray. Only works on SArrays of dict, array, or list type. If a given element is a missing value, then the output elements is also a missing value. This function is equivalent to the following but more performant:...
Randomly split the rows of an SArray into two SArrays. The first SArray contains * M * rows sampled uniformly ( without replacement ) from the original SArray. * M * is approximately the fraction times the original number of rows. The second SArray contains the remaining rows of the original SArray.
def random_split(self, fraction, seed=None): """ Randomly split the rows of an SArray into two SArrays. The first SArray contains *M* rows, sampled uniformly (without replacement) from the original SArray. *M* is approximately the fraction times the original number of rows. The s...
Splits an SArray of datetime type to multiple columns return a new SFrame that contains expanded columns. A SArray of datetime will be split by default into an SFrame of 6 columns one for each year/ month/ day/ hour/ minute/ second element.
def split_datetime(self, column_name_prefix = "X", limit=None, timezone=False): """ Splits an SArray of datetime type to multiple columns, return a new SFrame that contains expanded columns. A SArray of datetime will be split by default into an SFrame of 6 columns, one for each y...
Convert a wide SArray to one or two tall columns in an SFrame by stacking all values.
def stack(self, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" SArray to one or two "tall" columns in an SFrame by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two new columns a...
Convert an SArray of list array or dict type to an SFrame with multiple columns.
def unpack(self, column_name_prefix = "X", column_types=None, na_value=None, limit=None): """ Convert an SArray of list, array, or dict type to an SFrame with multiple columns. `unpack` expands an SArray using the values of each list/array/dict as elements in a new SFrame of mul...
Sort all values in this SArray.
def sort(self, ascending=True): """ Sort all values in this SArray. Sort only works for sarray of type str, int and float, otherwise TypeError will be raised. Creates a new, sorted SArray. Parameters ---------- ascending: boolean, optional If true, th...
Calculate a new SArray of the sum of different subsets over this SArray.
def rolling_sum(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the sum of different subsets over this SArray. Also known as a "moving sum" or "running sum". The subset that the sum is calculated over is defined as an inclusive range relativ...
Calculate a new SArray of the maximum value of different subsets over this SArray.
def rolling_max(self, window_start, window_end, min_observations=None): """ Calculate a new SArray of the maximum value of different subsets over this SArray. The subset that the maximum is calculated over is defined as an inclusive range relative to the position to each value i...
Count the number of non - NULL values of different subsets over this SArray.
def rolling_count(self, window_start, window_end): """ Count the number of non-NULL values of different subsets over this SArray. The subset that the count is executed on is defined as an inclusive range relative to the position to each value in the SArray, using `window...
Return the cumulative sum of the elements in the SArray.
def cumulative_sum(self): """ Return the cumulative sum of the elements in the SArray. Returns an SArray where each element in the output corresponds to the sum of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or a numeri...
Return the cumulative mean of the elements in the SArray.
def cumulative_mean(self): """ Return the cumulative mean of the elements in the SArray. Returns an SArray where each element in the output corresponds to the mean value of all the elements preceding and including it. The SArray is expected to be of numeric type (int, float), or...
Return the cumulative minimum value of the elements in the SArray.
def cumulative_min(self): """ Return the cumulative minimum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the minimum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int,...
Return the cumulative maximum value of the elements in the SArray.
def cumulative_max(self): """ Return the cumulative maximum value of the elements in the SArray. Returns an SArray where each element in the output corresponds to the maximum value of all the elements preceding and including it. The SArray is expected to be of numeric type (int,...
Return the cumulative standard deviation of the elements in the SArray.
def cumulative_std(self): """ Return the cumulative standard deviation of the elements in the SArray. Returns an SArray where each element in the output corresponds to the standard deviation of all the elements preceding and including it. The SArray is expected to be of numeric ...
Return the cumulative variance of the elements in the SArray.
def cumulative_var(self): """ Return the cumulative variance of the elements in the SArray. Returns an SArray where each element in the output corresponds to the variance of all the elements preceding and including it. The SArray is expected to be of numeric type, or a numeric v...
Filter an SArray by values inside an iterable object. The result is an SArray that only includes ( or excludes ) the values in the given values: class: ~turicreate. SArray. If values is not an SArray we attempt to convert it to one before filtering. Parameters ---------- values: SArray | list | numpy. ndarray | pandas....
def filter_by(self, values, exclude=False): """ Filter an SArray by values inside an iterable object. The result is an SArray that only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`. If ``values`` is not an SArray, we attempt to convert it...
Run the doxygen make command in the designated folder.
def run_build_lib(folder): """Run the doxygen make command in the designated folder.""" try: retcode = subprocess.call("cd %s; make" % folder, shell=True) retcode = subprocess.call("rm -rf _build/html/doxygen", shell=True) retcode = subprocess.call("mkdir _build", shell=True) ret...
Run the doxygen make commands if we re on the ReadTheDocs server
def generate_doxygen_xml(app): """Run the doxygen make commands if we're on the ReadTheDocs server""" read_the_docs_build = os.environ.get('READTHEDOCS', None) == 'True' if read_the_docs_build: run_doxygen('..') sys.stderr.write('Check if shared lib exists\n') run_build_lib('..') ...
Converts protobuf message to JSON format.
def MessageToJson(message, including_default_value_fields=False, preserving_proto_field_name=False): """Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitiv...
Converts protobuf message to a JSON dictionary.
def MessageToDict(message, including_default_value_fields=False, preserving_proto_field_name=False): """Converts protobuf message to a JSON dictionary. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular pr...
Parses a JSON dictionary representation into a message.
def ParseDict(js_dict, message, ignore_unknown_fields=False): """Parses a JSON dictionary representation into a message. Args: js_dict: Dict representation of a JSON message. message: A protocol buffer message to merge into. ignore_unknown_fields: If True, do not raise errors for unknown fields. Ret...
Convert a single scalar field value.
def _ConvertScalarFieldValue(value, field, require_str=False): """Convert a single scalar field value. Args: value: A scalar value to convert the scalar field value. field: The descriptor of the field to convert. require_str: If True, the field value must be a str. Returns: The converted scalar ...
Convert an integer.
def _ConvertInteger(value): """Convert an integer. Args: value: A scalar value to convert. Returns: The integer value. Raises: ParseError: If an integer couldn't be consumed. """ if isinstance(value, float) and not value.is_integer(): raise ParseError('Couldn\'t parse integer: {0}.'.forma...
Convert an floating point number.
def _ConvertFloat(value): """Convert an floating point number.""" if value == 'nan': raise ParseError('Couldn\'t parse float "nan", use "NaN" instead.') try: # Assume Python compatible syntax. return float(value) except ValueError: # Check alternative spellings. if value == _NEG_INFINITY: ...
Convert a boolean value.
def _ConvertBool(value, require_str): """Convert a boolean value. Args: value: A scalar value to convert. require_str: If True, value must be a str. Returns: The bool parsed. Raises: ParseError: If a boolean value couldn't be consumed. """ if require_str: if value == 'true': ret...
Converts message to an object according to Proto3 JSON Specification.
def _MessageToJsonObject(self, message): """Converts message to an object according to Proto3 JSON Specification.""" message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): return self._WrapperMessageToJsonObject(message) if fu...
Converts normal message according to Proto3 JSON Specification.
def _RegularMessageToJsonObject(self, message, js): """Converts normal message according to Proto3 JSON Specification.""" fields = message.ListFields() try: for field, value in fields: if self.preserving_proto_field_name: name = field.name else: name = field.json_n...
Converts field value according to Proto3 JSON Specification.
def _FieldToJsonObject(self, field, value): """Converts field value according to Proto3 JSON Specification.""" if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: return self._MessageToJsonObject(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: enum_value = fie...
Converts Any message according to Proto3 JSON Specification.
def _AnyMessageToJsonObject(self, message): """Converts Any message according to Proto3 JSON Specification.""" if not message.ListFields(): return {} # Must print @type first, use OrderedDict instead of {} js = OrderedDict() type_url = message.type_url js['@type'] = type_url sub_messag...
Converts Value message according to Proto3 JSON Specification.
def _ValueMessageToJsonObject(self, message): """Converts Value message according to Proto3 JSON Specification.""" which = message.WhichOneof('kind') # If the Value message is not set treat as null_value when serialize # to JSON. The parse back result will be different from original message. if whic...
Converts Struct message according to Proto3 JSON Specification.
def _StructMessageToJsonObject(self, message): """Converts Struct message according to Proto3 JSON Specification.""" fields = message.fields ret = {} for key in fields: ret[key] = self._ValueMessageToJsonObject(fields[key]) return ret
Convert a JSON object into a message.
def ConvertMessage(self, value, message): """Convert a JSON object into a message. Args: value: A JSON object. message: A WKT or regular protocol message to record the data. Raises: ParseError: In case of convert problems. """ message_descriptor = message.DESCRIPTOR full_name...
Convert field value pairs into regular message.
def _ConvertFieldValuePair(self, js, message): """Convert field value pairs into regular message. Args: js: A JSON object to convert the field value pairs. message: A regular protocol message to record the data. Raises: ParseError: In case of problems converting. """ names = [] ...
Convert a JSON representation into Any message.
def _ConvertAnyMessage(self, value, message): """Convert a JSON representation into Any message.""" if isinstance(value, dict) and not value: return try: type_url = value['@type'] except KeyError: raise ParseError('@type is missing when parsing any message.') sub_message = _Create...
Convert a JSON representation into Wrapper message.
def _ConvertWrapperMessage(self, value, message): """Convert a JSON representation into Wrapper message.""" field = message.DESCRIPTOR.fields_by_name['value'] setattr(message, 'value', _ConvertScalarFieldValue(value, field))
Convert map field value for a message map field.
def _ConvertMapFieldValue(self, value, message, field): """Convert map field value for a message map field. Args: value: A JSON object to convert the map field value. message: A protocol message to record the converted data. field: The descriptor of the map field to be converted. Raises:...
Plots the data in x on the X axis and the data in y on the Y axis in a 2d visualization and shows the resulting visualization. Uses the following heuristic to choose the visualization:
def plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are bot...
Plots the data in x on the X axis and the data in y on the Y axis in a 2d visualization and shows the resulting visualization. Uses the following heuristic to choose the visualization:
def show(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d visualization, and shows the resulting visualization. Uses the following heuristic to choose the visualization: * If `x` and `y` are bot...
Plots the data in x on the X axis and the data in y on the Y axis in a 2d scatter plot and returns the resulting Plot object. The function supports SArrays of dtypes: int float.
def scatter(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d scatter plot, and returns the resulting Plot object. The function supports SArrays of dtypes: int, float. Parameters -------...
Plots the data in x on the X axis and the data in y on the Y axis in a 2d categorical heatmap and returns the resulting Plot object. The function supports SArrays of dtypes str.
def categorical_heatmap(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d categorical heatmap, and returns the resulting Plot object. The function supports SArrays of dtypes str. Parameters ...
Plots the data in x on the X axis and the data in y on the Y axis in a 2d box and whiskers plot and returns the resulting Plot object. The function x as SArray of dtype str and y as SArray of dtype: int float.
def box_plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots the data in `x` on the X axis and the data in `y` on the Y axis in a 2d box and whiskers plot, and returns the resulting Plot object. The function x as SArray of dtype str and y as SArray of dtype: int, f...
Plots a columnwise summary of the sframe provided as input and returns the resulting Plot object. The function supports SFrames.
def columnwise_summary(sf): """ Plots a columnwise summary of the sframe provided as input, and returns the resulting Plot object. The function supports SFrames. Parameters ---------- sf : SFrame The data to get a columnwise summary for. Returns ------- out : Pl...
Plots a histogram of the sarray provided as input and returns the resulting Plot object. The function supports numeric SArrays with dtypes int or float.
def histogram(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots a histogram of the sarray provided as input, and returns the resulting Plot object. The function supports numeric SArrays with dtypes int or float. Parameters ---------- sa : SArray The...
Plots an item frequency of the sarray provided as input and returns the resulting Plot object. The function supports SArrays with dtype str.
def item_frequency(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT): """ Plots an item frequency of the sarray provided as input, and returns the resulting Plot object. The function supports SArrays with dtype str. Parameters ---------- sa : SArray The data t...
Parses the input file and returns C code and corresponding header file.
def Parse(factory, file): """ Parses the input file and returns C code and corresponding header file. """ entities = [] while 1: # Just gets the whole struct nicely formatted data = GetNextStruct(file) if not data: break entities.extend(ProcessStruct(f...
Creates the name inside an enumeration for distinguishing data types.
def EntryTagName(self, entry): """Creates the name inside an enumeration for distinguishing data types.""" name = "%s_%s" % (self._name, entry.Name()) return name.upper()
Takes an array add indentation to each entry and prints it.
def PrintIndented(self, file, ident, code): """Takes an array, add indentation to each entry and prints it.""" for entry in code: print >>file, '%s%s' % (ident, entry)
Prints the tag definitions for a structure.
def PrintTags(self, file): """Prints the tag definitions for a structure.""" print >>file, '/* Tag definition for %s */' % self._name print >>file, 'enum %s_ {' % self._name.lower() for entry in self._entries: print >>file, ' %s=%d,' % (self.EntryTagName(entry), ...
Builtin approximate quantile aggregator for groupby. Accepts as an argument one or more of a list of quantiles to query. For instance:
def QUANTILE(src_column, *args): """ Builtin approximate quantile aggregator for groupby. Accepts as an argument, one or more of a list of quantiles to query. For instance: To extract the median >>> sf.groupby("user", ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.5)}) To...
Compute the K - core decomposition of the graph. Return a model object with total number of cores as well as the core id for each vertex in the graph.
def create(graph, kmin=0, kmax=10, verbose=True): """ Compute the K-core decomposition of the graph. Return a model object with total number of cores as well as the core id for each vertex in the graph. Parameters ---------- graph : SGraph The graph on which to compute the k-core decomp...
Raise an error if an option is not supported.
def raise_error_unsupported_categorical_option(option_name, option_value, layer_type, layer_name): """ Raise an error if an option is not supported. """ raise RuntimeError("Unsupported option %s=%s in layer %s(%s)" % (option_name, option_value, layer_type, layer_name))
Given a list of class labels and a list of output_features validate the list and return a valid version of output_features with all the correct data type information included.
def process_or_validate_classifier_output_features( output_features, class_labels, supports_class_scores = True): """ Given a list of class labels and a list of output_features, validate the list and return a valid version of output_features with all the correct data type information included. ...
Puts features into a standard form from a number of different possible forms.
def process_or_validate_features(features, num_dimensions = None, feature_type_map = {}): """ Puts features into a standard form from a number of different possible forms. The standard form is a list of 2-tuples of (name, datatype) pairs. The name is a string and the datatype is an object as defined i...
Performs python - side bootstrapping of Boost. Build/ Python.
def bootstrap(root_path): """Performs python-side bootstrapping of Boost.Build/Python. This function arranges for 'b2.whatever' package names to work, while also allowing to put python files alongside corresponding jam modules. """ m = imp.new_module("b2") # Note that: # 1. If __path__ is ...
The main function of the utility
def main(): """The main function of the utility""" parser = argparse.ArgumentParser( description='Manage the build environment of Boost.Metaparse' ) parser.add_argument( '--dep_json', required=True, help='The json file describing the dependencies' ) parser.add_arg...
Outputs the last num elements that were appended either by append or append_multiple.
def read_history(self, num=10, segment=0): """ Outputs the last `num` elements that were appended either by `append` or `append_multiple`. Returns ------- out : list """ if num < 0: num = 0 if segment < 0: raise TypeError(...
Specifies the flags ( variables ) that must be set on targets under certain conditions described by arguments. rule_or_module: If contains dot should be a rule name. The flags will be applied when that rule is used to set up build actions.
def flags(rule_or_module, variable_name, condition, values = []): """ Specifies the flags (variables) that must be set on targets under certain conditions, described by arguments. rule_or_module: If contains dot, should be a rule name. The flags will be applied when that ...
Returns the first element of property - sets which is a subset of properties or an empty list if no such element exists.
def find_satisfied_condition(conditions, ps): """Returns the first element of 'property-sets' which is a subset of 'properties', or an empty list if no such element exists.""" assert is_iterable_typed(conditions, property_set.PropertySet) assert isinstance(ps, property_set.PropertySet) for conditio...
Brings all flag definitions from the base toolset into the toolset toolset. Flag definitions whose conditions make use of properties in prohibited - properties are ignored. Don t confuse property and feature for example <debug - symbols > on and <debug - symbols > off so blocking one of them does not block the other on...
def inherit_flags(toolset, base, prohibited_properties = []): """Brings all flag definitions from the 'base' toolset into the 'toolset' toolset. Flag definitions whose conditions make use of properties in 'prohibited-properties' are ignored. Don't confuse property and feature, for example <debug-symbols...
Given a rule name and a property set returns a list of tuples of variables names and values which must be set on targets for that rule/ properties combination.
def __set_target_variables_aux (manager, rule_or_module, ps): """ Given a rule name and a property set, returns a list of tuples of variables names and values, which must be set on targets for that rule/properties combination. """ assert isinstance(rule_or_module, basestring) assert isin...
Adds a new flag setting with the specified values. Does no checking.
def __add_flag (rule_or_module, variable_name, condition, values): """ Adds a new flag setting with the specified values. Does no checking. """ assert isinstance(rule_or_module, basestring) assert isinstance(variable_name, basestring) assert is_iterable_typed(condition, property_set.Property...
Convert a Logistic Regression model to the protobuf spec. Parameters ---------- model: LogisticRegression A trained LogisticRegression model.
def convert(model, feature_names, target): """Convert a Logistic Regression model to the protobuf spec. Parameters ---------- model: LogisticRegression A trained LogisticRegression model. feature_names: [str], optional (default=None) Name of the input columns. target: str, opti...
If path is relative it is rooted at root. Otherwise it s unchanged.
def root (path, root): """ If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged. """ if os.path.isabs (path): return path else: return os.path.join (root, path)
Returns path2 such that os. path. join ( path path2 ) ==.. path may not contain.. or be rooted.
def reverse(path): """Returns path2 such that `os.path.join(path, path2) == '.'`. `path` may not contain '..' or be rooted. Args: path (str): the path to reverse Returns: the string of the reversed path Example: >>> p1 = 'path/to/somewhere' >>> p2 = reverse('path/...