text
stringlengths
81
112k
Applies various filtering and processing options on token. Returns: The processed token. None if filtered. def _apply_options(self, token): """Applies various filtering and processing options on token. Returns: The processed token. None if filtered. """ ...
Yields tokens from texts as `(text_idx, word)` Args: texts: The list of texts. **kwargs: Supported args include: n_threads/num_threads: Number of threads to use. Uses num_cpus - 1 by default. batch_size: The number of texts to accumulate into a common wor...
Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required. def _append(lst, indices, value): """Adds `value` to `lst` list indexed by `indices`. Will create sub lists as required. """ for i, idx in enumerate(indices): # We need to loop because sometimes indices can incremen...
Supported args include: Args: n_threads/num_threads: Number of threads to use. Uses num_cpus - 1 by default. batch_size: The number of texts to accumulate into a common working set before processing. (Default value: 1000) def _parse_spacy_kwargs(**kwargs): """Supported args include...
Updates counts based on indices. The algorithm tracks the index change at i and update global counts for all indices beyond i with local counts tracked so far. def update(self, indices): """Updates counts based on indices. The algorithm tracks the index change at i and update global counts for ...
This will add the very last document to counts. We also get rid of counts[0] since that represents document level which doesnt come under anything else. We also convert all count values to numpy arrays so that stats can be computed easily. def finalize(self): """This will add the very last docu...
read text files in directory and returns them as array Args: directory: where the text files are Returns: Array of text def read_folder(directory): """read text files in directory and returns them as array Args: directory: where the text files are Returns: Array ...
returns array with positive and negative examples def read_pos_neg_data(path, folder, limit): """returns array with positive and negative examples""" training_pos_path = os.path.join(path, folder, 'pos') training_neg_path = os.path.join(path, folder, 'neg') X_pos = read_folder(training_pos_path) X...
Downloads (and caches) IMDB Moview Reviews. 25k training data, 25k test data Args: limit: get only first N items for each class Returns: [X_train, y_train, X_test, y_test] def imdb(limit=None, shuffle=True): """Downloads (and caches) IMDB Moview Reviews. 25k training data, 25k test data ...
Converts coordinates provided with reference to the center \ of the canvas (0, 0) to absolute coordinates which are used \ by the canvas object in which (0, 0) is located in the top \ left of the object. :param x: x value in pixels :param y: x value in pixels :return: No...
Sets the value of the graphic :param number: the number (must be between 0 and \ 'max_range' or the scale will peg the limits :return: None def set_value(self, number: (float, int)): """ Sets the value of the graphic :param number: the number (must be between 0 and \ ...
Draws the background of the dial :param divisions: the number of divisions between 'ticks' shown on the dial :return: None def _draw_background(self, divisions=10): """ Draws the background of the dial :param divisions: the number of divisions between 'ticks' s...
Removes all existing series and re-draws the axes. :return: None def draw_axes(self): """ Removes all existing series and re-draws the axes. :return: None """ self.canvas.delete('all') rect = 50, 50, self.w - 50, self.h - 50 self.canvas.create_rectangl...
Places a single point on the grid :param x: the x coordinate :param y: the y coordinate :param visible: True if the individual point should be visible :param color: the color of the point :param size: the point size in pixels :return: The absolute coordinates as a tuple ...
Plot a line of points :param points: a list of tuples, each tuple containing an (x, y) point :param color: the color of the line :param point_visibility: True if the points \ should be individually visible :return: None def plot_line(self, points: list, color='black', point_vis...
Works like range for doubles :param start: starting value :param stop: ending value :param step: the increment_value :param digits_to_round: the digits to which to round \ (makes floating-point numbers much easier to work with) :return: generator def frange(start, stop,...
Load a new image. :param img_data: the image data as a base64 string :return: None def _load_new(self, img_data: str): """ Load a new image. :param img_data: the image data as a base64 string :return: None """ self._image = tk.PhotoImage(data=img_data) ...
Change the LED to grey. :param on: Unused, here for API consistency with the other states :return: None def to_grey(self, on: bool=False): """ Change the LED to grey. :param on: Unused, here for API consistency with the other states :return: None """ se...
Change the LED to green (on or off). :param on: True or False :return: None def to_green(self, on: bool=False): """ Change the LED to green (on or off). :param on: True or False :return: None """ self._on = on if on: self._load_new(l...
Change the LED to red (on or off) :param on: True or False :return: None def to_red(self, on: bool=False): """ Change the LED to red (on or off) :param on: True or False :return: None """ self._on = on if on: self._load_new(led_red_on)...
Change the LED to yellow (on or off) :param on: True or False :return: None def to_yellow(self, on: bool=False): """ Change the LED to yellow (on or off) :param on: True or False :return: None """ self._on = on if on: self._load_new(le...
Forgets the current layout and redraws with the most recent information :return: None def _redraw(self): """ Forgets the current layout and redraws with the most recent information :return: None """ for row in self._rows: for widget in row: ...
Removes a specified row of data :param row_number: the row to remove (defaults to the last row) :return: None def remove_row(self, row_number: int=-1): """ Removes a specified row of data :param row_number: the row to remove (defaults to the last row) :return: None ...
Add a row of data to the current widget :param data: a row of data :return: None def add_row(self, data: list): """ Add a row of data to the current widget :param data: a row of data :return: None """ # validation if self.headers: if...
Add a row of data to the current widget, add a <Tab> \ binding to the last element of the last row, and set \ the focus at the beginning of the next row. :param data: a row of data :return: None def add_row(self, data: list=None): """ Add a row of data to the current wi...
Read the data contained in all entries as a list of dictionaries with the headers as the dictionary keys :return: list of dicts containing all tabular data def _read_as_dict(self): """ Read the data contained in all entries as a list of dictionaries with the headers as the dict...
Read the data contained in all entries as a list of lists containing all of the data :return: list of dicts containing all tabular data def _read_as_table(self): """ Read the data contained in all entries as a list of lists containing all of the data :return: list of d...
Add a row of buttons each with their own callbacks to the current widget. Each element in `data` will consist of a label and a command. :param data: a list of tuples of the form ('label', <callback>) :return: None def add_row(self, data: list): """ Add a row of buttons ...
Add a single row and re-draw as necessary :param key: the name and dict accessor :param default: the default value :param unit_label: the label that should be \ applied at the right of the entry :param enable: the 'enabled' state (defaults to True) :return: def add_row(...
Clears all entries. :return: None def reset(self): """ Clears all entries. :return: None """ for i in range(len(self.values)): self.values[i].delete(0, tk.END) if self.defaults[i] is not None: self.values[i].insert(0, self.defau...
Enable/disable inputs. :param enables_list: list containing enables for each key :return: None def change_enables(self, enables_list: list): """ Enable/disable inputs. :param enables_list: list containing enables for each key :return: None """ for i, en...
Load values into the key/values via dict. :param data: dict containing the key/values that should be inserted :return: None def load(self, data: dict): """ Load values into the key/values via dict. :param data: dict containing the key/values that should be inserted :re...
Retrieve the GUI elements for program use. :return: a dictionary containing all \ of the data from the key/value entries def get(self): """ Retrieve the GUI elements for program use. :return: a dictionary containing all \ of the data from the key/value entries ...
Clicked somewhere in the calendar. def _pressed(self, evt): """ Clicked somewhere in the calendar. """ x, y, widget = evt.x, evt.y, evt.widget item = widget.identify_row(y) column = widget.identify_column(x) if not column or not (item in self._items): ...
Clear the contents of the entry field and insert the contents of string. :param string: an str containing the text to display :return: def add(self, string: (str, list)): """ Clear the contents of the entry field and insert the contents of string. :param string...
Deletes itself. :return: None def remove(self): """ Deletes itself. :return: None """ for e in self._entries: e.grid_forget() e.destroy() self._remove_btn.grid_forget() self._remove_btn.destroy() self.deleted = True ...
Returns the value for the slot. :return: the entry value def get(self): """ Returns the value for the slot. :return: the entry value """ values = [e.get() for e in self._entries] if len(self._entries) == 1: return values[0] else: r...
Clears the current layout and re-draws all elements in self._slots :return: def _redraw(self): """ Clears the current layout and re-draws all elements in self._slots :return: """ if self._blank_label: self._blank_label.grid_forget() self._blank_la...
Add a new slot to the multi-frame containing the string. :param string: a string to insert :return: None def add(self, string: (str, list)): """ Add a new slot to the multi-frame containing the string. :param string: a string to insert :return: None """ s...
Clear out the multi-frame :return: def clear(self): """ Clear out the multi-frame :return: """ for slot in self._slots: slot.grid_forget() slot.destroy() self._slots = []
Clear the segment. :return: None def clear(self): """ Clear the segment. :return: None """ for _, frame in self._segments.items(): frame.configure(background=self._bg_color)
Sets the value of the 7-segment display :param value: the desired value :return: None def set_value(self, value: str): """ Sets the value of the 7-segment display :param value: the desired value :return: None """ self.clear() if '.' in value: ...
Takes a string and groups it appropriately with any period or other appropriate punctuation so that it is displayed correctly. :param value: a string containing an integer or float :return: None def _group(self, value: str): """ Takes a string and groups it appropriately...
Sets the displayed digits based on the value string. :param value: a string containing an integer or float value :return: None def set_value(self, value: str): """ Sets the displayed digits based on the value string. :param value: a string containing an integer or float value ...
Add a callback on change :param callback: callable function :return: None def add_callback(self, callback: callable): """ Add a callback on change :param callback: callable function :return: None """ def internal_callback(*args): try: ...
Set the current value :param value: :return: None def set(self, value: int): """ Set the current value :param value: :return: None """ max_value = int(''.join(['1' for _ in range(self._bit_width)]), 2) if value > max_value: raise Va...
Returns the bit value at position :param position: integer between 0 and <width>, inclusive :return: the value at position as a integer def get_bit(self, position: int): """ Returns the bit value at position :param position: integer between 0 and <width>, inclusive :re...
Toggles the value at position :param position: integer between 0 and 7, inclusive :return: None def toggle_bit(self, position: int): """ Toggles the value at position :param position: integer between 0 and 7, inclusive :return: None """ if position > (s...
Sets the value at position :param position: integer between 0 and 7, inclusive :return: None def set_bit(self, position: int): """ Sets the value at position :param position: integer between 0 and 7, inclusive :return: None """ if position > (self._bit_...
Clears the value at position :param position: integer between 0 and 7, inclusive :return: None def clear_bit(self, position: int): """ Clears the value at position :param position: integer between 0 and 7, inclusive :return: None """ if position > (self...
Populate this list by calling populate(), but only once. def _populate(self): """ Populate this list by calling populate(), but only once. """ if not self._populated: logging.debug("Populating lazy list %d (%s)" % (id(self), self.__class__.__name__)) try: self.po...
Register model in the admin, ignoring any previously registered models. Alternatively it could be used in the future to replace a previously registered model. def _register_admin(admin_site, model, admin_class): """ Register model in the admin, ignoring any previously registered models. Al...
If the 'optional' core fields (_site and _language) are required, list them here. def core_choice_fields(metadata_class): """ If the 'optional' core fields (_site and _language) are required, list them here. """ fields = [] if metadata_class._meta.use_sites: fields.append('_s...
Monkey patch the inline onto the given admin_class instance. def _monkey_inline(model, admin_class_instance, metadata_class, inline_class, admin_site): """ Monkey patch the inline onto the given admin_class instance. """ if model in metadata_class._meta.seo_models: # *Not* adding to the class attribute...
Decorator for register function that adds an appropriate inline. def _with_inline(func, admin_site, metadata_class, inline_class): """ Decorator for register function that adds an appropriate inline.""" def register(model_or_iterable, admin_class=None, **options): # Call the (bound) function we wer...
This is a questionable function that automatically adds our metadata inline to all relevant models in the site. def auto_register_inlines(admin_site, metadata_class): """ This is a questionable function that automatically adds our metadata inline to all relevant models in the site. """ inl...
Gets metadata linked from the given object. def get_linked_metadata(obj, name=None, context=None, site=None, language=None): """ Gets metadata linked from the given object. """ # XXX Check that 'modelinstance' and 'model' metadata are installed in backends # I believe that get_model() would return None if ...
For a given model and metadata class, ensure there is metadata for every instance. def populate_metadata(model, MetadataClass): """ For a given model and metadata class, ensure there is metadata for every instance. """ content_type = ContentType.objects.get_for_model(model) for instance in model.objec...
Cache instances, allowing generators to be used and reused. This fills a cache as the generator gets emptied, eventually reading exclusively from the cache. def __instances(self): """ Cache instances, allowing generators to be used and reused. This fills a cache as the gen...
Returns an appropriate value for the given name. This simply asks each of the instances for a value. def _resolve_value(self, name): """ Returns an appropriate value for the given name. This simply asks each of the instances for a value. """ for instance in self.__inst...
Return an object to conveniently access the appropriate values. def _get_formatted_data(cls, path, context=None, site=None, language=None): """ Return an object to conveniently access the appropriate values. """ return FormattedMetadata(cls(), cls._get_instances(path, context, site, language), path, si...
A sequence of instances to discover metadata. Each instance from each backend is looked up when possible/necessary. This is a generator to eliminate unnecessary queries. def _get_instances(cls, path, context=None, site=None, language=None): """ A sequence of instances to discover metad...
Resolves any template references in the given value. def _resolve(value, model_instance=None, context=None): """ Resolves any template references in the given value. """ if isinstance(value, basestring) and "{" in value: if context is None: context = Context() if model_instanc...
Validates the application of this backend to a given metadata def validate(options): """ Validates the application of this backend to a given metadata """ try: if options.backends.index('modelinstance') > options.backends.index('model'): raise Exception("Metadata ba...
Takes elements from the metadata class and creates a base model for all backend models . def _register_elements(self, elements): """ Takes elements from the metadata class and creates a base model for all backend models . """ self.elements = elements for key, obj in elements.items(): ...
Builds a subclass model for the given backend def _add_backend(self, backend): """ Builds a subclass model for the given backend """ md_type = backend.verbose_name base = backend().get_model(self) # TODO: Rename this field new_md_attrs = {'_metadata': self.metadata, '__module__'...
Gets the actual models to be used. def _set_seo_models(self, value): """ Gets the actual models to be used. """ seo_models = [] for model_name in value: if "." in model_name: app_label, model_name = model_name.split(".", 1) model = models.get_model(ap...
Discover certain illegal configurations def validate(self): """ Discover certain illegal configurations """ if not self.editable: assert self.populate_from is not NotSet, u"If field (%s) is not editable, you must set populate_from" % self.name
Create metadata instances for all models in seo_models if empty. Once you have created a single metadata instance, this will not run. This is because it is a potentially slow operation that need only be done once. If you want to ensure that everything is populated, run the populate_metad...
Populate this list with all views that take no arguments. def populate(self): """ Populate this list with all views that take no arguments. """ from django.conf import settings from django.core import urlresolvers self.append(("", "")) urlconf = settings.ROOT_URLCONF ...
Creates a generator by slicing ``data`` into chunks of ``block_size``. >>> data = range(10) >>> list(block_splitter(data, 2)) [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]] If ``data`` cannot be evenly divided by ``block_size``, the last block will simply be the remainder of the data. Example: >>> ...
Round coordinates of a geometric object to given precision. def round_geom(geom, precision=None): """Round coordinates of a geometric object to given precision.""" if geom['type'] == 'Point': x, y = geom['coordinates'] xp, yp = [x], [y] if precision is not None: xp = [round(...
Flatten a multi-dimensional array-like to a single dimensional sequence (as a generator). def flatten_multi_dim(sequence): """Flatten a multi-dimensional array-like to a single dimensional sequence (as a generator). """ for x in sequence: if (isinstance(x, collections.Iterable) ...
Convert text read from the first positional argument, stdin, or a file to GeoJSON and write to stdout. def cli(input, verbose, quiet, output_format, precision, indent): """Convert text read from the first positional argument, stdin, or a file to GeoJSON and write to stdout.""" verbosity = verbose - qu...
Get the GeoJSON geometry type label from a WKB type byte string. :param type_bytes: 4 byte string in big endian byte order containing a WKB type number. It may also contain a "has SRID" flag in the high byte (the first type, since this is big endian byte order), indicated as 0x20. If the SR...
Dump a GeoJSON-like `dict` to a WKB string. .. note:: The dimensions of the generated WKB will be inferred from the first vertex in the GeoJSON `coordinates`. It will be assumed that all vertices are uniform. There are 4 types: - 2D (X, Y): 2-dimensional geometry - Z (X, Y,...
Construct a GeoJSON `dict` from WKB (`string`). The resulting GeoJSON `dict` will include the SRID as an integer in the `meta` object. This was an arbitrary decision made by `geomet, the discussion of which took place here: https://github.com/geomet/geomet/issues/28. In order to be consistent with...
Utility function to get the WKB header (endian byte + type header), byte format string, and byte order string. def _header_bytefmt_byteorder(geom_type, num_dims, big_endian, meta=None): """ Utility function to get the WKB header (endian byte + type header), byte format string, and byte order string. ...
Dump a GeoJSON-like `dict` to a point WKB string. :param dict obj: GeoJson-like `dict` object. :param bool big_endian: If `True`, data values in the generated WKB will be represented using big endian byte order. Else, little endian. :param dict meta: Metadata associated with...
Dump a GeoJSON-like `dict` to a linestring WKB string. Input parameters and output are similar to :func:`_dump_point`. def _dump_linestring(obj, big_endian, meta): """ Dump a GeoJSON-like `dict` to a linestring WKB string. Input parameters and output are similar to :func:`_dump_point`. """ co...
Dump a GeoJSON-like `dict` to a multipoint WKB string. Input parameters and output are similar to :funct:`_dump_point`. def _dump_multipoint(obj, big_endian, meta): """ Dump a GeoJSON-like `dict` to a multipoint WKB string. Input parameters and output are similar to :funct:`_dump_point`. """ ...
Dump a GeoJSON-like `dict` to a multilinestring WKB string. Input parameters and output are similar to :funct:`_dump_point`. def _dump_multilinestring(obj, big_endian, meta): """ Dump a GeoJSON-like `dict` to a multilinestring WKB string. Input parameters and output are similar to :funct:`_dump_point...
Dump a GeoJSON-like `dict` to a multipolygon WKB string. Input parameters and output are similar to :funct:`_dump_point`. def _dump_multipolygon(obj, big_endian, meta): """ Dump a GeoJSON-like `dict` to a multipolygon WKB string. Input parameters and output are similar to :funct:`_dump_point`. ""...
Convert byte data for a Point to a GeoJSON `dict`. :param bool big_endian: If `True`, interpret the ``data_bytes`` in big endian order, else little endian. :param str type_bytes: 4-byte integer (as a binary string) indicating the geometry type (Point) and the dimensions (2D, Z, ...
Dump a GeoJSON-like `dict` to a WKT string. def dumps(obj, decimals=16): """ Dump a GeoJSON-like `dict` to a WKT string. """ try: geom_type = obj['type'] exporter = _dumps_registry.get(geom_type) if exporter is None: _unsupported_geom_type(geom_type) # Chec...
Construct a GeoJSON `dict` from WKT (`string`). def loads(string): """ Construct a GeoJSON `dict` from WKT (`string`). """ sio = StringIO.StringIO(string) # NOTE: This is not the intended purpose of `tokenize`, but it works. tokens = (x[1] for x in tokenize.generate_tokens(sio.readline)) to...
Since the tokenizer treats "-" and numeric strings as separate values, combine them and yield them as a single token. This utility encapsulates parsing of negative numeric values from WKT can be used generically in all parsers. def _tokenize_wkt(tokens): """ Since the tokenizer treats "-" and numer...
Round the input value to `decimals` places, and pad with 0's if the resulting value is less than `decimals`. :param value: The value to round :param decimals: Number of decimals places which should be displayed after the rounding. :return: str of the rounded value def _round_an...
Dump a GeoJSON-like Point object to WKT. :param dict obj: A GeoJSON-like `dict` representing a Point. :param int decimals: int which indicates the number of digits to display after the decimal point when formatting coordinates. :returns: WKT representation of the input GeoJ...
Dump a GeoJSON-like LineString object to WKT. Input parameters and return value are the LINESTRING equivalent to :func:`_dump_point`. def _dump_linestring(obj, decimals): """ Dump a GeoJSON-like LineString object to WKT. Input parameters and return value are the LINESTRING equivalent to :func...
Dump a GeoJSON-like Polygon object to WKT. Input parameters and return value are the POLYGON equivalent to :func:`_dump_point`. def _dump_polygon(obj, decimals): """ Dump a GeoJSON-like Polygon object to WKT. Input parameters and return value are the POLYGON equivalent to :func:`_dump_point`....
Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func:`_dump_point`. def _dump_multipoint(obj, decimals): """ Dump a GeoJSON-like MultiPoint object to WKT. Input parameters and return value are the MULTIPOINT equivalent to :func...
Dump a GeoJSON-like MultiLineString object to WKT. Input parameters and return value are the MULTILINESTRING equivalent to :func:`_dump_point`. def _dump_multilinestring(obj, decimals): """ Dump a GeoJSON-like MultiLineString object to WKT. Input parameters and return value are the MULTILINESTRIN...
Dump a GeoJSON-like MultiPolygon object to WKT. Input parameters and return value are the MULTIPOLYGON equivalent to :func:`_dump_point`. def _dump_multipolygon(obj, decimals): """ Dump a GeoJSON-like MultiPolygon object to WKT. Input parameters and return value are the MULTIPOLYGON equivalent to...
Dump a GeoJSON-like GeometryCollection object to WKT. Input parameters and return value are the GEOMETRYCOLLECTION equivalent to :func:`_dump_point`. The WKT conversions for each geometry in the collection are delegated to their respective functions. def _dump_geometrycollection(obj, decimals): "...
:param tokens: A generator of string tokens for the input WKT, begining just after the geometry type. The geometry type is consumed before we get to here. For example, if :func:`loads` is called with the input 'POINT(0.0 1.0)', ``tokens`` would generate the following values: .. ...
Has similar inputs and return value to to :func:`_load_point`, except is for handling LINESTRING geometry. :returns: A GeoJSON `dict` LineString representation of the WKT ``string``. def _load_linestring(tokens, string): """ Has similar inputs and return value to to :func:`_load_point`, except...
Has similar inputs and return value to to :func:`_load_point`, except is for handling POLYGON geometry. :returns: A GeoJSON `dict` Polygon representation of the WKT ``string``. def _load_polygon(tokens, string): """ Has similar inputs and return value to to :func:`_load_point`, except is f...
Has similar inputs and return value to to :func:`_load_point`, except is for handling MULTIPOINT geometry. :returns: A GeoJSON `dict` MultiPoint representation of the WKT ``string``. def _load_multipoint(tokens, string): """ Has similar inputs and return value to to :func:`_load_point`, except...
Has similar inputs and return value to to :func:`_load_point`, except is for handling MULTIPOLYGON geometry. :returns: A GeoJSON `dict` MultiPolygon representation of the WKT ``string``. def _load_multipolygon(tokens, string): """ Has similar inputs and return value to to :func:`_load_point`, ...