Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def is_topk(self, topk=10, reverse=False):
with cython_context():
return SArray(_proxy = self.__proxy__.topk_index(topk, reverse)) | [
"\n Create an SArray indicating which elements are in the top k.\n\n Entries are '1' if the corresponding element in the current SArray is a\n part of the top k elements, and '0' if that corresponding element is\n not. Order is descending by default.\n\n Parameters\n ------... |
Please provide a description of the function:def summary(self, background=False, sub_sketch_keys=None):
from ..data_structures.sketch import Sketch
if (self.dtype == _Image):
raise TypeError("summary() is not supported for arrays of image type")
if (type(background) != bool)... | [
"\n Summary statistics that can be calculated with one pass over the SArray.\n\n Returns a turicreate.Sketch object which can be further queried for many\n descriptive statistics over this SArray. Many of the statistics are\n approximate. See the :class:`~turicreate.Sketch` documentation... |
Please provide a description of the function:def value_counts(self):
from .sframe import SFrame as _SFrame
return _SFrame({'value':self}).groupby('value', {'count':_aggregate.COUNT}).sort('count', ascending=False) | [
"\n Return an SFrame containing counts of unique values. The resulting\n SFrame will be sorted in descending frequency.\n\n Returns\n -------\n out : SFrame\n An SFrame containing 2 columns : 'value', and 'count'. The SFrame will\n be sorted in descending ord... |
Please provide a description of the function:def append(self, other):
if type(other) is not SArray:
raise RuntimeError("SArray append can only work with SArray")
if self.dtype != other.dtype:
raise RuntimeError("Data types in both SArrays have to be the same")
... | [
"\n Append an SArray to the current SArray. Creates a new SArray with the\n rows from both SArrays. Both SArrays must be of the same type.\n\n Parameters\n ----------\n other : SArray\n Another SArray whose rows are appended to current SArray.\n\n Returns\n ... |
Please provide a description of the function:def unique(self):
from .sframe import SFrame as _SFrame
tmp_sf = _SFrame()
tmp_sf.add_column(self, 'X1', inplace=True)
res = tmp_sf.groupby('X1',{})
return SArray(_proxy=res['X1'].__proxy__) | [
"\n Get all unique values in the current SArray.\n\n Raises a TypeError if the SArray is of dictionary type. Will not\n necessarily preserve the order of the given SArray in the new SArray.\n\n\n Returns\n -------\n out : SArray\n A new SArray that contains the u... |
Please provide a description of the function:def show(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
returned_plot = self.plot(title, xlabel, ylabel)
returned_plot.show() | [
"\n Visualize the SArray.\n\n Notes\n -----\n - The plot will render either inline in a Jupyter Notebook, or in a\n native GUI window, depending on the value provided in\n `turicreate.visualization.set_target` (defaults to 'auto').\n\n Parameters\n -------... |
Please provide a description of the function:def plot(self, title=LABEL_DEFAULT, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT):
if title == "":
title = " "
if xlabel == "":
xlabel = " "
if ylabel == "":
ylabel = " "
if title is None:
... | [
"\n Create a Plot object representing the SArray.\n\n Notes\n -----\n - The plot will render either inline in a Jupyter Notebook, or in a\n native GUI window, depending on the value provided in\n `turicreate.visualization.set_target` (defaults to 'auto').\n\n Par... |
Please provide a description of the function:def item_length(self):
if (self.dtype not in [list, dict, array.array]):
raise TypeError("item_length() is only applicable for SArray of type list, dict and array.")
with cython_context():
return SArray(_proxy = self.__proxy... | [
"\n Length of each element in the current SArray.\n\n Only works on SArrays of dict, array, or list type. If a given element\n is a missing value, then the output elements is also a missing value.\n This function is equivalent to the following but more performant:\n\n sa_item_... |
Please provide a description of the function:def random_split(self, fraction, seed=None):
from .sframe import SFrame
temporary_sf = SFrame()
temporary_sf['X1'] = self
(train, test) = temporary_sf.random_split(fraction, seed)
return (train['X1'], test['X1']) | [
"\n Randomly split the rows of an SArray into two SArrays. The first SArray\n contains *M* rows, sampled uniformly (without replacement) from the\n original SArray. *M* is approximately the fraction times the original\n number of rows. The second SArray contains the remaining rows of the... |
Please provide a description of the function:def split_datetime(self, column_name_prefix = "X", limit=None, timezone=False):
from .sframe import SFrame as _SFrame
if self.dtype != datetime.datetime:
raise TypeError("Only column of datetime type is supported.")
if column_na... | [
"\n Splits an SArray of datetime type to multiple columns, return a\n new SFrame that contains expanded columns. A SArray of datetime will be\n split by default into an SFrame of 6 columns, one for each\n year/month/day/hour/minute/second element.\n\n **Column Naming**\n\n ... |
Please provide a description of the function:def stack(self, new_column_name=None, drop_na=False, new_column_type=None):
from .sframe import SFrame as _SFrame
return _SFrame({'SArray': self}).stack('SArray',
new_column_name=new_column_name,
... | [
"\n Convert a \"wide\" SArray to one or two \"tall\" columns in an SFrame by\n stacking all values.\n\n The stack works only for columns of dict, list, or array type. If the\n column is dict type, two new columns are created as a result of\n stacking: one column holds the key and... |
Please provide a description of the function:def unpack(self, column_name_prefix = "X", column_types=None, na_value=None, limit=None):
from .sframe import SFrame as _SFrame
if self.dtype not in [dict, array.array, list]:
raise TypeError("Only SArray of dict/list/array type supports... | [
"\n Convert an SArray of list, array, or dict type to an SFrame with\n multiple columns.\n\n `unpack` expands an SArray using the values of each list/array/dict as\n elements in a new SFrame of multiple columns. For example, an SArray of\n lists each of length 4 will be expanded i... |
Please provide a description of the function:def sort(self, ascending=True):
from .sframe import SFrame as _SFrame
if self.dtype not in (int, float, str, datetime.datetime):
raise TypeError("Only sarray with type (int, float, str, datetime.datetime) can be sorted")
sf = _SF... | [
"\n Sort all values in this SArray.\n\n Sort only works for sarray of type str, int and float, otherwise TypeError\n will be raised. Creates a new, sorted SArray.\n\n Parameters\n ----------\n ascending: boolean, optional\n If true, the sarray values are sorted in... |
Please provide a description of the function:def rolling_sum(self, window_start, window_end, min_observations=None):
min_observations = self.__check_min_observations(min_observations)
agg_op = None
if self.dtype is array.array:
agg_op = '__builtin__vector__sum__'
els... | [
"\n Calculate a new SArray of the sum of different subsets over this\n SArray.\n\n Also known as a \"moving sum\" or \"running sum\". The subset that\n the sum is calculated over is defined as an inclusive range relative\n to the position to each value in the SArray, using `window... |
Please provide a description of the function:def rolling_max(self, window_start, window_end, min_observations=None):
min_observations = self.__check_min_observations(min_observations)
agg_op = '__builtin__max__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_st... | [
"\n Calculate a new SArray of the maximum value of different subsets over\n this SArray.\n\n The subset that the maximum is calculated over is defined as an\n inclusive range relative to the position to each value in the SArray,\n using `window_start` and `window_end`. For a bette... |
Please provide a description of the function:def rolling_count(self, window_start, window_end):
agg_op = '__builtin__nonnull__count__'
return SArray(_proxy=self.__proxy__.builtin_rolling_apply(agg_op, window_start, window_end, 0)) | [
"\n Count the number of non-NULL values of different subsets over this\n SArray.\n\n The subset that the count is executed on is defined as an inclusive\n range relative to the position to each value in the SArray, using\n `window_start` and `window_end`. For a better understandin... |
Please provide a description of the function:def cumulative_sum(self):
from .. import extensions
agg_op = "__builtin__cum_sum__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"\n Return the cumulative sum of the elements in the SArray.\n\n Returns an SArray where each element in the output corresponds to the\n sum of all the elements preceding and including it. The SArray is\n expected to be of numeric type (int, float), or a numeric vector type.\n\n R... |
Please provide a description of the function:def cumulative_mean(self):
from .. import extensions
agg_op = "__builtin__cum_avg__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"\n Return the cumulative mean of the elements in the SArray.\n\n Returns an SArray where each element in the output corresponds to the\n mean value of all the elements preceding and including it. The SArray\n is expected to be of numeric type (int, float), or a numeric vector\n t... |
Please provide a description of the function:def cumulative_min(self):
from .. import extensions
agg_op = "__builtin__cum_min__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"\n Return the cumulative minimum value of the elements in the SArray.\n\n Returns an SArray where each element in the output corresponds to the\n minimum value of all the elements preceding and including it. The\n SArray is expected to be of numeric type (int, float).\n\n Returns... |
Please provide a description of the function:def cumulative_max(self):
from .. import extensions
agg_op = "__builtin__cum_max__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"\n Return the cumulative maximum value of the elements in the SArray.\n\n Returns an SArray where each element in the output corresponds to the\n maximum value of all the elements preceding and including it. The\n SArray is expected to be of numeric type (int, float).\n\n Returns... |
Please provide a description of the function:def cumulative_std(self):
from .. import extensions
agg_op = "__builtin__cum_std__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"\n Return the cumulative standard deviation of the elements in the SArray.\n\n Returns an SArray where each element in the output corresponds to the\n standard deviation of all the elements preceding and including it. The\n SArray is expected to be of numeric type, or a numeric vector t... |
Please provide a description of the function:def cumulative_var(self):
from .. import extensions
agg_op = "__builtin__cum_var__"
return SArray(_proxy = self.__proxy__.builtin_cumulative_aggregate(agg_op)) | [
"\n Return the cumulative variance of the elements in the SArray.\n\n Returns an SArray where each element in the output corresponds to the\n variance of all the elements preceding and including it. The SArray is\n expected to be of numeric type, or a numeric vector type.\n\n Retu... |
Please provide a description of the function:def filter_by(self, values, exclude=False):
from .sframe import SFrame as _SFrame
column_name = 'sarray'
# Convert values to SArray
if not isinstance(values, SArray): #type(values) is not SArray:
... | [
"\n Filter an SArray by values inside an iterable object. The result is an SArray that\n only includes (or excludes) the values in the given ``values`` :class:`~turicreate.SArray`.\n If ``values`` is not an SArray, we attempt to convert it to one before filtering.\n \n Parameters\... |
Please provide a description of the function:def run_build_lib(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)
retcode = subproce... | [
"Run the doxygen make command in the designated folder."
] |
Please provide a description of the function:def generate_doxygen_xml(app):
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('..')
sys.stderr.write('The wr... | [
"Run the doxygen make commands if we're on the ReadTheDocs server"
] |
Please provide a description of the function:def MessageToJson(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
return printer.ToJsonString(me... | [
"Converts protobuf message to JSON format.\n\n Args:\n message: The protocol buffers message instance to serialize.\n including_default_value_fields: If True, singular primitive fields,\n repeated fields, and map fields will always be serialized. If\n False, only serialize non-empty fields. S... |
Please provide a description of the function:def MessageToDict(message,
including_default_value_fields=False,
preserving_proto_field_name=False):
printer = _Printer(including_default_value_fields,
preserving_proto_field_name)
# pylint: disable=protected-ac... | [
"Converts protobuf message to a JSON dictionary.\n\n Args:\n message: The protocol buffers message instance to serialize.\n including_default_value_fields: If True, singular primitive fields,\n repeated fields, and map fields will always be serialized. If\n False, only serialize non-empty fiel... |
Please provide a description of the function:def ParseDict(js_dict, message, ignore_unknown_fields=False):
parser = _Parser(ignore_unknown_fields)
parser.ConvertMessage(js_dict, message)
return message | [
"Parses a JSON dictionary representation into a message.\n\n Args:\n js_dict: Dict representation of a JSON message.\n message: A protocol buffer message to merge into.\n ignore_unknown_fields: If True, do not raise errors for unknown fields.\n\n Returns:\n The same message passed as argument.\n "
] |
Please provide a description of the function:def _ConvertScalarFieldValue(value, field, require_str=False):
if field.cpp_type in _INT_TYPES:
return _ConvertInteger(value)
elif field.cpp_type in _FLOAT_TYPES:
return _ConvertFloat(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
... | [
"Convert a single scalar field value.\n\n Args:\n value: A scalar value to convert the scalar field value.\n field: The descriptor of the field to convert.\n require_str: If True, the field value must be a str.\n\n Returns:\n The converted scalar field value\n\n Raises:\n ParseError: In case of co... |
Please provide a description of the function:def _ConvertInteger(value):
if isinstance(value, float) and not value.is_integer():
raise ParseError('Couldn\'t parse integer: {0}.'.format(value))
if isinstance(value, six.text_type) and value.find(' ') != -1:
raise ParseError('Couldn\'t parse integer: "{0}"... | [
"Convert an integer.\n\n Args:\n value: A scalar value to convert.\n\n Returns:\n The integer value.\n\n Raises:\n ParseError: If an integer couldn't be consumed.\n "
] |
Please provide a description of the function:def _ConvertFloat(value):
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_INFINI... | [
"Convert an floating point number."
] |
Please provide a description of the function:def _ConvertBool(value, require_str):
if require_str:
if value == 'true':
return True
elif value == 'false':
return False
else:
raise ParseError('Expected "true" or "false", not {0}.'.format(value))
if not isinstance(value, bool):
ra... | [
"Convert a boolean value.\n\n Args:\n value: A scalar value to convert.\n require_str: If True, value must be a str.\n\n Returns:\n The bool parsed.\n\n Raises:\n ParseError: If a boolean value couldn't be consumed.\n "
] |
Please provide a description of the function:def _MessageToJsonObject(self, message):
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
return self._WrapperMessageToJsonObject(message)
if full_name in _WKTJSONMETHODS:
... | [
"Converts message to an object according to Proto3 JSON Specification."
] |
Please provide a description of the function:def _RegularMessageToJsonObject(self, message, js):
fields = message.ListFields()
try:
for field, value in fields:
if self.preserving_proto_field_name:
name = field.name
else:
name = field.json_name
if _IsMapEnt... | [
"Converts normal message according to Proto3 JSON Specification."
] |
Please provide a description of the function:def _FieldToJsonObject(self, field, value):
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
return self._MessageToJsonObject(value)
elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
enum_value = field.enum_type.values_b... | [
"Converts field value according to Proto3 JSON Specification."
] |
Please provide a description of the function:def _AnyMessageToJsonObject(self, message):
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_message = _CreateMessageFro... | [
"Converts Any message according to Proto3 JSON Specification."
] |
Please provide a description of the function:def _ValueMessageToJsonObject(self, message):
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 which is None or which == '... | [
"Converts Value message according to Proto3 JSON Specification."
] |
Please provide a description of the function:def _StructMessageToJsonObject(self, message):
fields = message.fields
ret = {}
for key in fields:
ret[key] = self._ValueMessageToJsonObject(fields[key])
return ret | [
"Converts Struct message according to Proto3 JSON Specification."
] |
Please provide a description of the function:def ConvertMessage(self, value, message):
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
self._ConvertWrapperMessage(value, message)
elif full_name in _WKTJSONMETHODS:
... | [
"Convert a JSON object into a message.\n\n Args:\n value: A JSON object.\n message: A WKT or regular protocol message to record the data.\n\n Raises:\n ParseError: In case of convert problems.\n "
] |
Please provide a description of the function:def _ConvertFieldValuePair(self, js, message):
names = []
message_descriptor = message.DESCRIPTOR
fields_by_json_name = dict((f.json_name, f)
for f in message_descriptor.fields)
for name in js:
try:
field = fi... | [
"Convert field value pairs into regular message.\n\n Args:\n js: A JSON object to convert the field value pairs.\n message: A regular protocol message to record the data.\n\n Raises:\n ParseError: In case of problems converting.\n "
] |
Please provide a description of the function:def _ConvertAnyMessage(self, value, 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 = _CreateMessageF... | [
"Convert a JSON representation into Any message."
] |
Please provide a description of the function:def _ConvertWrapperMessage(self, value, message):
field = message.DESCRIPTOR.fields_by_name['value']
setattr(message, 'value', _ConvertScalarFieldValue(value, field)) | [
"Convert a JSON representation into Wrapper message."
] |
Please provide a description of the function:def _ConvertMapFieldValue(self, value, message, field):
if not isinstance(value, dict):
raise ParseError(
'Map field {0} must be in a dict which is {1}.'.format(
field.name, value))
key_field = field.message_type.fields_by_name['key... | [
"Convert map field value for a message map field.\n\n Args:\n value: A JSON object to convert the map field value.\n message: A protocol message to record the converted data.\n field: The descriptor of the map field to be converted.\n\n Raises:\n ParseError: In case of convert problems.\n ... |
Please provide a description of the function:def plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
title = _get_title(title)
plt_ref = tc.extensions.plot(x, y, xlabel, ylabel, title)
return Plot(plt_ref) | [
"\n Plots the data in `x` on the X axis and the data in `y` on the Y axis\n in a 2d visualization, and shows the resulting visualization.\n Uses the following heuristic to choose the visualization:\n\n * If `x` and `y` are both numeric (SArray of int or float), and they contain\n fewer than or equa... |
Please provide a description of the function:def show(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
plot(x, y, xlabel, ylabel, title).show() | [
"\n Plots the data in `x` on the X axis and the data in `y` on the Y axis\n in a 2d visualization, and shows the resulting visualization.\n Uses the following heuristic to choose the visualization:\n\n * If `x` and `y` are both numeric (SArray of int or float), and they contain\n fewer than or equa... |
Please provide a description of the function:def scatter(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
if (not isinstance(x, tc.data_structures.sarray.SArray) or
not isinstance(y, tc.data_structures.sarray.SArray) or
x.dtype not in [int, float] or y.dtype not in [int,... | [
"\n Plots the data in `x` on the X axis and the data in `y` on the Y axis\n in a 2d scatter plot, and returns the resulting Plot object.\n \n The function supports SArrays of dtypes: int, float.\n\n Parameters\n ----------\n x : SArray\n The data to plot on the X axis of the scatter plot. ... |
Please provide a description of the function:def categorical_heatmap(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
if (not isinstance(x, tc.data_structures.sarray.SArray) or
not isinstance(y, tc.data_structures.sarray.SArray) or
x.dtype != str or y.dtype != str):
... | [
"\n Plots the data in `x` on the X axis and the data in `y` on the Y axis\n in a 2d categorical heatmap, and returns the resulting Plot object.\n \n The function supports SArrays of dtypes str.\n\n Parameters\n ----------\n x : SArray\n The data to plot on the X axis of the categorical hea... |
Please provide a description of the function:def box_plot(x, y, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
if (not isinstance(x, tc.data_structures.sarray.SArray) or
not isinstance(y, tc.data_structures.sarray.SArray) or
x.dtype != str or y.dtype not in [int, float]):
... | [
"\n Plots the data in `x` on the X axis and the data in `y` on the Y axis\n in a 2d box and whiskers plot, and returns the resulting Plot object.\n \n The function x as SArray of dtype str and y as SArray of dtype: int, float.\n\n Parameters\n ----------\n x : SArray\n The data to plot on ... |
Please provide a description of the function:def columnwise_summary(sf):
if not isinstance(sf, tc.data_structures.sframe.SFrame):
raise ValueError("turicreate.visualization.columnwise_summary " +
"supports SFrame")
plt_ref = tc.extensions.plot_columnwise_summary(sf)
return Plot(plt... | [
"\n Plots a columnwise summary of the sframe provided as input, \n and returns the resulting Plot object.\n \n The function supports SFrames.\n\n Parameters\n ----------\n sf : SFrame\n The data to get a columnwise summary for.\n \n Returns\n -------\n out : Plot\n A :clas... |
Please provide a description of the function:def histogram(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
if (not isinstance(sa, tc.data_structures.sarray.SArray) or
sa.dtype not in [int, float]):
raise ValueError("turicreate.visualization.histogram supports " +
... | [
"\n Plots a histogram of the sarray provided as input, and returns the \n resulting Plot object.\n \n The function supports numeric SArrays with dtypes int or float.\n\n Parameters\n ----------\n sa : SArray\n The data to get a histogram for. Must be numeric (int/float).\n xlabel : str ... |
Please provide a description of the function:def item_frequency(sa, xlabel=LABEL_DEFAULT, ylabel=LABEL_DEFAULT, title=LABEL_DEFAULT):
if (not isinstance(sa, tc.data_structures.sarray.SArray) or
sa.dtype != str):
raise ValueError("turicreate.visualization.item_frequency supports " +
... | [
"\n Plots an item frequency of the sarray provided as input, and returns the \n resulting Plot object.\n \n The function supports SArrays with dtype str.\n\n Parameters\n ----------\n sa : SArray\n The data to get an item frequency for. Must have dtype str\n xlabel : str (optional)\n ... |
Please provide a description of the function:def Parse(factory, file):
entities = []
while 1:
# Just gets the whole struct nicely formatted
data = GetNextStruct(file)
if not data:
break
entities.extend(ProcessStruct(factory, data))
return entities | [
"\n Parses the input file and returns C code and corresponding header file.\n "
] |
Please provide a description of the function:def EntryTagName(self, entry):
name = "%s_%s" % (self._name, entry.Name())
return name.upper() | [
"Creates the name inside an enumeration for distinguishing data\n types."
] |
Please provide a description of the function:def PrintIndented(self, file, ident, code):
for entry in code:
print >>file, '%s%s' % (ident, entry) | [
"Takes an array, add indentation to each entry and prints it."
] |
Please provide a description of the function:def PrintTags(self, file):
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),
... | [
"Prints the tag definitions for a structure."
] |
Please provide a description of the function:def QUANTILE(src_column, *args):
if len(args) == 1:
quantiles = args[0]
else:
quantiles = list(args)
if not _is_non_string_iterable(quantiles):
quantiles = [quantiles]
query = ",".join([str(i) for i in quantiles])
return ("__... | [
"\n Builtin approximate quantile aggregator for groupby.\n Accepts as an argument, one or more of a list of quantiles to query.\n For instance:\n\n To extract the median\n\n >>> sf.groupby(\"user\",\n ... {'rating_quantiles':tc.aggregate.QUANTILE('rating', 0.5)})\n\n To extract a few quantile... |
Please provide a description of the function:def create(graph, kmin=0, kmax=10, verbose=True):
from turicreate._cython.cy_server import QuietProgress
if not isinstance(graph, _SGraph):
raise TypeError('graph input must be a SGraph object.')
opts = {'graph': graph.__proxy__, 'kmin': kmin, 'kma... | [
"\n Compute the K-core decomposition of the graph. Return a model object with\n total number of cores as well as the core id for each vertex in the graph.\n\n Parameters\n ----------\n graph : SGraph\n The graph on which to compute the k-core decomposition.\n\n kmin : int, optional\n ... |
Please provide a description of the function:def raise_error_unsupported_categorical_option(option_name, option_value, layer_type, layer_name):
raise RuntimeError("Unsupported option %s=%s in layer %s(%s)" % (option_name, option_value,
layer_type, layer_name)) | [
"\n Raise an error if an option is not supported.\n "
] |
Please provide a description of the function:def process_or_validate_classifier_output_features(
output_features, class_labels, supports_class_scores = True):
def raise_error(msg):
raise ValueError("Classifier error: %s" % msg)
class_labels = list(class_labels)
# First, we need to ... | [
"\n Given a list of class labels and a list of output_features, validate the\n list and return a valid version of output_features with all the correct\n data type information included.\n "
] |
Please provide a description of the function:def process_or_validate_features(features, num_dimensions = None, feature_type_map = {}):
original_features = copy(features)
if num_dimensions is not None and not isinstance(num_dimensions, _integer_types):
raise TypeError("num_dimensions must be None,... | [
"\n Puts features into a standard form from a number of different possible forms.\n\n The standard form is a list of 2-tuples of (name, datatype) pairs. The name\n is a string and the datatype is an object as defined in the _datatype module.\n\n The possible input forms are as follows:\n\n * A lis... |
Please provide a description of the function:def bootstrap(root_path):
m = imp.new_module("b2")
# Note that:
# 1. If __path__ is not list of strings, nothing will work
# 2. root_path is already list of strings.
m.__path__ = root_path
sys.modules["b2"] = m
import b2.build_system
re... | [
"Performs python-side bootstrapping of Boost.Build/Python.\n\n This function arranges for 'b2.whatever' package names to work, while also\n allowing to put python files alongside corresponding jam modules.\n "
] |
Please provide a description of the function:def main():
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.... | [
"The main function of the utility"
] |
Please provide a description of the function:def read_history(self, num=10, segment=0):
if num < 0:
num = 0
if segment < 0:
raise TypeError("segment must be >= 0")
return self._builder.read_history(num, segment) | [
"\n Outputs the last `num` elements that were appended either by `append` or\n `append_multiple`.\n\n Returns\n -------\n out : list\n\n "
] |
Please provide a description of the function:def flags(rule_or_module, variable_name, condition, values = []):
assert isinstance(rule_or_module, basestring)
assert isinstance(variable_name, basestring)
assert is_iterable_typed(condition, basestring)
assert is_iterable(values) and all(isinstance(v, ... | [
" Specifies the flags (variables) that must be set on targets under certain\n conditions, described by arguments.\n rule_or_module: If contains dot, should be a rule name.\n The flags will be applied when that rule is\n used to set up build actions.\... |
Please provide a description of the function:def find_satisfied_condition(conditions, ps):
assert is_iterable_typed(conditions, property_set.PropertySet)
assert isinstance(ps, property_set.PropertySet)
for condition in conditions:
found_all = True
for i in condition.all():
... | [
"Returns the first element of 'property-sets' which is a subset of\n 'properties', or an empty list if no such element exists."
] |
Please provide a description of the function:def inherit_flags(toolset, base, prohibited_properties = []):
assert isinstance(toolset, basestring)
assert isinstance(base, basestring)
assert is_iterable_typed(prohibited_properties, basestring)
for f in __module_flags.get(base, []):
if not f.... | [
"Brings all flag definitions from the 'base' toolset into the 'toolset'\n toolset. Flag definitions whose conditions make use of properties in\n 'prohibited-properties' are ignored. Don't confuse property and feature, for\n example <debug-symbols>on and <debug-symbols>off, so blocking one of them does\n ... |
Please provide a description of the function:def __set_target_variables_aux (manager, rule_or_module, ps):
assert isinstance(rule_or_module, basestring)
assert isinstance(ps, property_set.PropertySet)
result = []
for f in __flags.get(rule_or_module, []):
if not f.condition or find_satisfi... | [
" Given a rule name and a property set, returns a list of tuples of\n variables names and values, which must be set on targets for that\n rule/properties combination.\n "
] |
Please provide a description of the function:def __add_flag (rule_or_module, variable_name, condition, values):
assert isinstance(rule_or_module, basestring)
assert isinstance(variable_name, basestring)
assert is_iterable_typed(condition, property_set.PropertySet)
assert is_iterable(values) and all... | [
" Adds a new flag setting with the specified values.\n Does no checking.\n "
] |
Please provide a description of the function:def convert(model, feature_names, target):
if not(_HAS_SKLEARN):
raise RuntimeError('scikit-learn not found. scikit-learn conversion API is disabled.')
_sklearn_util.check_expected_type(model, LogisticRegression)
_sklearn_util.check_fitted(model, la... | [
"Convert a Logistic Regression model to the protobuf spec.\n Parameters\n ----------\n model: LogisticRegression\n A trained LogisticRegression model.\n\n feature_names: [str], optional (default=None)\n Name of the input columns.\n\n target: str, optional (default=None)\n Name of... |
Please provide a description of the function:def root (path, root):
if os.path.isabs (path):
return path
else:
return os.path.join (root, path) | [
" If 'path' is relative, it is rooted at 'root'. Otherwise, it's unchanged.\n "
] |
Please provide a description of the function:def reverse(path):
if is_rooted(path) or '..' in path:
from b2.manager import get_manager
get_manager().errors()(
'reverse(path): path is either rooted or contains ".." in the path')
if path == '.':
return path
path = os.p... | [
"Returns path2 such that `os.path.join(path, path2) == '.'`.\n `path` may not contain '..' or be rooted.\n\n Args:\n path (str): the path to reverse\n\n Returns:\n the string of the reversed path\n\n Example:\n\n >>> p1 = 'path/to/somewhere'\n >>> p2 = reverse('path/to/somewh... |
Please provide a description of the function:def glob (dirs, patterns):
# {
# local result ;
# if $(patterns:D)
# {
# # When a pattern has a directory element, we first glob for
# # directory, and then glob for file name is the found directories.
# for local p in $... | [
" Returns the list of files matching the given pattern in the\n specified directory. Both directories and patterns are\n supplied as portable paths. Each pattern should be non-absolute\n path, and can't contain \".\" or \"..\" elements. Each slash separated\n element of pattern can contain the followin... |
Please provide a description of the function:def glob(dirs, patterns, exclude_patterns=None):
assert(isinstance(patterns, list))
assert(isinstance(dirs, list))
if not exclude_patterns:
exclude_patterns = []
else:
assert(isinstance(exclude_patterns, list))
real_patterns = [os.p... | [
"Returns the list of files matching the given pattern in the\n specified directory. Both directories and patterns are\n supplied as portable paths. Each pattern should be non-absolute\n path, and can't contain '.' or '..' elements. Each slash separated\n element of pattern can contain the following spe... |
Please provide a description of the function:def glob_tree(roots, patterns, exclude_patterns=None):
if not exclude_patterns:
exclude_patterns = []
result = glob(roots, patterns, exclude_patterns)
subdirs = [s for s in glob(roots, ["*"], exclude_patterns) if s != "." and s != ".." and os.path.... | [
"Recursive version of GLOB. Builds the glob of files while\n also searching in the subdirectories of the given roots. An\n optional set of exclusion patterns will filter out the\n matching entries from the result. The exclusions also apply\n to the subdirectory scanning, such that directories that\n ... |
Please provide a description of the function:def glob_in_parents(dir, patterns, upper_limit=None):
assert(isinstance(dir, str))
assert(isinstance(patterns, list))
result = []
absolute_dir = os.path.join(os.getcwd(), dir)
absolute_dir = os.path.normpath(absolute_dir)
while absolute_dir:
... | [
"Recursive version of GLOB which glob sall parent directories\n of dir until the first match is found. Returns an empty result if no match\n is found"
] |
Please provide a description of the function:def _wrap_function_return(val):
if type(val) is _UnityGraphProxy:
return _SGraph(_proxy = val)
elif type(val) is _UnitySFrameProxy:
return _SFrame(_proxy = val)
elif type(val) is _UnitySArrayProxy:
return _SArray(_proxy = val)
el... | [
"\n Recursively walks each thing in val, opening lists and dictionaries,\n converting all occurrences of UnityGraphProxy to an SGraph,\n UnitySFrameProxy to SFrame, and UnitySArrayProxy to SArray.\n "
] |
Please provide a description of the function:def _setattr_wrapper(mod, key, value):
setattr(mod, key, value)
if mod == _thismodule:
setattr(_sys.modules[__name__], key, value) | [
"\n A setattr wrapper call used only by _publish(). This ensures that anything\n published into this module is also published into tc.extensions\n "
] |
Please provide a description of the function:def _run_toolkit_function(fnname, arguments, args, kwargs):
# scan for all the arguments in args
num_args_got = len(args) + len(kwargs)
num_args_required = len(arguments)
if num_args_got != num_args_required:
raise TypeError("Expecting " + str(nu... | [
"\n Dispatches arguments to a toolkit function.\n\n Parameters\n ----------\n fnname : string\n The toolkit function to run\n\n arguments : list[string]\n The list of all the arguments the function takes.\n\n args : list\n The arguments that were passed\n\n kwargs : diction... |
Please provide a description of the function:def _class_instance_from_name(class_name, *arg, **kwarg):
# we first look in tc.extensions for the class name
module_path = class_name.split('.')
import_path = module_path[0:-1]
module = __import__('.'.join(import_path), fromlist=[module_path[-1]])
c... | [
"\n class_name is of the form modA.modB.modC.class module_path splits on \".\"\n and the import_path is then ['modA','modB','modC'] the __import__ call is\n really annoying but essentially it reads like:\n\n import class from modA.modB.modC\n\n - Then the module variable points to modC\n - Then yo... |
Please provide a description of the function:def _create_class_instance(class_name, _proxy):
try:
return _class_instance_from_name('turicreate.extensions.' + class_name, _proxy=_proxy)
except:
pass
return _class_instance_from_name(class_name, _proxy=_proxy) | [
"\n Look for the class in .extensions in case it has already been\n imported (perhaps as a builtin extensions hard compiled into unity_server).\n "
] |
Please provide a description of the function:def _publish():
import copy
unity = _get_unity()
fnlist = unity.list_toolkit_functions()
# Loop through all the functions and inject it into
# turicreate.extensions.[blah]
# Note that [blah] may be somemodule.somefunction
# and so the inject... | [
"\n Publishes all functions and classes registered in unity_server.\n The functions and classes will appear in the module turicreate.extensions\n "
] |
Please provide a description of the function:def ext_import(soname, module_subpath=""):
unity = _get_unity()
import os
if os.path.exists(soname):
soname = os.path.abspath(soname)
else:
soname = _make_internal_url(soname)
ret = unity.load_toolkit(soname, module_subpath)
if le... | [
"\n Loads a turicreate toolkit module (a shared library) into the\n tc.extensions namespace.\n\n Toolkit module created via SDK can either be directly imported,\n e.g. ``import example`` or via this function, e.g. ``turicreate.ext_import(\"example.so\")``.\n Use ``ext_import`` when you need more name... |
Please provide a description of the function:def _get_argument_list_from_toolkit_function_name(fn):
unity = _get_unity()
fnprops = unity.describe_toolkit_function(fn)
argnames = fnprops['arguments']
return argnames | [
"\n Given a toolkit function name, return the argument list\n "
] |
Please provide a description of the function:def _descend_namespace(caller_globals, name):
names = name.split('.')
cur = caller_globals
for i in names:
if type(cur) is dict:
cur = cur[i]
else:
cur = getattr(cur, i)
return cur | [
"\n Given a globals dictionary, and a name of the form \"a.b.c.d\", recursively\n walk the globals expanding caller_globals['a']['b']['c']['d'] returning\n the result. Raises an exception (IndexError) on failure.\n "
] |
Please provide a description of the function:def _build_native_function_call(fn):
# See if fn is the native function itself
native_function_name = _get_toolkit_function_name_from_function(fn)
if native_function_name != "":
# yup!
# generate an "identity" argument list
argnames =... | [
"\n If fn can be interpreted and handled as a native function: i.e.\n fn is one of the extensions, or fn is a simple lambda closure using one of\n the extensions.\n\n fn = tc.extensions.add\n fn = lambda x: tc.extensions.add(5)\n\n Then, this returns a closure object, which describes the fun... |
Please provide a description of the function:def find_module(self, fullname, submodule_path=None):
# first see if we have this particular so has been loaded by
# turicreate's extension library before
ret = self.try_find_module(fullname, submodule_path)
if ret is not None:
... | [
"\n We have to see if fullname refers to a module we can import.\n Some care is needed here because:\n\n import xxx # tries to load xxx.so from any of the python import paths\n import aaa.bbb.xxx # tries to load aaa/bbb/xxx.so from any of the python import paths\n "
] |
Please provide a description of the function:def main():
source_lines = (line.rstrip() for line in sys.stdin)
console = InteractiveInterpreter()
console.runsource('import turicreate')
source = ''
try:
while True:
source = source_lines.next()
more = console.runsou... | [
"\n Print lines of input along with output.\n "
] |
Please provide a description of the function:def GetTypeChecker(field):
if (field.cpp_type == _FieldDescriptor.CPPTYPE_STRING and
field.type == _FieldDescriptor.TYPE_STRING):
return UnicodeValueChecker()
if field.cpp_type == _FieldDescriptor.CPPTYPE_ENUM:
if SupportsOpenEnums(field):
# When o... | [
"Returns a type checker for a message field of the specified types.\n\n Args:\n field: FieldDescriptor object for this field.\n\n Returns:\n An instance of TypeChecker which can be used to verify the types\n of values assigned to a field of the specified type.\n "
] |
Please provide a description of the function:def CheckValue(self, proposed_value):
if not isinstance(proposed_value, self._acceptable_types):
message = ('%.1024r has type %s, but expected one of: %s' %
(proposed_value, type(proposed_value), self._acceptable_types))
raise TypeError(... | [
"Type check the provided value and return it.\n\n The returned value might have been normalized to another type.\n "
] |
Please provide a description of the function:def python_source(ast, file=sys.stdout):
'''
Generate executable python source code from an ast node.
:param ast: ast node
:param file: file to write output to.
'''
gen = SourceGen()
gen.visit(ast)
gen.dump(file) | [] |
Please provide a description of the function:def CEscape(text, as_utf8):
# PY3 hack: make Ord work for str and bytes:
# //platforms/networking/data uses unicode here, hence basestring.
Ord = ord if isinstance(text, six.string_types) else lambda x: x
if as_utf8:
return ''.join(_cescape_utf8_to_str[Ord(c)]... | [
"Escape a bytes string for use in an ascii protocol buffer.\n\n text.encode('string_escape') does not seem to satisfy our needs as it\n encodes unprintable characters using two-digit hex escapes whereas our\n C++ unescaping function allows hex escapes to be any length. So,\n \"\\0011\".encode('string_escape') ... |
Please provide a description of the function:def CUnescape(text):
def ReplaceHex(m):
# Only replace the match if the number of leading back slashes is odd. i.e.
# the slash itself is not escaped.
if len(m.group(1)) & 1:
return m.group(1) + 'x0' + m.group(2)
return m.group(0)
# This is req... | [
"Unescape a text string with C-style escape sequences to UTF-8 bytes."
] |
Please provide a description of the function:def reset ():
global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache
__register_features ()
# Stores suffixes for generated targets.
__prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()... | [
" Clear the module state. This is mainly for testing purposes.\n Note that this must be called _after_ resetting the module 'feature'.\n "
] |
Please provide a description of the function:def register (type, suffixes = [], base_type = None):
# Type names cannot contain hyphens, because when used as
# feature-values they will be interpreted as composite features
# which need to be decomposed.
if __re_hyphen.search (type):
raise Bas... | [
" Registers a target type, possibly derived from a 'base-type'.\n If 'suffixes' are provided, they list all the suffixes that mean a file is of 'type'.\n Also, the first element gives the suffix to be used when constructing and object of\n 'type'.\n type: a string\n suffixes: None... |
Please provide a description of the function:def register_suffixes (suffixes, type):
assert is_iterable_typed(suffixes, basestring)
assert isinstance(type, basestring)
for s in suffixes:
if s in __suffixes_to_types:
old_type = __suffixes_to_types [s]
if old_type != type:... | [
" Specifies that targets with suffix from 'suffixes' have the type 'type'.\n If a different type is already specified for any of syffixes, issues an error.\n "
] |
Please provide a description of the function:def set_scanner (type, scanner):
if __debug__:
from .scanner import Scanner
assert isinstance(type, basestring)
assert issubclass(scanner, Scanner)
validate (type)
__types [type]['scanner'] = scanner | [
" Sets a scanner class that will be used for this 'type'.\n "
] |
Please provide a description of the function:def get_scanner (type, prop_set):
if __debug__:
from .property_set import PropertySet
assert isinstance(type, basestring)
assert isinstance(prop_set, PropertySet)
if registered (type):
scanner_type = __types [type]['scanner']
... | [
" Returns a scanner instance appropriate to 'type' and 'property_set'.\n "
] |
Please provide a description of the function:def all_bases (type):
assert isinstance(type, basestring)
result = []
while type:
result.append (type)
type = __types [type]['base']
return result | [
" Returns type and all of its bases, in the order of their distance from type.\n "
] |
Please provide a description of the function:def all_derived (type):
assert isinstance(type, basestring)
result = [type]
for d in __types [type]['derived']:
result.extend (all_derived (d))
return result | [
" Returns type and all classes that derive from it, in the order of their distance from type.\n "
] |
Please provide a description of the function:def is_derived (type, base):
assert isinstance(type, basestring)
assert isinstance(base, basestring)
# TODO: this isn't very efficient, especially for bases close to type
if base in all_bases (type):
return True
else:
return False | [
" Returns true if 'type' is 'base' or has 'base' as its direct or indirect base.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.