Search is not available for this dataset
text
stringlengths
75
104k
def _list(api_list_class, arg_namespace, **extra): """ A common function for building methods of the "list showing". """ if arg_namespace.starting_point: ordering_field = (arg_namespace.ordering or '').lstrip('-') if ordering_field in ('', 'datetime_uploaded', 'datetime_created'): ...
def bar(iter_content, parts, title=''): """ Iterates over the "iter_content" and draws a progress bar to stdout. """ parts = max(float(parts), 1.0) cells = 10 progress = 0 step = cells / parts draw = lambda progress: sys.stdout.write( '\r[{0:10}] {1:.2f}% {2}'.format( '#...
def rest_request(verb, path, data=None, timeout=conf.DEFAULT, retry_throttled=conf.DEFAULT): """Makes REST API request and returns response as ``dict``. It provides auth headers as well and takes settings from ``conf`` module. Make sure that given ``path`` does not contain leading slash. ...
def uploading_request(verb, path, data=None, files=None, timeout=conf.DEFAULT): """Makes Uploading API request and returns response as ``dict``. It takes settings from ``conf`` module. Make sure that given ``path`` does not contain leading slash. Usage example:: >>> file_obj = open('photo.jp...
def home_mode_set_state(self, state, **kwargs): """Set the state of Home Mode""" # It appears that surveillance station needs lowercase text # true/false for the on switch if state not in (HOME_MODE_ON, HOME_MODE_OFF): raise ValueError('Invalid home mode state') api...
def home_mode_status(self, **kwargs): """Returns the status of Home Mode""" api = self._api_info['home_mode'] payload = dict({ 'api': api['name'], 'method': 'GetInfo', 'version': api['version'], '_sid': self._sid }, **kwargs) respon...
def camera_list(self, **kwargs): """Return a list of cameras.""" api = self._api_info['camera'] payload = dict({ '_sid': self._sid, 'api': api['name'], 'method': 'List', 'version': api['version'], }, **kwargs) response = self._get_j...
def camera_info(self, camera_ids, **kwargs): """Return a list of cameras matching camera_ids.""" api = self._api_info['camera'] payload = dict({ '_sid': self._sid, 'api': api['name'], 'method': 'GetInfo', 'version': api['version'], 'cam...
def camera_snapshot(self, camera_id, **kwargs): """Return bytes of camera image.""" api = self._api_info['camera'] payload = dict({ '_sid': self._sid, 'api': api['name'], 'method': 'GetSnapshot', 'version': api['version'], 'cameraId': c...
def camera_disable(self, camera_id, **kwargs): """Disable camera.""" api = self._api_info['camera'] payload = dict({ '_sid': self._sid, 'api': api['name'], 'method': 'Disable', 'version': 9, 'idList': camera_id, }, **kwargs) ...
def camera_event_motion_enum(self, camera_id, **kwargs): """Return motion settings matching camera_id.""" api = self._api_info['camera_event'] payload = dict({ '_sid': self._sid, 'api': api['name'], 'method': 'MotionEnum', 'version': api['version']...
def camera_event_md_param_save(self, camera_id, **kwargs): """Update motion settings matching camera_id with keyword args.""" api = self._api_info['camera_event'] payload = dict({ '_sid': self._sid, 'api': api['name'], 'method': 'MDParamSave', 'ver...
def update(self): """Update cameras and motion settings with latest from API.""" cameras = self._api.camera_list() self._cameras_by_id = {v.camera_id: v for i, v in enumerate(cameras)} motion_settings = [] for camera_id in self._cameras_by_id.keys(): motion_setting =...
def set_home_mode(self, state): """Set the state of Home Mode""" state_parameter = HOME_MODE_OFF if state: state_parameter = HOME_MODE_ON return self._api.home_mode_set_state(state_parameter)
def replace_ext(file_path, new_ext): """ >>> replace_ext('one/two/three.four.doc', '.html') 'one/two/three.four.html' >>> replace_ext('one/two/three.four.DOC', '.html') 'one/two/three.four.html' >>> replace_ext('one/two/three.four.DOC', 'html') 'one/two/three.four.html' """ if not ne...
def is_last_li(li, meta_data, current_numId): """ Determine if ``li`` is the last list item for a given list """ if not is_li(li, meta_data): return False w_namespace = get_namespace(li, 'w') next_el = li while True: # If we run out of element this must be the last list item ...
def get_single_list_nodes_data(li, meta_data): """ Find consecutive li tags that have content that have the same list id. """ yield li w_namespace = get_namespace(li, 'w') current_numId = get_numId(li, w_namespace) starting_ilvl = get_ilvl(li, w_namespace) el = li while True: ...
def get_ilvl(li, w_namespace): """ The ilvl on an li tag tells the li tag at what level of indentation this tag is at. This is used to determine if the li tag needs to be nested or not. """ ilvls = li.xpath('.//w:ilvl', namespaces=li.nsmap) if len(ilvls) == 0: return -1 return in...
def get_numId(li, w_namespace): """ The numId on an li tag maps to the numbering dictionary along side the ilvl to determine what the list should look like (unordered, digits, lower alpha, etc) """ numIds = li.xpath('.//w:numId', namespaces=li.nsmap) if len(numIds) == 0: return -1 ...
def create_list(list_type): """ Based on the passed in list_type create a list objects (ol/ul). In the future this function will also deal with what the numbering of an ordered list should look like. """ list_types = { 'bullet': 'ul', } el = etree.Element(list_types.get(list_type...
def get_v_merge(tc): """ vMerge is what docx uses to denote that a table cell is part of a rowspan. The first cell to have a vMerge is the start of the rowspan, and the vMerge will be denoted with 'restart'. If it is anything other than restart then it is a continuation of another rowspan. """ ...
def get_grid_span(tc): """ gridSpan is what docx uses to denote that a table cell has a colspan. This is much more simple than rowspans in that there is a one-to-one mapping from gridSpan to colspan. """ w_namespace = get_namespace(tc, 'w') grid_spans = tc.xpath('.//w:gridSpan', namespaces=t...
def get_td_at_index(tr, index): """ When calculating the rowspan for a given cell it is required to find all table cells 'below' the initial cell with a v_merge. This function will return the td element at the passed in index, taking into account colspans. """ current = 0 for td in tr.xpath(...
def style_is_false(style): """ For bold, italics and underline. Simply checking to see if the various tags are present will not suffice. If the tag is present and set to False then the style should not be present. """ if style is None: return False w_namespace = get_namespace(style, ...
def is_bold(r): """ The function will return True if the r tag passed in is considered bold. """ w_namespace = get_namespace(r, 'w') rpr = r.find('%srPr' % w_namespace) if rpr is None: return False bold = rpr.find('%sb' % w_namespace) return style_is_false(bold)
def is_italics(r): """ The function will return True if the r tag passed in is considered italicized. """ w_namespace = get_namespace(r, 'w') rpr = r.find('%srPr' % w_namespace) if rpr is None: return False italics = rpr.find('%si' % w_namespace) return style_is_false(italics...
def is_underlined(r): """ The function will return True if the r tag passed in is considered underlined. """ w_namespace = get_namespace(r, 'w') rpr = r.find('%srPr' % w_namespace) if rpr is None: return False underline = rpr.find('%su' % w_namespace) return style_is_false(un...
def is_title(p): """ Certain p tags are denoted as ``Title`` tags. This function will return True if the passed in p tag is considered a title. """ w_namespace = get_namespace(p, 'w') styles = p.xpath('.//w:pStyle', namespaces=p.nsmap) if len(styles) == 0: return False style = st...
def get_text_run_content_data(r): """ It turns out that r tags can contain both t tags and drawing tags. Since we need both, this function will return them in the order in which they are found. """ w_namespace = get_namespace(r, 'w') valid_elements = ( '%st' % w_namespace, '%...
def whole_line_styled(p): """ Checks to see if the whole p tag will end up being bold or italics. Returns a tuple (boolean, boolean). The first boolean will be True if the whole line is bold, False otherwise. The second boolean will be True if the whole line is italics, False otherwise. """ ...
def get_numbering_info(tree): """ There is a separate file called numbering.xml that stores how lists should look (unordered, digits, lower case letters, etc.). Parse that file and return a dictionary of what each combination should be based on list Id and level of indentation. """ if tree i...
def get_style_dict(tree): """ Some things that are considered lists are actually supposed to be H tags (h1, h2, etc.) These can be denoted by their styleId """ # This is a partial document and actual h1 is the document title, which # will be displayed elsewhere. headers = { 'heading ...
def get_relationship_info(tree, media, image_sizes): """ There is a separate file holds the targets to links as well as the targets for images. Return a dictionary based on the relationship id and the target. """ if tree is None: return {} result = {} # Loop through each relation...
def _get_document_data(f, image_handler=None): ''' ``f`` is a ``ZipFile`` that is open Extract out the document data, numbering data and the relationship data. ''' if image_handler is None: def image_handler(image_id, relationship_dict): return relationship_dict.get(image_id) ...
def get_ordered_list_type(meta_data, numId, ilvl): """ Return the list type. If numId or ilvl not in the numbering dict then default to returning decimal. This function only cares about ordered lists, unordered lists get dealt with elsewhere. """ # Early return if numId or ilvl are not val...
def build_list(li_nodes, meta_data): """ Build the list structure and return the root list """ # Need to keep track of all incomplete nested lists. ol_dict = {} # Need to keep track of the current indentation level. current_ilvl = -1 # Need to keep track of the current list id. cur...
def build_tr(tr, meta_data, row_spans): """ This will return a single tr element, with all tds already populated. """ # Create a blank tr element. tr_el = etree.Element('tr') w_namespace = get_namespace(tr, 'w') visited_nodes = [] for el in tr: if el in visited_nodes: ...
def build_table(table, meta_data): """ This returns a table object with all rows and cells correctly populated. """ # Create a blank table element. table_el = etree.Element('table') w_namespace = get_namespace(table, 'w') # Get the rowspan values for cells that have a rowspan. row_span...
def get_t_tag_content( t, parent, remove_bold, remove_italics, meta_data): """ Generate the string data that for this particular t tag. """ if t is None or t.text is None: return '' # Need to escape the text so that we do not accidentally put in text # that is not valid XML. ...
def get_element_content( p, meta_data, is_td=False, remove_italics=False, remove_bold=False, ): """ P tags are made up of several runs (r tags) of text. This function takes a p tag and constructs the text that should be part of the p tag. image_handler should be ...
def _strip_tag(tree, tag): """ Remove all tags that have the tag name ``tag`` """ for el in tree.iter(): if el.tag == tag: el.getparent().remove(el)
def convert(file_path, image_handler=None, fall_back=None, converter=None): """ ``file_path`` is a path to the file on the file system that you want to be converted to html. ``image_handler`` is a function that takes an image_id and a relationship_dict to generate the src attribute for image...
def find(dataset, url): '''Find the location of a dataset on disk, downloading if needed.''' fn = os.path.join(DATASETS, dataset) dn = os.path.dirname(fn) if not os.path.exists(dn): print('creating dataset directory: %s', dn) os.makedirs(dn) if not os.path.exists(fn): if sys....
def load_mnist(flatten=True, labels=False): '''Load the MNIST digits dataset.''' fn = find('mnist.pkl.gz', 'http://deeplearning.net/data/mnist/mnist.pkl.gz') h = gzip.open(fn, 'rb') if sys.version_info < (3, ): (timg, tlab), (vimg, vlab), (simg, slab) = pickle.load(h) else: (timg, tl...
def load_cifar(flatten=True, labels=False): '''Load the CIFAR10 image dataset.''' def extract(name): print('extracting data from {}'.format(name)) h = tar.extractfile(name) if sys.version_info < (3, ): d = pickle.load(h) else: d = pickle.load(h, encoding='...
def plot_images(imgs, loc, title=None, channels=1): '''Plot an array of images. We assume that we are given a matrix of data whose shape is (n*n, s*s*c) -- that is, there are n^2 images along the first axis of the array, and each image is c squares measuring s pixels on a side. Each row of the input wi...
def plot_layers(weights, tied_weights=False, channels=1): '''Create a plot of weights, visualized as "bottom-level" pixel arrays.''' if hasattr(weights[0], 'get_value'): weights = [w.get_value() for w in weights] k = min(len(weights), 9) imgs = np.eye(weights[0].shape[0]) for i, weight in en...
def plot_filters(filters): '''Create a plot of conv filters, visualized as pixel arrays.''' imgs = filters.get_value() N, channels, x, y = imgs.shape n = int(np.sqrt(N)) assert n * n == N, 'filters must contain a square number of rows!' assert channels == 1 or channels == 3, 'can only plot gray...
def batches(arrays, steps=100, batch_size=64, rng=None): '''Create a callable that generates samples from a dataset. Parameters ---------- arrays : list of ndarray (time-steps, data-dimensions) Arrays of data. Rows in these arrays are assumed to correspond to time steps, and columns to ...
def encode(self, txt): '''Encode a text string by replacing characters with alphabet index. Parameters ---------- txt : str A string to encode. Returns ------- classes : list of int A sequence of alphabet index values corresponding to the...
def classifier_batches(self, steps, batch_size, rng=None): '''Create a callable that returns a batch of training data. Parameters ---------- steps : int Number of time steps in each batch. batch_size : int Number of training examples per batch. rn...
def predict_sequence(self, labels, steps, streams=1, rng=None): '''Draw a sequential sample of class labels from this network. Parameters ---------- labels : list of int A list of integer class labels to get the classifier started. steps : int The number ...
def add_conv_weights(self, name, mean=0, std=None, sparsity=0): '''Add a convolutional weight array to this layer's parameters. Parameters ---------- name : str Name of the parameter to add. mean : float, optional Mean value for randomly-initialized weigh...
def encode(self, x, layer=None, sample=False, **kwargs): '''Encode a dataset using the hidden layer activations of our network. Parameters ---------- x : ndarray A dataset to encode. Rows of this dataset capture individual data points, while columns represent the...
def decode(self, z, layer=None, **kwargs): '''Decode an encoded dataset by computing the output layer activation. Parameters ---------- z : ndarray A matrix containing encoded data from this autoencoder. layer : int or str or :class:`Layer <layers.Layer>`, optional ...
def _find_output(self, layer): '''Find a layer output name for the given layer specifier. Parameters ---------- layer : None, int, str, or :class:`theanets.layers.Layer` A layer specification. If this is None, the "middle" layer in the network will be used (i.e.,...
def score(self, x, w=None, **kwargs): '''Compute R^2 coefficient of determination for a given input. Parameters ---------- x : ndarray (num-examples, num-inputs) An array containing data to be fed into the network. Multiple examples are arranged as rows in this a...
def monitors(self, **kwargs): '''Return expressions that should be computed to monitor training. Returns ------- monitors : list of (name, expression) pairs A list of named monitor expressions to compute for this network. ''' monitors = super(Classifier, self...
def predict(self, x, **kwargs): '''Compute a greedy classification for the given set of data. Parameters ---------- x : ndarray (num-examples, num-variables) An array containing examples to classify. Examples are given as the rows in this array. Returns ...
def predict_proba(self, x, **kwargs): '''Compute class posterior probabilities for the given set of data. Parameters ---------- x : ndarray (num-examples, num-variables) An array containing examples to predict. Examples are given as the rows in this array. ...
def predict_logit(self, x, **kwargs): '''Compute the logit values that underlie the softmax output. Parameters ---------- x : ndarray (num-examples, num-variables) An array containing examples to classify. Examples are given as the rows in this array. Re...
def score(self, x, y, w=None, **kwargs): '''Compute the mean accuracy on a set of labeled data. Parameters ---------- x : ndarray (num-examples, num-variables) An array containing examples to classify. Examples are given as the rows in this array. y : nda...
def batch_at(features, labels, seq_begins, seq_lengths): '''Extract a single batch of data to pass to the model being trained. Parameters ---------- features, labels : ndarray Arrays of the input features and target labels. seq_begins : ndarray Array of the start offsets of the spee...
def batches(dataset): '''Returns a callable that chooses sequences from netcdf data.''' seq_lengths = dataset.variables['seqLengths'].data seq_begins = np.concatenate(([0], np.cumsum(seq_lengths)[:-1])) def sample(): chosen = np.random.choice( list(range(len(seq_lengths))), BATCH_SI...
def load(self, path): '''Load a saved network from a pickle file on disk. This method sets the ``network`` attribute of the experiment to the loaded network model. Parameters ---------- filename : str Load the keyword arguments and parameters of a network fr...
def random_matrix(rows, cols, mean=0, std=1, sparsity=0, radius=0, diagonal=0, rng=None): '''Create a matrix of randomly-initialized weights. Parameters ---------- rows : int Number of rows of the weight matrix -- equivalently, the number of "input" units that the weight matrix connects...
def random_vector(size, mean=0, std=1, rng=None): '''Create a vector of randomly-initialized values. Parameters ---------- size : int Length of vecctor to create. mean : float, optional Mean value for initial vector values. Defaults to 0. std : float, optional Standard d...
def outputs_matching(outputs, patterns): '''Get the outputs from a network that match a pattern. Parameters ---------- outputs : dict or sequence of (str, theano expression) Output expressions to filter for matches. If this is a dictionary, its ``items()`` will be processed for matches....
def params_matching(layers, patterns): '''Get the parameters from a network that match a pattern. Parameters ---------- layers : list of :class:`theanets.layers.Layer` A list of network layers to retrieve parameters from. patterns : sequence of str A sequence of glob-style patterns ...
def from_kwargs(graph, **kwargs): '''Construct common regularizers from a set of keyword arguments. Keyword arguments not listed below will be passed to :func:`Regularizer.build` if they specify the name of a registered :class:`Regularizer`. Parameters ---------- graph : :class:`theanets.g...
def variables(self): '''A list of Theano variables used in this loss.''' result = [self._target] if self._weights is not None: result.append(self._weights) return result
def accuracy(self, outputs): '''Build a Theano expression for computing the accuracy of graph output. Parameters ---------- outputs : dict of Theano expressions A dictionary mapping network output names to Theano expressions representing the outputs of a computat...
def add_weights(self, name, nin, nout, mean=0, std=0, sparsity=0, radius=0, diagonal=0): '''Helper method to create a new weight matrix. Parameters ---------- name : str Name of parameter to define. nin : int, optional Size of "input" ...
def _scan(self, inputs, outputs, name='scan', step=None, constants=None): '''Helper method for defining a basic loop in theano. Parameters ---------- inputs : sequence of theano expressions Inputs to the scan operation. outputs : sequence of output specifiers ...
def _create_rates(self, dist='uniform', size=None, eps=1e-4): '''Create a rate parameter (usually for a recurrent network layer). Parameters ---------- dist : {'uniform', 'log'}, optional Distribution of rate values. Defaults to ``'uniform'``. size : int, optional ...
def build(name, layer, **kwargs): '''Construct an activation function by name. Parameters ---------- name : str or :class:`Activation` The name of the type of activation function to build, or an already-created instance of an activation function. layer : :class:`theanets.layers.Laye...
def itertrain(self, train, valid=None, **kwargs): '''Train a model using a training and validation set. This method yields a series of monitor values to the caller. After every iteration, a pair of monitor dictionaries is generated: one evaluated on the training dataset, and another eva...
def reservoir(xs, n, rng): '''Select a random sample of n items from xs.''' pool = [] for i, x in enumerate(xs): if len(pool) < n: pool.append(x / np.linalg.norm(x)) continue j = rng.randint(i + 1) if j < n: pool...
def itertrain(self, train, valid=None, **kwargs): '''Train a model using a training and validation set. This method yields a series of monitor values to the caller. After every iteration, a pair of monitor dictionaries is generated: one evaluated on the training dataset, and another eva...
def itertrain(self, train, valid=None, **kwargs): '''Train a model using a training and validation set. This method yields a series of monitor values to the caller. After every iteration, a pair of monitor dictionaries is generated: one evaluated on the training dataset, and another eva...
def itertrain(self, train, valid=None, **kwargs): '''Train a model using a training and validation set. This method yields a series of monitor values to the caller. After every iteration, a pair of monitor dictionaries is generated: one evaluated on the training dataset, and another eva...
def add_layer(self, layer=None, **kwargs): '''Add a :ref:`layer <layers>` to our network graph. Parameters ---------- layer : int, tuple, dict, or :class:`Layer <theanets.layers.base.Layer>` A value specifying the layer to add. For more information, please see :r...
def add_loss(self, loss=None, **kwargs): '''Add a :ref:`loss function <losses>` to the model. Parameters ---------- loss : str, dict, or :class:`theanets.losses.Loss` A loss function to add. If this is a Loss instance, it will be added immediately. If this is a s...
def set_loss(self, *args, **kwargs): '''Clear the current loss functions from the network and add a new one. All parameters and keyword arguments are passed to :func:`add_loss` after clearing the current losses. ''' self.losses = [] self.add_loss(*args, **kwargs)
def itertrain(self, train, valid=None, algo='rmsprop', subalgo='rmsprop', save_every=0, save_progress=None, **kwargs): '''Train our network, one batch at a time. This method yields a series of ``(train, valid)`` monitor pairs. The ``train`` value is a dictionary mapping names ...
def train(self, *args, **kwargs): '''Train the network until the trainer converges. All arguments are passed to :func:`itertrain`. Returns ------- training : dict A dictionary of monitor values computed using the training dataset, at the conclusion of tr...
def _hash(self, regularizers=()): '''Construct a string key for representing a computation graph. This key will be unique for a given (a) network topology, (b) set of losses, and (c) set of regularizers. Returns ------- key : str A hash representing the comp...
def build_graph(self, regularizers=()): '''Connect the layers in this network to form a computation graph. Parameters ---------- regularizers : list of :class:`theanets.regularizers.Regularizer` A list of the regularizers to apply while building the computation g...
def inputs(self): '''A list of Theano variables for feedforward computations.''' return [l.input for l in self.layers if isinstance(l, layers.Input)]
def variables(self): '''A list of Theano variables for loss computations.''' result = self.inputs seen = set(i.name for i in result) for loss in self.losses: for v in loss.variables: if v.name not in seen: result.append(v) ...
def find(self, which, param): '''Get a parameter from a layer in the network. Parameters ---------- which : int or str The layer that owns the parameter to return. If this is an integer, then 0 refers to the input layer, 1 refers to the first hidden ...
def feed_forward(self, x, **kwargs): '''Compute a forward pass of all layers from the given input. All keyword arguments are passed directly to :func:`build_graph`. Parameters ---------- x : ndarray (num-examples, num-variables) An array containing data to be fed in...
def predict(self, x, **kwargs): '''Compute a forward pass of the inputs, returning the network output. All keyword arguments end up being passed to :func:`build_graph`. Parameters ---------- x : ndarray (num-examples, num-variables) An array containing data to be fe...
def score(self, x, y, w=None, **kwargs): '''Compute R^2 coefficient of determination for a given labeled input. Parameters ---------- x : ndarray (num-examples, num-inputs) An array containing data to be fed into the network. Multiple examples are arranged as row...
def save(self, filename_or_handle): '''Save the state of this network to a pickle file on disk. Parameters ---------- filename_or_handle : str or file handle Save the state of this network to a pickle file. If this parameter is a string, it names the file where t...
def load(cls, filename_or_handle): '''Load a saved network from disk. Parameters ---------- filename_or_handle : str or file handle Load the state of this network from a pickle file. If this parameter is a string, it names the file where the pickle will be saved....
def loss(self, **kwargs): '''Return a variable representing the regularized loss for this network. The regularized loss includes both the :ref:`loss computation <losses>` for the network as well as any :ref:`regularizers <regularizers>` that are in place. Keyword arguments are ...
def monitors(self, **kwargs): '''Return expressions that should be computed to monitor training. Returns ------- monitors : list of (name, expression) pairs A list of named monitor expressions to compute for this network. ''' regs = regularizers.from_kwargs(s...
def updates(self, **kwargs): '''Return expressions to run as updates during network training. Returns ------- updates : list of (parameter, expression) pairs A list of named parameter update expressions for this network. ''' regs = regularizers.from_kwargs(se...
def input_name(self): '''Name of layer input (for layers with one input).''' if len(self._input_shapes) != 1: raise util.ConfigurationError( 'expected one input for layer "{}", got {}' .format(self.name, self._input_shapes)) return list(self._input_sha...