repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
JonathanRaiman/pytreebank
pytreebank/treelstm.py
assign_texts
python
def assign_texts(node, words, next_idx=0): if len(node.children) == 0: node.text = words[next_idx] return next_idx + 1 else: for child in node.children: next_idx = assign_texts(child, words, next_idx) return next_idx
Recursively assign the words to nodes by finding and assigning strings to the leaves of a tree in left to right order.
train
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L44-L56
[ "def assign_texts(node, words, next_idx=0):\n \"\"\"\n Recursively assign the words to nodes by finding and\n assigning strings to the leaves of a tree in left\n to right order.\n \"\"\"\n if len(node.children) == 0:\n node.text = words[next_idx]\n return next_idx + 1\n else:\n ...
""" Special loading methods for importing dataset as processed by the TreeLSTM code from https://github.com/stanfordnlp/treelstm """ from .labeled_trees import LabeledTree import codecs def import_tree_corpus(labels_path, parents_path, texts_path): """ Import dataset from the TreeLSTM data generation scrips. ...
JonathanRaiman/pytreebank
pytreebank/treelstm.py
read_tree
python
def read_tree(parents, labels, words): trees = {} root = None for i in range(1, len(parents) + 1): if not i in trees and parents[i - 1] != - 1: idx = i prev = None while True: parent = parents[idx - 1] if parent == -1: ...
Take as input a list of integers for parents and labels, along with a list of words, and reconstruct a LabeledTree.
train
https://github.com/JonathanRaiman/pytreebank/blob/7b4c671d3dff661cc3677e54db817e50c5a1c666/pytreebank/treelstm.py#L58-L89
[ "def assign_texts(node, words, next_idx=0):\n \"\"\"\n Recursively assign the words to nodes by finding and\n assigning strings to the leaves of a tree in left\n to right order.\n \"\"\"\n if len(node.children) == 0:\n node.text = words[next_idx]\n return next_idx + 1\n else:\n ...
""" Special loading methods for importing dataset as processed by the TreeLSTM code from https://github.com/stanfordnlp/treelstm """ from .labeled_trees import LabeledTree import codecs def import_tree_corpus(labels_path, parents_path, texts_path): """ Import dataset from the TreeLSTM data generation scrips. ...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.check_relations
python
def check_relations(self, relations): for rel in relations: if not rel: continue fields = rel.split('.', 1) local_field = fields[0] if local_field not in self.fields: raise ValueError('Unknown field "{}"'.format(local_field)) ...
Recursive function which checks if a relation is valid.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L102-L120
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_json_api_response
python
def format_json_api_response(self, data, many): ret = self.format_items(data, many) ret = self.wrap_response(ret, many) ret = self.render_included_data(ret) ret = self.render_meta_document(ret) return ret
Post-dump hook that formats serialized data as a top-level JSON API object. See: http://jsonapi.org/format/#document-top-level
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L123-L132
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.on_bind_field
python
def on_bind_field(self, field_name, field_obj): if _MARSHMALLOW_VERSION_INFO[0] < 3: if not field_obj.load_from: field_obj.load_from = self.inflect(field_name) else: if not field_obj.data_key: field_obj.data_key = self.inflect(field_name) r...
Schema hook override. When binding fields, set ``data_key`` (on marshmallow 3) or load_from (on marshmallow 2) to the inflected form of field_name.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L217-L227
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema._do_load
python
def _do_load(self, data, many=None, **kwargs): many = self.many if many is None else bool(many) # Store this on the instance so we have access to the included data # when processing relationships (``included`` is outside of the # ``data``). self.included_data = data.get('include...
Override `marshmallow.Schema._do_load` for custom JSON API handling. Specifically, we do this to format errors as JSON API Error objects, and to support loading of included data.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L229-L260
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema._extract_from_included
python
def _extract_from_included(self, data): return (item for item in self.included_data if item['type'] == data['type'] and str(item['id']) == str(data['id']))
Extract included data matching the items in ``data``. For each item in ``data``, extract the full data from the included data.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L262-L270
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.inflect
python
def inflect(self, text): return self.opts.inflect(text) if self.opts.inflect else text
Inflect ``text`` if the ``inflect`` class Meta option is defined, otherwise do nothing.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L272-L276
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_errors
python
def format_errors(self, errors, many): if not errors: return {} if isinstance(errors, (list, tuple)): return {'errors': errors} formatted_errors = [] if many: for index, errors in iteritems(errors): for field_name, field_errors in iter...
Format validation errors as JSON Error objects.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L280-L301
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_error
python
def format_error(self, field_name, message, index=None): pointer = ['/data'] if index is not None: pointer.append(str(index)) relationship = isinstance( self.declared_fields.get(field_name), BaseRelationship, ) if relationship: pointer.append...
Override-able hook to format a single error message as an Error object. See: http://jsonapi.org/format/#error-objects
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L303-L332
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_item
python
def format_item(self, item): # http://jsonapi.org/format/#document-top-level # Primary data MUST be either... a single resource object, a single resource # identifier object, or null, for requests that target single resources if not item: return None ret = self.dict_...
Format a single datum as a Resource object. See: http://jsonapi.org/format/#document-resource-objects
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L334-L379
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.format_items
python
def format_items(self, data, many): if many: return [self.format_item(item) for item in data] else: return self.format_item(data)
Format data as a Resource object or list of Resource objects. See: http://jsonapi.org/format/#document-resource-objects
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L381-L389
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.get_top_level_links
python
def get_top_level_links(self, data, many): self_link = None if many: if self.opts.self_url_many: self_link = self.generate_url(self.opts.self_url_many) else: if self.opts.self_url: self_link = data.get('links', {}).get('self', None) ...
Hook for adding links to the root of the response data.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L391-L402
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.get_resource_links
python
def get_resource_links(self, item): if self.opts.self_url: ret = self.dict_class() kwargs = resolve_params(item, self.opts.self_url_kwargs or {}) ret['self'] = self.generate_url(self.opts.self_url, **kwargs) return ret return None
Hook for adding links to a resource object.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L404-L411
[ "def resolve_params(obj, params, default=missing):\n \"\"\"Given a dictionary of keyword arguments, return the same dictionary except with\n values enclosed in `< >` resolved to attributes on `obj`.\n \"\"\"\n param_values = {}\n for name, attr_tpl in iteritems(params):\n attr_name = tpl(str(a...
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/schema.py
Schema.wrap_response
python
def wrap_response(self, data, many): ret = {'data': data} # self_url_many is still valid when there isn't any data, but self_url # may only be included if there is data in the ret if many or data: top_level_links = self.get_top_level_links(data, many) if top_level...
Wrap data and links according to the JSON API
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L413-L422
null
class Schema(ma.Schema): """Schema class that formats data according to JSON API 1.0. Must define the ``type_`` `class Meta` option. Example: :: from marshmallow_jsonapi import Schema, fields def dasherize(text): return text.replace('_', '-') class PostSchema(Schema):...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/fields.py
Relationship.extract_value
python
def extract_value(self, data): errors = [] if 'id' not in data: errors.append('Must have an `id` field') if 'type' not in data: errors.append('Must have a `type` field') elif data['type'] != self.type_: errors.append('Invalid `type` specified') ...
Extract the id key and validate the request structure.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/fields.py#L183-L208
null
class Relationship(BaseRelationship): """Framework-independent field which serializes to a "relationship object". See: http://jsonapi.org/format/#document-resource-object-relationships Examples: :: author = Relationship( related_url='/authors/{author_id}', related_url_kwar...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/fields.py
Relationship.deserialize
python
def deserialize(self, value, attr=None, data=None): if value is missing_: return super(Relationship, self).deserialize(value, attr, data) if not isinstance(value, dict) or 'data' not in value: # a relationships object does not need 'data' if 'links' is present if valu...
Deserialize ``value``. :raise ValidationError: If the value is not type `dict`, if the value does not contain a `data` key, and if the value is required but unspecified.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/fields.py#L210-L225
null
class Relationship(BaseRelationship): """Framework-independent field which serializes to a "relationship object". See: http://jsonapi.org/format/#document-resource-object-relationships Examples: :: author = Relationship( related_url='/authors/{author_id}', related_url_kwar...
marshmallow-code/marshmallow-jsonapi
examples/flask_example.py
J
python
def J(*args, **kwargs): response = jsonify(*args, **kwargs) response.mimetype = 'application/vnd.api+json' return response
Wrapper around jsonify that sets the Content-Type of the response to application/vnd.api+json.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/examples/flask_example.py#L102-L108
null
from flask import Flask, request, jsonify ### MODELS ### class Model: def __init__(self, **kwargs): for key, val in kwargs.items(): setattr(self, key, val) class Comment(Model): pass class Author(Model): pass class Post(Model): pass ### MOCK DATABASE ### comment1 = Comment(id...
marshmallow-code/marshmallow-jsonapi
marshmallow_jsonapi/utils.py
resolve_params
python
def resolve_params(obj, params, default=missing): param_values = {} for name, attr_tpl in iteritems(params): attr_name = tpl(str(attr_tpl)) if attr_name: attribute_value = get_value(obj, attr_name, default=default) if attribute_value is not missing: param_...
Given a dictionary of keyword arguments, return the same dictionary except with values enclosed in `< >` resolved to attributes on `obj`.
train
https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/utils.py#L38-L56
[ "def tpl(val):\n \"\"\"Return value within ``< >`` if possible, else return ``None``.\"\"\"\n match = _tpl_pattern.match(val)\n if match:\n return match.groups()[0]\n return None\n" ]
# -*- coding: utf-8 -*- """Utility functions. This module should be considered private API. """ import re import marshmallow from marshmallow.compat import iteritems from marshmallow.utils import get_value as _get_value, missing _MARSHMALLOW_VERSION_INFO = tuple( [int(part) for part in marshmallow.__version__.sp...
dnouri/nolearn
nolearn/lasagne/visualize.py
plot_conv_weights
python
def plot_conv_weights(layer, figsize=(6, 6)): W = layer.W.get_value() shape = W.shape nrows = np.ceil(np.sqrt(shape[0])).astype(int) ncols = nrows for feature_map in range(shape[1]): figs, axes = plt.subplots(nrows, ncols, figsize=figsize, squeeze=False) for ax in axes.flatten(): ...
Plot the weights of a specific layer. Only really makes sense with convolutional layers. Parameters ---------- layer : lasagne.layers.Layer
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L26-L54
null
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/visualize.py
plot_conv_activity
python
def plot_conv_activity(layer, x, figsize=(6, 8)): if x.shape[0] != 1: raise ValueError("Only one sample can be plotted at a time.") # compile theano function xs = T.tensor4('xs').astype(theano.config.floatX) get_activity = theano.function([xs], get_output(layer, xs)) activity = get_activit...
Plot the acitivities of a specific layer. Only really makes sense with layers that work 2D data (2D convolutional layers, 2D pooling layers ...). Parameters ---------- layer : lasagne.layers.Layer x : numpy.ndarray Only takes one sample at a time, i.e. x.shape[0] == 1.
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L57-L102
null
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/visualize.py
occlusion_heatmap
python
def occlusion_heatmap(net, x, target, square_length=7): if (x.ndim != 4) or x.shape[0] != 1: raise ValueError("This function requires the input data to be of " "shape (1, c, x, y), instead got {}".format(x.shape)) if square_length % 2 == 0: raise ValueError("Square lengt...
An occlusion test that checks an image for its critical parts. In this function, a square part of the image is occluded (i.e. set to 0) and then the net is tested for its propensity to predict the correct label. One should expect that this propensity shrinks of critical parts of the image are occluded....
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L105-L180
null
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/visualize.py
plot_occlusion
python
def plot_occlusion(net, X, target, square_length=7, figsize=(9, None)): return _plot_heat_map( net, X, figsize, lambda net, X, n: occlusion_heatmap( net, X, target[n], square_length))
Plot which parts of an image are particularly import for the net to classify the image correctly. See paper: Zeiler, Fergus 2013 Parameters ---------- net : NeuralNet instance The neural net to test. X : numpy.array The input data, should be of shape (b, c, 0, 1). Only makes ...
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L214-L250
[ "def _plot_heat_map(net, X, figsize, get_heat_image):\n if (X.ndim != 4):\n raise ValueError(\"This function requires the input data to be of \"\n \"shape (b, c, x, y), instead got {}\".format(X.shape))\n\n num_images = X.shape[0]\n if figsize[1] is None:\n figsize = (...
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/visualize.py
get_hex_color
python
def get_hex_color(layer_type): COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', '#3173A2', '#17649B', '#FFBB60', '#FFDAA9', '#FFC981', '#FCAC41', '#F29416', '#C54AAA', '#E698D4', '#D56CBE', '#B72F99', '#B0108D', '#75DF54', '#B3F1A0', '#91E875', '#5DD637', '#3FCD12'] hashed =...
Determines the hex color for a layer. :parameters: - layer_type : string Class name of the layer :returns: - color : string containing a hex color for filling block.
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L270-L293
null
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/visualize.py
make_pydot_graph
python
def make_pydot_graph(layers, output_shape=True, verbose=False): import pydotplus as pydot pydot_graph = pydot.Dot('Network', graph_type='digraph') pydot_nodes = {} pydot_edges = [] for i, layer in enumerate(layers): layer_name = getattr(layer, 'name', None) if layer_name is None: ...
:parameters: - layers : list List of the layers, as obtained from lasagne.layers.get_all_layers - output_shape: (default `True`) If `True`, the output shape of each layer will be displayed. - verbose: (default `False`) If `True`, layer attributes like filter s...
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L296-L352
[ "def get_hex_color(layer_type):\n \"\"\"\n Determines the hex color for a layer.\n :parameters:\n - layer_type : string\n Class name of the layer\n :returns:\n - color : string containing a hex color for filling block.\n \"\"\"\n COLORS = ['#4A88B3', '#98C1DE', '#6CA2C8', ...
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/visualize.py
draw_to_file
python
def draw_to_file(layers, filename, **kwargs): layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) ext = filename[filename.rfind('.') + 1:] with io.open(filename, 'wb') as fid: fid.write(dot.create(format=ext))
Draws a network diagram to a file :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - filename : string The filename to save output to - **kwargs: see docstring of make_pydot_graph for other options
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L355-L370
[ "def make_pydot_graph(layers, output_shape=True, verbose=False):\n \"\"\"\n :parameters:\n - layers : list\n List of the layers, as obtained from lasagne.layers.get_all_layers\n - output_shape: (default `True`)\n If `True`, the output shape of each layer will be displayed.\...
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/visualize.py
draw_to_notebook
python
def draw_to_notebook(layers, **kwargs): from IPython.display import Image layers = (layers.get_all_layers() if hasattr(layers, 'get_all_layers') else layers) dot = make_pydot_graph(layers, **kwargs) return Image(dot.create_png())
Draws a network diagram in an IPython notebook :parameters: - layers : list or NeuralNet instance List of layers or the neural net to draw. - **kwargs : see the docstring of make_pydot_graph for other options
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/visualize.py#L373-L385
[ "def make_pydot_graph(layers, output_shape=True, verbose=False):\n \"\"\"\n :parameters:\n - layers : list\n List of the layers, as obtained from lasagne.layers.get_all_layers\n - output_shape: (default `True`)\n If `True`, the output shape of each layer will be displayed.\...
from itertools import product from lasagne.layers import get_output from lasagne.layers import get_output_shape from lasagne.objectives import binary_crossentropy import matplotlib.pyplot as plt import numpy as np import theano import theano.tensor as T import io import lasagne def plot_loss(net): train_loss = ...
dnouri/nolearn
nolearn/lasagne/util.py
get_real_filter
python
def get_real_filter(layers, img_size): real_filter = np.zeros((len(layers), 2)) conv_mode = True first_conv_layer = True expon = np.ones((1, 2)) for i, layer in enumerate(layers[1:]): j = i + 1 if not conv_mode: real_filter[j] = img_size continue if ...
Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks.
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/util.py#L57-L91
[ "def is_conv2d(layers):\n if isinstance(layers, Layer):\n return isinstance(layers, tuple(convlayers))\n return any([isinstance(layer, tuple(convlayers))\n for layer in layers])\n", "def is_maxpool2d(layers):\n if isinstance(layers, Layer):\n return isinstance(layers, tuple(m...
from functools import reduce from operator import mul from lasagne.layers import Layer from lasagne.layers import Conv2DLayer from lasagne.layers import MaxPool2DLayer import numpy as np from tabulate import tabulate convlayers = [Conv2DLayer] maxpoollayers = [MaxPool2DLayer] try: from lasagne.layers.cuda_convnet...
dnouri/nolearn
nolearn/lasagne/util.py
get_receptive_field
python
def get_receptive_field(layers, img_size): receptive_field = np.zeros((len(layers), 2)) conv_mode = True first_conv_layer = True expon = np.ones((1, 2)) for i, layer in enumerate(layers[1:]): j = i + 1 if not conv_mode: receptive_field[j] = img_size continue ...
Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding and similar gimmicks.
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/util.py#L94-L129
[ "def is_conv2d(layers):\n if isinstance(layers, Layer):\n return isinstance(layers, tuple(convlayers))\n return any([isinstance(layer, tuple(convlayers))\n for layer in layers])\n", "def is_maxpool2d(layers):\n if isinstance(layers, Layer):\n return isinstance(layers, tuple(m...
from functools import reduce from operator import mul from lasagne.layers import Layer from lasagne.layers import Conv2DLayer from lasagne.layers import MaxPool2DLayer import numpy as np from tabulate import tabulate convlayers = [Conv2DLayer] maxpoollayers = [MaxPool2DLayer] try: from lasagne.layers.cuda_convnet...
dnouri/nolearn
nolearn/decaf.py
ConvNetFeatures.prepare_image
python
def prepare_image(self, image): from decaf.util import transform # soft dep _JEFFNET_FLIP = True # first, extract the 256x256 center. image = transform.scale_and_extract(transform.as_rgb(image), 256) # convert to [0,255] float32 image = image.astype(np.float32) * 255. ...
Returns image of shape `(256, 256, 3)`, as expected by `transform` when `classify_direct = True`.
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/decaf.py#L138-L154
null
class ConvNetFeatures(BaseEstimator): """Extract features from images using a pretrained ConvNet. Based on Yangqing Jia and Jeff Donahue's `DeCAF <https://github.com/UCB-ICSI-Vision-Group/decaf-release/wiki>`_. Please make sure you read and accept DeCAF's license before you use this class. If ...
dnouri/nolearn
nolearn/metrics.py
multiclass_logloss
python
def multiclass_logloss(actual, predicted, eps=1e-15): # Convert 'actual' to a binary array if it's not already: if len(actual.shape) == 1: actual2 = np.zeros((actual.shape[0], predicted.shape[1])) for i, val in enumerate(actual): actual2[i, val] = 1 actual = actual2 clip...
Multi class version of Logarithmic Loss metric. :param actual: Array containing the actual target classes :param predicted: Matrix with class predictions, one probability per class
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/metrics.py#L8-L24
null
from __future__ import print_function import numpy as np from sklearn.base import clone from sklearn.metrics import f1_score class LearningCurve(object): score_func = staticmethod(f1_score) def __init__(self, score_func=None): if score_func is None: score_func = self.score_func ...
dnouri/nolearn
nolearn/lasagne/base.py
objective
python
def objective(layers, loss_function, target, aggregate=aggregate, deterministic=False, l1=0, l2=0, get_output_kw=None): if get_output_kw is None: get_output_kw = {} output_layer = layers[-1] network_out...
Default implementation of the NeuralNet objective. :param layers: The underlying layers of the NeuralNetwork :param loss_function: The callable loss function to use :param target: the expected output :param aggregate: the aggregation function to use :param deterministic: Whether or not to get a de...
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L166-L202
null
from __future__ import absolute_import from .._compat import basestring from .._compat import chain_exception from .._compat import pickle from collections import OrderedDict, Iterable import itertools from pydoc import locate from warnings import warn from time import time from lasagne.layers import get_all_layers f...
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.initialize
python
def initialize(self): if getattr(self, '_initialized', False): return out = getattr(self, '_output_layers', None) if out is None: self.initialize_layers() self._check_for_unused_kwargs() iter_funcs = self._create_iter_funcs( self.layers_, sel...
Initializes the network. Checks that no extra kwargs were passed to the constructor, and compiles the train, predict, and evaluation functions. Subsequent calls to this function will return without any action.
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L473-L493
null
class NeuralNet(BaseEstimator): """A configurable Neural Network estimator based on Lasagne. Compatible with scikit-learn estimators. Attributes ---------- train_history_: A list of network training info for each epoch. Each index contains a dictionary with the following keys ...
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.initialize_layers
python
def initialize_layers(self, layers=None): if layers is not None: self.layers = layers self.layers_ = Layers() #If a Layer, or a list of Layers was passed in if isinstance(self.layers[0], Layer): for out_layer in self.layers: for i, layer in enumer...
Sets up the Lasagne layers :param layers: The dictionary of layers, or a :class:`lasagne.Layers` instance, describing the underlying network :return: the output layer of the underlying lasagne network. :seealso: :ref:`layer-def`
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L512-L616
[ "def chain_exception(exc1, exc2):\n exec(\"raise exc1 from exc2\")\n", "def values(self):\n return list(super(Layers, self).values())\n" ]
class NeuralNet(BaseEstimator): """A configurable Neural Network estimator based on Lasagne. Compatible with scikit-learn estimators. Attributes ---------- train_history_: A list of network training info for each epoch. Each index contains a dictionary with the following keys ...
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.fit
python
def fit(self, X, y, epochs=None): if self.check_input: X, y = self._check_good_input(X, y) if self.use_label_encoder: self.enc_ = LabelEncoder() y = self.enc_.fit_transform(y).astype(np.int32) self.classes_ = self.enc_.classes_ self.initialize() ...
Runs the training loop for a given number of epochs :param X: The input data :param y: The ground truth :param epochs: The number of epochs to run, if `None` runs for the network's :attr:`max_epochs` :return: This instance
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L680-L703
null
class NeuralNet(BaseEstimator): """A configurable Neural Network estimator based on Lasagne. Compatible with scikit-learn estimators. Attributes ---------- train_history_: A list of network training info for each epoch. Each index contains a dictionary with the following keys ...
dnouri/nolearn
nolearn/lasagne/base.py
NeuralNet.partial_fit
python
def partial_fit(self, X, y, classes=None): return self.fit(X, y, epochs=1)
Runs a single epoch using the provided data :return: This instance
train
https://github.com/dnouri/nolearn/blob/2ef346c869e80fc90247916e4aea5cfa7cf2edda/nolearn/lasagne/base.py#L705-L711
null
class NeuralNet(BaseEstimator): """A configurable Neural Network estimator based on Lasagne. Compatible with scikit-learn estimators. Attributes ---------- train_history_: A list of network training info for each epoch. Each index contains a dictionary with the following keys ...
ericsuh/dirichlet
dirichlet/dirichlet.py
pdf
python
def pdf(alphas): '''Returns a Dirichlet PDF function''' alphap = alphas - 1 c = np.exp(gammaln(alphas.sum()) - gammaln(alphas).sum()) def dirichlet(xs): '''N x K array''' return c * (xs**alphap).prod(axis=1) return dirichlet
Returns a Dirichlet PDF function
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L95-L102
null
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
meanprecision
python
def meanprecision(a): '''Mean and precision of Dirichlet distribution. Parameters ---------- a : array Parameters of Dirichlet distribution. Returns ------- mean : array Numbers [0,1] of the means of the Dirichlet distribution. precision : float Precision or con...
Mean and precision of Dirichlet distribution. Parameters ---------- a : array Parameters of Dirichlet distribution. Returns ------- mean : array Numbers [0,1] of the means of the Dirichlet distribution. precision : float Precision or concentration parameter of the D...
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L104-L121
null
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
loglikelihood
python
def loglikelihood(D, a): '''Compute log likelihood of Dirichlet distribution, i.e. log p(D|a). Parameters ---------- D : 2D array where ``N`` is the number of observations, ``K`` is the number of parameters for the Dirichlet distribution. a : array Parameters for the Dirichl...
Compute log likelihood of Dirichlet distribution, i.e. log p(D|a). Parameters ---------- D : 2D array where ``N`` is the number of observations, ``K`` is the number of parameters for the Dirichlet distribution. a : array Parameters for the Dirichlet distribution. Returns ...
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L123-L140
null
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
mle
python
def mle(D, tol=1e-7, method='meanprecision', maxiter=None): '''Iteratively computes maximum likelihood Dirichlet distribution for an observed data set, i.e. a for which log p(D|a) is maximum. Parameters ---------- D : 2D array ``N x K`` array of numbers from [0,1] where ``N`` is the number ...
Iteratively computes maximum likelihood Dirichlet distribution for an observed data set, i.e. a for which log p(D|a) is maximum. Parameters ---------- D : 2D array ``N x K`` array of numbers from [0,1] where ``N`` is the number of observations, ``K`` is the number of parameters for the ...
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L142-L171
[ "def _meanprecision(D, tol=1e-7, maxiter=None):\n '''Mean and precision alternating method for MLE of Dirichlet\n distribution'''\n N, K = D.shape\n logp = log(D).mean(axis=0)\n a0 = _init_a(D)\n s0 = a0.sum()\n if s0 < 0:\n a0 = a0/s0\n s0 = 1\n elif s0 == 0:\n a0 = one...
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
_fixedpoint
python
def _fixedpoint(D, tol=1e-7, maxiter=None): '''Simple fixed point iteration method for MLE of Dirichlet distribution''' N, K = D.shape logp = log(D).mean(axis=0) a0 = _init_a(D) # Start updating if maxiter is None: maxiter = MAXINT for i in xrange(maxiter): a1 = _ipsi(psi(a0...
Simple fixed point iteration method for MLE of Dirichlet distribution
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L173-L189
[ "def loglikelihood(D, a):\n '''Compute log likelihood of Dirichlet distribution, i.e. log p(D|a).\n\n Parameters\n ----------\n D : 2D array\n where ``N`` is the number of observations, ``K`` is the number of\n parameters for the Dirichlet distribution.\n a : array\n Parameters f...
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
_meanprecision
python
def _meanprecision(D, tol=1e-7, maxiter=None): '''Mean and precision alternating method for MLE of Dirichlet distribution''' N, K = D.shape logp = log(D).mean(axis=0) a0 = _init_a(D) s0 = a0.sum() if s0 < 0: a0 = a0/s0 s0 = 1 elif s0 == 0: a0 = ones(a.shape) / len...
Mean and precision alternating method for MLE of Dirichlet distribution
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L191-L219
[ "def loglikelihood(D, a):\n '''Compute log likelihood of Dirichlet distribution, i.e. log p(D|a).\n\n Parameters\n ----------\n D : 2D array\n where ``N`` is the number of observations, ``K`` is the number of\n parameters for the Dirichlet distribution.\n a : array\n Parameters f...
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
_fit_s
python
def _fit_s(D, a0, logp, tol=1e-7, maxiter=1000): '''Assuming a fixed mean for Dirichlet distribution, maximize likelihood for preicision a.k.a. s''' N, K = D.shape s1 = a0.sum() m = a0 / s1 mlogp = (m*logp).sum() for i in xrange(maxiter): s0 = s1 g = psi(s1) - (m*psi(s1*m)).s...
Assuming a fixed mean for Dirichlet distribution, maximize likelihood for preicision a.k.a. s
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L221-L249
null
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
_fit_m
python
def _fit_m(D, a0, logp, tol=1e-7, maxiter=1000): '''With fixed precision s, maximize mean m''' N,K = D.shape s = a0.sum() for i in xrange(maxiter): m = a0 / s a1 = _ipsi(logp + (m*(psi(a0) - logp)).sum()) a1 = a1/a1.sum() * s if norm(a1 - a0) < tol: return a...
With fixed precision s, maximize mean m
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L251-L266
null
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
_piecewise
python
def _piecewise(x, condlist, funclist, *args, **kw): '''Fixed version of numpy.piecewise for 0-d arrays''' x = asanyarray(x) n2 = len(funclist) if isscalar(condlist) or \ (isinstance(condlist, np.ndarray) and condlist.ndim == 0) or \ (x.ndim > 0 and condlist[0].ndim == 0): ...
Fixed version of numpy.piecewise for 0-d arrays
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L268-L316
null
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
_init_a
python
def _init_a(D): '''Initial guess for Dirichlet alpha parameters given data D''' E = D.mean(axis=0) E2 = (D**2).mean(axis=0) return ((E[0] - E2[0])/(E2[0]-E[0]**2)) * E
Initial guess for Dirichlet alpha parameters given data D
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L318-L322
null
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/dirichlet.py
_ipsi
python
def _ipsi(y, tol=1.48e-9, maxiter=10): '''Inverse of psi (digamma) using Newton's method. For the purposes of Dirichlet MLE, since the parameters a[i] must always satisfy a > 0, we define ipsi :: R -> (0,inf).''' y = asanyarray(y, dtype='float') x0 = _piecewise(y, [y >= -2.22, y < -2.22], ...
Inverse of psi (digamma) using Newton's method. For the purposes of Dirichlet MLE, since the parameters a[i] must always satisfy a > 0, we define ipsi :: R -> (0,inf).
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/dirichlet.py#L324-L337
[ "def _trigamma(x):\n return polygamma(1, x)\n", "def _piecewise(x, condlist, funclist, *args, **kw):\n '''Fixed version of numpy.piecewise for 0-d arrays'''\n x = asanyarray(x)\n n2 = len(funclist)\n if isscalar(condlist) or \\\n (isinstance(condlist, np.ndarray) and condlist.ndim == 0) ...
# Copyright (C) 2012 Eric J. Suh # # This file is subject to the terms and conditions defined in file # 'LICENSE.txt', which is part of this source code package. '''Dirichlet.py Maximum likelihood estimation and likelihood ratio tests of Dirichlet distribution models of data. Most of this package is a port of Thomas...
ericsuh/dirichlet
dirichlet/simplex.py
cartesian
python
def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1]) >>> cartesian((0,0,1)) ...
Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the first quadrant, i.e.:: >>> cartesian((1,0,0)) array([0, 0]) >>> cartesian((0,1,0)) array([0, 1]) >>> cartesian((0,0,1)) array([0.5, 0.866025403784438...
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L13-L38
null
import numpy as np import matplotlib import matplotlib.pyplot as plt __all__ = [ 'cartesian', 'barycentric', 'scatter', 'contour', 'contourf', ] def barycentric(points): '''Inverse of :func:`cartesian`.''' points = np.asanyarray(points) ndim = points.ndim if ndim == 1: poi...
ericsuh/dirichlet
dirichlet/simplex.py
barycentric
python
def barycentric(points): '''Inverse of :func:`cartesian`.''' points = np.asanyarray(points) ndim = points.ndim if ndim == 1: points = points.reshape((1,points.size)) c = (2/np.sqrt(3.0))*points[:,1] b = (2*points[:,0] - c)/2.0 a = 1.0 - c - b out = np.vstack([a,b,c]).T if ndi...
Inverse of :func:`cartesian`.
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L40-L52
null
import numpy as np import matplotlib import matplotlib.pyplot as plt __all__ = [ 'cartesian', 'barycentric', 'scatter', 'contour', 'contourf', ] def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the f...
ericsuh/dirichlet
dirichlet/simplex.py
scatter
python
def scatter(points, vertexlabels=None, **kwargs): '''Scatter plot of barycentric 2-simplex points on a 2D triangle. :param points: Points on a 2-simplex. :type points: N x 3 list or ndarray. :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b =...
Scatter plot of barycentric 2-simplex points on a 2D triangle. :param points: Points on a 2-simplex. :type points: N x 3 list or ndarray. :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``, ``c == (0,0,1)``. :type vertexla...
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L54-L72
[ "def cartesian(points):\n '''Converts array of barycentric coordinates on a 2-simplex to an array of\n Cartesian coordinates on a 2D triangle in the first quadrant, i.e.::\n\n >>> cartesian((1,0,0))\n array([0, 0])\n >>> cartesian((0,1,0))\n array([0, 1])\n >>> cartesian((0,...
import numpy as np import matplotlib import matplotlib.pyplot as plt __all__ = [ 'cartesian', 'barycentric', 'scatter', 'contour', 'contourf', ] def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the f...
ericsuh/dirichlet
dirichlet/simplex.py
contour
python
def contour(f, vertexlabels=None, **kwargs): '''Contour line plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. :param f: Function to evaluate on N x 3 ndarray of coordinates :type f: ``ufunc`` :param vertexlabels: Labels for corners of plot in the order ``(a, b,...
Contour line plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. :param f: Function to evaluate on N x 3 ndarray of coordinates :type f: ``ufunc`` :param vertexlabels: Labels for corners of plot in the order ``(a, b, c)`` where ``a == (1,0,0)``, ``b == (0,1,0)``, ...
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L74-L86
[ "def _contour(f, vertexlabels=None, contourfunc=None, **kwargs):\n '''Workhorse function for the above, where ``contourfunc`` is the contour\n plotting function to use for actual plotting.'''\n\n if contourfunc is None:\n contourfunc = plt.tricontour\n if vertexlabels is None:\n vertexlabe...
import numpy as np import matplotlib import matplotlib.pyplot as plt __all__ = [ 'cartesian', 'barycentric', 'scatter', 'contour', 'contourf', ] def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the f...
ericsuh/dirichlet
dirichlet/simplex.py
contourf
python
def contourf(f, vertexlabels=None, **kwargs): '''Filled contour plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. Function signature is identical to :func:`contour` with the caveat that ``**kwargs`` are passed on to :func:`plt.tricontourf`.''' return _contour(f, vertexl...
Filled contour plot on a 2D triangle of a function evaluated at barycentric 2-simplex points. Function signature is identical to :func:`contour` with the caveat that ``**kwargs`` are passed on to :func:`plt.tricontourf`.
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L88-L94
[ "def _contour(f, vertexlabels=None, contourfunc=None, **kwargs):\n '''Workhorse function for the above, where ``contourfunc`` is the contour\n plotting function to use for actual plotting.'''\n\n if contourfunc is None:\n contourfunc = plt.tricontour\n if vertexlabels is None:\n vertexlabe...
import numpy as np import matplotlib import matplotlib.pyplot as plt __all__ = [ 'cartesian', 'barycentric', 'scatter', 'contour', 'contourf', ] def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the f...
ericsuh/dirichlet
dirichlet/simplex.py
_contour
python
def _contour(f, vertexlabels=None, contourfunc=None, **kwargs): '''Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.''' if contourfunc is None: contourfunc = plt.tricontour if vertexlabels is None: vertexlabels = ('1','2...
Workhorse function for the above, where ``contourfunc`` is the contour plotting function to use for actual plotting.
train
https://github.com/ericsuh/dirichlet/blob/bf39a6d219348cbb4ed95dc195587a9c55c633b9/dirichlet/simplex.py#L96-L114
[ "def barycentric(points):\n '''Inverse of :func:`cartesian`.'''\n points = np.asanyarray(points)\n ndim = points.ndim\n if ndim == 1:\n points = points.reshape((1,points.size))\n c = (2/np.sqrt(3.0))*points[:,1]\n b = (2*points[:,0] - c)/2.0\n a = 1.0 - c - b\n out = np.vstack([a,b,c]...
import numpy as np import matplotlib import matplotlib.pyplot as plt __all__ = [ 'cartesian', 'barycentric', 'scatter', 'contour', 'contourf', ] def cartesian(points): '''Converts array of barycentric coordinates on a 2-simplex to an array of Cartesian coordinates on a 2D triangle in the f...
cognitect/transit-python
transit/reader.py
Reader.register
python
def register(self, key_or_tag, f_val): self.reader.decoder.register(key_or_tag, f_val)
Register a custom transit tag and decoder/parser function for use during reads.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/reader.py#L45-L49
null
class Reader(object): """The top-level object for reading in Transit data and converting it to Python objects. During initialization, you must specify the protocol used for unmarshalling the data- json or msgpack. """ def __init__(self, protocol="json"): if protocol in ("json", "json_verbos...
cognitect/transit-python
transit/reader.py
Reader.readeach
python
def readeach(self, stream, **kwargs): for o in self.reader.loadeach(stream): yield o
Temporary hook for API while streaming reads are in experimental phase. Read each object from stream as available with generator. JSON blocks indefinitely waiting on JSON entities to arrive. MsgPack requires unpacker property to be fed stream using unpacker.feed() method.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/reader.py#L51-L59
[ "def loadeach(self, stream):\n for o in sosjson.items(stream, object_pairs_hook=OrderedDict):\n yield self.decoder.decode(o)\n" ]
class Reader(object): """The top-level object for reading in Transit data and converting it to Python objects. During initialization, you must specify the protocol used for unmarshalling the data- json or msgpack. """ def __init__(self, protocol="json"): if protocol in ("json", "json_verbos...
cognitect/transit-python
transit/rolling_cache.py
RollingCache.decode
python
def decode(self, name, as_map_key=False): if is_cache_key(name) and (name in self.key_to_value): return self.key_to_value[name] return self.encache(name) if is_cacheable(name, as_map_key) else name
Always returns the name
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/rolling_cache.py#L61-L65
[ "def is_cache_key(name):\n return len(name) and (name[0] == SUB and name != MAP_AS_ARR)\n" ]
class RollingCache(object): """This is the internal cache used by python-transit for cacheing and expanding map keys during writing and reading. The cache enables transit to minimize the amount of duplicate data sent over the wire, effectively compressing down the overall payload size. The cache is no...
cognitect/transit-python
transit/rolling_cache.py
RollingCache.encode
python
def encode(self, name, as_map_key=False): if name in self.key_to_value: return self.key_to_value[name] return self.encache(name) if is_cacheable(name, as_map_key) else name
Returns the name the first time and the key after that
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/rolling_cache.py#L67-L71
[ "def is_cacheable(string, as_map_key=False):\n return string and len(string) >= MIN_SIZE_CACHEABLE \\\n and (as_map_key \\\n or (string[:2] in [\"~#\", \"~$\", \"~:\"]))\n" ]
class RollingCache(object): """This is the internal cache used by python-transit for cacheing and expanding map keys during writing and reading. The cache enables transit to minimize the amount of duplicate data sent over the wire, effectively compressing down the overall payload size. The cache is no...
cognitect/transit-python
transit/sosjson.py
read_chunk
python
def read_chunk(stream): chunk = stream.read(1) while chunk in SKIP: chunk = stream.read(1) if chunk == "\"": chunk += stream.read(1) while not chunk.endswith("\""): if chunk[-1] == ESCAPE: chunk += stream.read(2) else: chunk += ...
Ignore whitespace outside of strings. If we hit a string, read it in its entirety.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/sosjson.py#L25-L39
null
## copyright 2014 cognitect. all rights reserved. ## ## licensed under the apache license, version 2.0 (the "license"); ## you may not use this file except in compliance with the license. ## you may obtain a copy of the license at ## ## http://www.apache.org/licenses/license-2.0 ## ## unless required by applicable...
cognitect/transit-python
transit/sosjson.py
items
python
def items(stream, **kwargs): for s in yield_json(stream): yield json.loads(s, **kwargs)
External facing items. Will return item from stream as available. Currently waits in loop waiting for next item. Can pass keywords that json.loads accepts (such as object_pairs_hook)
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/sosjson.py#L42-L48
[ "def yield_json(stream):\n \"\"\"Uses array and object delimiter counts for balancing.\n \"\"\"\n buff = u\"\"\n arr_count = 0\n obj_count = 0\n while True:\n buff += read_chunk(stream)\n\n # If we finish parsing all objs or arrays, yield a finished JSON\n # entity.\n i...
## copyright 2014 cognitect. all rights reserved. ## ## licensed under the apache license, version 2.0 (the "license"); ## you may not use this file except in compliance with the license. ## you may obtain a copy of the license at ## ## http://www.apache.org/licenses/license-2.0 ## ## unless required by applicable...
cognitect/transit-python
transit/sosjson.py
yield_json
python
def yield_json(stream): buff = u"" arr_count = 0 obj_count = 0 while True: buff += read_chunk(stream) # If we finish parsing all objs or arrays, yield a finished JSON # entity. if buff.endswith('{'): obj_count += 1 if buff.endswith('['): a...
Uses array and object delimiter counts for balancing.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/sosjson.py#L51-L77
[ "def read_chunk(stream):\n \"\"\"Ignore whitespace outside of strings. If we hit a string, read it in\n its entirety.\n \"\"\"\n chunk = stream.read(1)\n while chunk in SKIP:\n chunk = stream.read(1)\n if chunk == \"\\\"\":\n chunk += stream.read(1)\n while not chunk.endswith(...
## copyright 2014 cognitect. all rights reserved. ## ## licensed under the apache license, version 2.0 (the "license"); ## you may not use this file except in compliance with the license. ## you may obtain a copy of the license at ## ## http://www.apache.org/licenses/license-2.0 ## ## unless required by applicable...
cognitect/transit-python
transit/writer.py
Marshaler.are_stringable_keys
python
def are_stringable_keys(self, m): for x in m.keys(): if len(self.handlers[x].tag(x)) != 1: return False return True
Test whether the keys within a map are stringable - a simple map, that can be optimized and whose keys can be cached
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L112-L119
null
class Marshaler(object): """The base Marshaler from which all Marshalers inherit. The Marshaler specifies how to emit Transit data given encodeable Python objects. The end of this process is specialized by other Marshalers to covert the final result into an on-the-wire payload (JSON or MsgPack). "...
cognitect/transit-python
transit/writer.py
Marshaler.marshal
python
def marshal(self, obj, as_map_key, cache): handler = self.handlers[obj] tag = handler.tag(obj) f = marshal_dispatch.get(tag) if f: f(self, obj, handler.string_rep(obj) if as_map_key else handler.rep(obj), as_map_key, cache) else: self.emit_encoded(tag, ha...
Marshal an individual obj, potentially as part of another container object (like a list/dictionary/etc). Specify if this object is a key to a map/dict, and pass in the current cache being used. This method should only be called by a top-level marshalling call and should not be considere...
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L193-L207
[ "def emit_encoded(self, tag, handler, obj, as_map_key, cache):\n rep = handler.rep(obj)\n if len(tag) == 1:\n if isinstance(rep, pyversion.string_types):\n self.emit_string(ESC, tag, rep, as_map_key, cache)\n elif as_map_key or self.opts[\"prefer_strings\"]:\n rep = handler...
class Marshaler(object): """The base Marshaler from which all Marshalers inherit. The Marshaler specifies how to emit Transit data given encodeable Python objects. The end of this process is specialized by other Marshalers to covert the final result into an on-the-wire payload (JSON or MsgPack). "...
cognitect/transit-python
transit/writer.py
Marshaler.marshal_top
python
def marshal_top(self, obj, cache=None): if not cache: cache = RollingCache() handler = self.handlers[obj] tag = handler.tag(obj) if tag: if len(tag) == 1: self.marshal(TaggedValue(QUOTE, obj), False, cache) else: self....
Given a complete object that needs to be marshaled into Transit data, and optionally a cache, dispatch accordingly, and flush the data directly into the IO stream.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L209-L227
[ "def marshal(self, obj, as_map_key, cache):\n \"\"\"Marshal an individual obj, potentially as part of another container\n object (like a list/dictionary/etc). Specify if this object is a key\n to a map/dict, and pass in the current cache being used.\n This method should only be called by a top-level ma...
class Marshaler(object): """The base Marshaler from which all Marshalers inherit. The Marshaler specifies how to emit Transit data given encodeable Python objects. The end of this process is specialized by other Marshalers to covert the final result into an on-the-wire payload (JSON or MsgPack). "...
cognitect/transit-python
transit/writer.py
Marshaler.dispatch_map
python
def dispatch_map(self, rep, as_map_key, cache): if self.are_stringable_keys(rep): return self.emit_map(rep, as_map_key, cache) return self.emit_cmap(rep, as_map_key, cache)
Used to determine and dipatch the writing of a map - a simple map with strings as keys, or a complex map, whose keys are also compound types.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L229-L236
[ "def are_stringable_keys(self, m):\n \"\"\"Test whether the keys within a map are stringable - a simple map,\n that can be optimized and whose keys can be cached\n \"\"\"\n for x in m.keys():\n if len(self.handlers[x].tag(x)) != 1:\n return False\n return True\n" ]
class Marshaler(object): """The base Marshaler from which all Marshalers inherit. The Marshaler specifies how to emit Transit data given encodeable Python objects. The end of this process is specialized by other Marshalers to covert the final result into an on-the-wire payload (JSON or MsgPack). "...
cognitect/transit-python
transit/writer.py
JsonMarshaler.emit_map
python
def emit_map(self, m, _, cache): self.emit_array_start(None) self.marshal(MAP_AS_ARR, False, cache) for k, v in m.items(): self.marshal(k, True, cache) self.marshal(v, False, cache) self.emit_array_end()
Emits array as per default JSON spec.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/writer.py#L353-L360
[ "def marshal(self, obj, as_map_key, cache):\n \"\"\"Marshal an individual obj, potentially as part of another container\n object (like a list/dictionary/etc). Specify if this object is a key\n to a map/dict, and pass in the current cache being used.\n This method should only be called by a top-level ma...
class JsonMarshaler(Marshaler): """The Marshaler tailor to JSON. To use this Marshaler, specify the 'json' protocol when creating a Writer. """ JSON_MAX_INT = pow(2, 53) - 1 JSON_MIN_INT = -pow(2, 53) + 1 default_opts = {"prefer_strings": True, "max_int": JSON_MAX_INT, ...
cognitect/transit-python
transit/decoder.py
Decoder.decode
python
def decode(self, node, cache=None, as_map_key=False): if not cache: cache = RollingCache() return self._decode(node, cache, as_map_key)
Given a node of data (any supported decodeable obj - string, dict, list), return the decoded object. Optionally set the current decode cache [None]. If None, a new RollingCache is instantiated and used. You may also hit to the decoder that this node is to be treated as a map key [False...
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L73-L82
[ "def _decode(self, node, cache, as_map_key):\n tp = type(node)\n if tp is pyversion.unicode_type:\n return self.decode_string(node, cache, as_map_key)\n elif tp is bytes:\n return self.decode_string(node.decode(\"utf-8\"), cache, as_map_key)\n elif tp is dict or tp is OrderedDict:\n ...
class Decoder(object): """The Decoder is the lowest level entry point for parsing, decoding, and fully converting Transit data into Python objects. During the creation of a Decoder object, you can specify custom options in a dictionary. One such option is 'decoders'. Note that while you can speci...
cognitect/transit-python
transit/decoder.py
Decoder.decode_list
python
def decode_list(self, node, cache, as_map_key): if node: if node[0] == MAP_AS_ARR: # key must be decoded before value for caching to work. returned_dict = {} for k, v in pairs(node[1:]): key = self._decode(k, cache, True) ...
Special case decodes map-as-array. Otherwise lists are treated as Python lists. Arguments follow the same convention as the top-level 'decode' function.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L100-L121
[ "def pairs(i):\n return izip(*[iter(i)] * 2)\n", "def _decode(self, node, cache, as_map_key):\n tp = type(node)\n if tp is pyversion.unicode_type:\n return self.decode_string(node, cache, as_map_key)\n elif tp is bytes:\n return self.decode_string(node.decode(\"utf-8\"), cache, as_map_ke...
class Decoder(object): """The Decoder is the lowest level entry point for parsing, decoding, and fully converting Transit data into Python objects. During the creation of a Decoder object, you can specify custom options in a dictionary. One such option is 'decoders'. Note that while you can speci...
cognitect/transit-python
transit/decoder.py
Decoder.decode_string
python
def decode_string(self, string, cache, as_map_key): if is_cache_key(string): return self.parse_string(cache.decode(string, as_map_key), cache, as_map_key) if is_cacheable(string, as_map_key): cache.encode(string, as_map_key) return sel...
Decode a string - arguments follow the same convention as the top-level 'decode' function.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L123-L132
[ "def is_cache_key(name):\n return len(name) and (name[0] == SUB and name != MAP_AS_ARR)\n" ]
class Decoder(object): """The Decoder is the lowest level entry point for parsing, decoding, and fully converting Transit data into Python objects. During the creation of a Decoder object, you can specify custom options in a dictionary. One such option is 'decoders'. Note that while you can speci...
cognitect/transit-python
transit/decoder.py
Decoder.register
python
def register(self, key_or_tag, obj): if key_or_tag == "default_decoder": self.options["default_decoder"] = obj else: self.decoders[key_or_tag] = obj
Register a custom Transit tag and new parsing function with the decoder. Also, you can optionally set the 'default_decoder' with this function. Your new tag and parse/decode function will be added to the interal dictionary of decoders for this Decoder object.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/decoder.py#L177-L186
null
class Decoder(object): """The Decoder is the lowest level entry point for parsing, decoding, and fully converting Transit data into Python objects. During the creation of a Decoder object, you can specify custom options in a dictionary. One such option is 'decoders'. Note that while you can speci...
cognitect/transit-python
transit/read_handlers.py
UuidHandler.from_rep
python
def from_rep(u): if isinstance(u, pyversion.string_types): return uuid.UUID(u) # hack to remove signs a = ctypes.c_ulong(u[0]) b = ctypes.c_ulong(u[1]) combined = a.value << 64 | b.value return uuid.UUID(int=combined)
Given a string, return a UUID object.
train
https://github.com/cognitect/transit-python/blob/59e27e7d322feaa3a7e8eb3de06ae96d8adb614f/transit/read_handlers.py#L78-L87
null
class UuidHandler(object): @staticmethod
bwesterb/py-seccure
src/__init__.py
serialize_number
python
def serialize_number(x, fmt=SER_BINARY, outlen=None): ret = b'' if fmt == SER_BINARY: while x: x, r = divmod(x, 256) ret = six.int2byte(int(r)) + ret if outlen is not None: assert len(ret) <= outlen ret = ret.rjust(outlen, b'\0') return ret...
Serializes `x' to a string of length `outlen' in format `fmt'
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L57-L75
null
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
deserialize_number
python
def deserialize_number(s, fmt=SER_BINARY): ret = gmpy.mpz(0) if fmt == SER_BINARY: if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") for c in s: ...
Deserializes a number from a string `s' in format `fmt'
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L78-L96
[ "def byte2int(b): return b\n" ]
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
mod_issquare
python
def mod_issquare(a, p): if not a: return True p1 = p // 2 p2 = pow(a, p1, p) return p2 == 1
Returns whether `a' is a square modulo p
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L113-L119
null
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
mod_root
python
def mod_root(a, p): if a == 0: return 0 if not mod_issquare(a, p): raise ValueError n = 2 while mod_issquare(n, p): n += 1 q = p - 1 r = 0 while not q.getbit(r): r += 1 q = q >> r y = pow(n, q, p) h = q >> 1 b = pow(a, h, p) x = (a * b) % p...
Return a root of `a' modulo p
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L122-L154
[ "def mod_issquare(a, p):\n \"\"\" Returns whether `a' is a square modulo p \"\"\"\n if not a:\n return True\n p1 = p // 2\n p2 = pow(a, p1, p)\n return p2 == 1\n" ]
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
encrypt
python
def encrypt(s, pk, pk_format=SER_COMPACT, mac_bytes=10, curve=None): curve = (Curve.by_pk_len(len(pk)) if curve is None else Curve.by_name(curve)) p = curve.pubkey_from_string(pk, pk_format) return p.encrypt(s, mac_bytes)
Encrypts `s' for public key `pk'
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L903-L908
[ "def encrypt(self, s, mac_bytes=10):\n \"\"\" Encrypt `s' for this pubkey. \"\"\"\n if isinstance(s, six.text_type):\n raise ValueError(\n \"Encode `s` to a bytestring yourself to\" +\n \" prevent problems with different default encodings\")\n out = BytesIO()\n with self.enc...
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
decrypt
python
def decrypt(s, passphrase, curve='secp160r1', mac_bytes=10): curve = Curve.by_name(curve) privkey = curve.passphrase_to_privkey(passphrase) return privkey.decrypt(s, mac_bytes)
Decrypts `s' with passphrase `passphrase'
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L911-L915
[ "def decrypt(self, s, mac_bytes=10):\n if isinstance(s, six.text_type):\n raise ValueError(\"s should be bytes\")\n instream = BytesIO(s)\n with self.decrypt_from(instream, mac_bytes) as f:\n return f.read()\n", "def by_name(name):\n for raw_curve in RAW_CURVES:\n if raw_curve[0] ...
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
encrypt_file
python
def encrypt_file(in_path_or_file, out_path_or_file, pk, pk_format=SER_COMPACT, mac_bytes=10, chunk_size=4096, curve=None): close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path...
Encrypts `in_file' to `out_file' for pubkey `pk'
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L918-L936
[ "def stringlike(x): return isinstance(x, (str, bytes))\n" ]
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
decrypt_file
python
def decrypt_file(in_path_or_file, out_path_or_file, passphrase, curve='secp160r1', mac_bytes=10, chunk_size=4096): close_in, close_out = False, False in_file, out_file = in_path_or_file, out_path_or_file try: if stringlike(in_path_or_file): in_file = open(in_path_or_file...
Decrypts `in_file' to `out_file' with passphrase `passphrase'
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L939-L957
[ "def stringlike(x): return isinstance(x, (str, bytes))\n" ]
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
verify
python
def verify(s, sig, pk, sig_format=SER_COMPACT, pk_format=SER_COMPACT, curve=None): if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = (Curve.by_pk_len(len(pk)) if c...
Verifies that `sig' is a signature of pubkey `pk' for the message `s'.
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L985-L995
[ "def verify(self, h, sig, sig_fmt=SER_BINARY):\n \"\"\" Verifies that `sig' is a signature for a message with\n SHA-512 hash `h'. \"\"\"\n s = deserialize_number(sig, sig_fmt)\n return self.p._ECDSA_verify(h, s)\n", "def by_name(name):\n for raw_curve in RAW_CURVES:\n if raw_curve[0] == ...
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
sign
python
def sign(s, passphrase, sig_format=SER_COMPACT, curve='secp160r1'): if isinstance(s, six.text_type): raise ValueError("Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") curve = Curve.by_name(curve) privkey = curve.passphrase_to_p...
Signs `s' with passphrase `passphrase'
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L998-L1005
[ "def sign(self, h, sig_format=SER_BINARY):\n \"\"\" Signs the message with SHA-512 hash `h' with this private key. \"\"\"\n outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT\n else self.curve.sig_len_bin)\n sig = self._ECDSA_sign(h)\n return serialize_number(sig, sig_format,...
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
generate_keypair
python
def generate_keypair(curve='secp160r1', randfunc=None): if randfunc is None: randfunc = Crypto.Random.new().read curve = Curve.by_name(curve) raw_privkey = randfunc(curve.order_len_bin) privkey = serialize_number(deserialize_number(raw_privkey), SER_COMPACT) pubkey = str(passphrase_to_pubkey...
Convenience function to generate a random new keypair (passphrase, pubkey).
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L1013-L1022
[ "def serialize_number(x, fmt=SER_BINARY, outlen=None):\n \"\"\" Serializes `x' to a string of length `outlen' in format `fmt' \"\"\"\n ret = b''\n if fmt == SER_BINARY:\n while x:\n x, r = divmod(x, 256)\n ret = six.int2byte(int(r)) + ret\n if outlen is not None:\n ...
""" Elliptic Curve cryptography compatible with SECCURE: http://point-at-infinity.org/seccure/ """ import hmac import hashlib import logging import binascii import contextlib import collections from ._version import __version__ # noqa: F401 # PyCrypto import Crypto.Util import Crypto.Cipher.AES import Crypt...
bwesterb/py-seccure
src/__init__.py
PubKey.verify
python
def verify(self, h, sig, sig_fmt=SER_BINARY): s = deserialize_number(sig, sig_fmt) return self.p._ECDSA_verify(h, s)
Verifies that `sig' is a signature for a message with SHA-512 hash `h'.
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L597-L601
[ "def deserialize_number(s, fmt=SER_BINARY):\n \"\"\" Deserializes a number from a string `s' in format `fmt' \"\"\"\n ret = gmpy.mpz(0)\n if fmt == SER_BINARY:\n if isinstance(s, six.text_type):\n raise ValueError(\n \"Encode `s` to a bytestring yourself to\" +\n ...
class PubKey(object): """ A public affine point """ def __init__(self, p): self.p = p @contextlib.contextmanager def encrypt_to(self, f, mac_bytes=10): """ Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'. """ ...
bwesterb/py-seccure
src/__init__.py
PubKey.encrypt_to
python
def encrypt_to(self, f, mac_bytes=10): ctx = EncryptionContext(f, self.p, mac_bytes) yield ctx ctx.finish()
Returns a file like object `ef'. Anything written to `ef' will be encrypted for this pubkey and written to `f'.
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L604-L609
[ "def finish(self):\n if not self.f:\n raise IOError(\"closed\")\n self.f.write(self.h.digest()[:self.mac_bytes])\n self.f = None\n" ]
class PubKey(object): """ A public affine point """ def __init__(self, p): self.p = p def verify(self, h, sig, sig_fmt=SER_BINARY): """ Verifies that `sig' is a signature for a message with SHA-512 hash `h'. """ s = deserialize_number(sig, sig_fmt) return self.p...
bwesterb/py-seccure
src/__init__.py
PubKey.encrypt
python
def encrypt(self, s, mac_bytes=10): if isinstance(s, six.text_type): raise ValueError( "Encode `s` to a bytestring yourself to" + " prevent problems with different default encodings") out = BytesIO() with self.encrypt_to(out, mac_bytes) as f: ...
Encrypt `s' for this pubkey.
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L611-L620
null
class PubKey(object): """ A public affine point """ def __init__(self, p): self.p = p def verify(self, h, sig, sig_fmt=SER_BINARY): """ Verifies that `sig' is a signature for a message with SHA-512 hash `h'. """ s = deserialize_number(sig, sig_fmt) return self.p...
bwesterb/py-seccure
src/__init__.py
PrivKey.decrypt_from
python
def decrypt_from(self, f, mac_bytes=10): ctx = DecryptionContext(self.curve, f, self, mac_bytes) yield ctx ctx.read()
Decrypts a message from f.
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L643-L647
[ "def read(self, n=None):\n if not self.f:\n return ''\n if n is None:\n tmp = self.ahead + self.f.read()\n else:\n tmp = self.ahead + self.f.read(n)\n ct = tmp[:-self.mac_bytes]\n self.ahead = tmp[-self.mac_bytes:]\n self.h.update(ct)\n pt = self.cipher.decrypt(ct)\n if ...
class PrivKey(object): """ A secret exponent """ def __init__(self, e, curve): self.e = e self.curve = curve @contextlib.contextmanager def decrypt(self, s, mac_bytes=10): if isinstance(s, six.text_type): raise ValueError("s should be bytes") instream = By...
bwesterb/py-seccure
src/__init__.py
PrivKey.sign
python
def sign(self, h, sig_format=SER_BINARY): outlen = (self.curve.sig_len_compact if sig_format == SER_COMPACT else self.curve.sig_len_bin) sig = self._ECDSA_sign(h) return serialize_number(sig, sig_format, outlen)
Signs the message with SHA-512 hash `h' with this private key.
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L656-L661
[ "def serialize_number(x, fmt=SER_BINARY, outlen=None):\n \"\"\" Serializes `x' to a string of length `outlen' in format `fmt' \"\"\"\n ret = b''\n if fmt == SER_BINARY:\n while x:\n x, r = divmod(x, 256)\n ret = six.int2byte(int(r)) + ret\n if outlen is not None:\n ...
class PrivKey(object): """ A secret exponent """ def __init__(self, e, curve): self.e = e self.curve = curve @contextlib.contextmanager def decrypt_from(self, f, mac_bytes=10): """ Decrypts a message from f. """ ctx = DecryptionContext(self.curve, f, self, mac_bytes) ...
bwesterb/py-seccure
src/__init__.py
Curve.hash_to_exponent
python
def hash_to_exponent(self, h): ctr = Crypto.Util.Counter.new(128, initial_value=0) cipher = Crypto.Cipher.AES.new(h, Crypto.Cipher.AES.MODE_CTR, counter=ctr) buf = cipher.encrypt(b'\0' * self.order_len_bin) return self._buf_to_exponent(buf)
Converts a 32 byte hash to an exponent
train
https://github.com/bwesterb/py-seccure/blob/944760744686dd0ad015bd90ecb13a3ce0d7c9c9/src/__init__.py#L859-L865
[ "def _buf_to_exponent(self, buf):\n a = deserialize_number(buf, SER_BINARY)\n a = (a % (self.order - 1)) + 1\n return a\n" ]
class Curve(object): """ Represents a Elliptic Curve """ @staticmethod def by_name_substring(substring): substring = substring.lower() candidates = [] for raw_curve in RAW_CURVES: if substring in raw_curve[0]: candidates.append(raw_curve) if len(c...
bitprophet/releases
releases/line_manager.py
LineManager.add_family
python
def add_family(self, major_number): # Normally, we have separate buckets for bugfixes vs features keys = ['unreleased_bugfix', 'unreleased_feature'] # But unstable prehistorical releases roll all up into just # 'unreleased' if major_number == 0 and self.config.releases_unstable_p...
Expand to a new release line with given ``major_number``. This will flesh out mandatory buckets like ``unreleased_bugfix`` and do other necessary bookkeeping.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/line_manager.py#L23-L37
null
class LineManager(dict): """ Manages multiple release lines/families as well as related config state. """ def __init__(self, app): """ Initialize new line manager dict. :param app: The core Sphinx app object. Mostly used for config. """ super(LineManager, self)._...
bitprophet/releases
releases/line_manager.py
LineManager.has_stable_releases
python
def has_stable_releases(self): nonzeroes = self.stable_families # Nothing but 0.x releases -> yup we're prehistory if not nonzeroes: return False # Presumably, if there's >1 major family besides 0.x, we're at least # one release into the 1.0 (or w/e) line. if ...
Returns whether stable (post-0.x) releases seem to exist.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/line_manager.py#L59-L75
null
class LineManager(dict): """ Manages multiple release lines/families as well as related config state. """ def __init__(self, app): """ Initialize new line manager dict. :param app: The core Sphinx app object. Mostly used for config. """ super(LineManager, self)._...
bitprophet/releases
releases/util.py
parse_changelog
python
def parse_changelog(path, **kwargs): app, doctree = get_doctree(path, **kwargs) # Have to semi-reproduce the 'find first bullet list' bit from main code, # which is unfortunately side-effect-heavy (thanks to Sphinx plugin # design). first_list = None for node in doctree[0]: if isinstance...
Load and parse changelog file from ``path``, returning data structures. This function does not alter any files on disk; it is solely for introspecting a Releases ``changelog.rst`` and programmatically answering questions like "are there any unreleased bugfixes for the 2.3 line?" or "what was included i...
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/util.py#L37-L106
[ "def construct_releases(entries, app):\n log = partial(_log, config=app.config)\n # Walk from back to front, consuming entries & copying them into\n # per-release buckets as releases are encountered. Store releases in order.\n releases = []\n # Release lines, to be organized by major releases, then b...
""" Utility functions, such as helpers for standalone changelog parsing. """ import logging import os from tempfile import mkdtemp import sphinx from docutils.core import Publisher from docutils.io import NullOutput from docutils.nodes import bullet_list from sphinx.application import Sphinx # not exposed at top leve...
bitprophet/releases
releases/util.py
get_doctree
python
def get_doctree(path, **kwargs): root, filename = os.path.split(path) docname, _ = os.path.splitext(filename) # TODO: this only works for top level changelog files (i.e. ones where # their dirname is the project/doc root) app = make_app(srcdir=root, **kwargs) # Create & init a BuildEnvironment. ...
Obtain a Sphinx doctree from the RST file at ``path``. Performs no Releases-specific processing; this code would, ideally, be in Sphinx itself, but things there are pretty tightly coupled. So we wrote this. Any additional kwargs are passed unmodified into an internal `make_app` call. :param s...
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/util.py#L109-L194
[ "def make_app(**kwargs):\n \"\"\"\n Create a dummy Sphinx app, filling in various hardcoded assumptions.\n\n For example, Sphinx assumes the existence of various source/dest\n directories, even if you're only calling internals that never generate (or\n sometimes, even read!) on-disk files. This funct...
""" Utility functions, such as helpers for standalone changelog parsing. """ import logging import os from tempfile import mkdtemp import sphinx from docutils.core import Publisher from docutils.io import NullOutput from docutils.nodes import bullet_list from sphinx.application import Sphinx # not exposed at top leve...
bitprophet/releases
releases/util.py
load_conf
python
def load_conf(srcdir): path = os.path.join(srcdir, 'conf.py') mylocals = {'__file__': path} with open(path) as fd: exec(fd.read(), mylocals) return mylocals
Load ``conf.py`` from given ``srcdir``. :returns: Dictionary derived from the conf module.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/util.py#L197-L207
null
""" Utility functions, such as helpers for standalone changelog parsing. """ import logging import os from tempfile import mkdtemp import sphinx from docutils.core import Publisher from docutils.io import NullOutput from docutils.nodes import bullet_list from sphinx.application import Sphinx # not exposed at top leve...
bitprophet/releases
releases/util.py
make_app
python
def make_app(**kwargs): srcdir = kwargs.pop('srcdir', mkdtemp()) dstdir = kwargs.pop('dstdir', mkdtemp()) doctreedir = kwargs.pop('doctreedir', mkdtemp()) load_extensions = kwargs.pop('load_extensions', False) real_conf = None try: # Sphinx <1.6ish Sphinx._log = lambda self, mess...
Create a dummy Sphinx app, filling in various hardcoded assumptions. For example, Sphinx assumes the existence of various source/dest directories, even if you're only calling internals that never generate (or sometimes, even read!) on-disk files. This function creates safe temp directories for these in...
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/util.py#L210-L318
[ "def setup(app):\n for key, default in (\n # Issue base URI setting: releases_issue_uri\n # E.g. 'https://github.com/fabric/fabric/issues/'\n ('issue_uri', None),\n # Release-tag base URI setting: releases_release_uri\n # E.g. 'https://github.com/fabric/fabric/tree/'\n (...
""" Utility functions, such as helpers for standalone changelog parsing. """ import logging import os from tempfile import mkdtemp import sphinx from docutils.core import Publisher from docutils.io import NullOutput from docutils.nodes import bullet_list from sphinx.application import Sphinx # not exposed at top leve...
bitprophet/releases
releases/__init__.py
_log
python
def _log(txt, config): if config.releases_debug: sys.stderr.write(str(txt) + "\n") sys.stderr.flush()
Log debug output if debug setting is on. Intended to be partial'd w/ config at top of functions. Meh.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L15-L23
null
import itertools import re import sys from functools import partial from docutils import nodes, utils from docutils.parsers.rst import roles import six from .models import Issue, ISSUE_TYPES, Release, Version, Spec from .line_manager import LineManager from ._version import __version__ def issue_nodelist(name, ide...
bitprophet/releases
releases/__init__.py
scan_for_spec
python
def scan_for_spec(keyword): # Both 'spec' formats are wrapped in parens, discard keyword = keyword.lstrip('(').rstrip(')') # First, test for intermediate '1.2+' style matches = release_line_re.findall(keyword) if matches: return Spec(">={}".format(matches[0])) # Failing that, see if Spec...
Attempt to return some sort of Spec from given keyword value. Returns None if one could not be derived.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L38-L55
null
import itertools import re import sys from functools import partial from docutils import nodes, utils from docutils.parsers.rst import roles import six from .models import Issue, ISSUE_TYPES, Release, Version, Spec from .line_manager import LineManager from ._version import __version__ def _log(txt, config): ""...
bitprophet/releases
releases/__init__.py
issues_role
python
def issues_role(name, rawtext, text, lineno, inliner, options={}, content=[]): parts = utils.unescape(text).split() issue_no = parts.pop(0) # Lol @ access back to Sphinx config = inliner.document.settings.env.app.config if issue_no not in ('-', '0'): ref = None if config.releases_iss...
Use: :issue|bug|feature|support:`ticket_number` When invoked as :issue:, turns into just a "#NN" hyperlink to `releases_issue_uri`. When invoked otherwise, turns into "[Type] <#NN hyperlink>: ". Spaces present in the "ticket number" are used as fields for keywords (major, backported) and/or specs...
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L58-L128
[ "def issue_nodelist(name, identifier=None):\n which = '[<span style=\"color: #%s;\">%s</span>]' % (\n ISSUE_TYPES[name], name.capitalize()\n )\n signifier = [nodes.raw(text=which, format='html')]\n id_nodelist = [nodes.inline(text=\" \"), identifier] if identifier else []\n trail = [] if ident...
import itertools import re import sys from functools import partial from docutils import nodes, utils from docutils.parsers.rst import roles import six from .models import Issue, ISSUE_TYPES, Release, Version, Spec from .line_manager import LineManager from ._version import __version__ def _log(txt, config): ""...
bitprophet/releases
releases/__init__.py
release_role
python
def release_role(name, rawtext, text, lineno, inliner, options={}, content=[]): # Make sure year has been specified match = year_arg_re.match(text) if not match: msg = inliner.reporter.error("Must specify release date!") return [inliner.problematic(rawtext, rawtext, msg)], [msg] number, ...
Invoked as :release:`N.N.N <YYYY-MM-DD>`. Turns into useful release header + link to GH tree for the tag.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L164-L181
[ "def release_nodes(text, slug, date, config):\n # Doesn't seem possible to do this \"cleanly\" (i.e. just say \"make me a\n # title and give it these HTML attributes during render time) so...fuckit.\n # We were already doing fully raw elements elsewhere anyway. And who cares\n # about a PDF of a changel...
import itertools import re import sys from functools import partial from docutils import nodes, utils from docutils.parsers.rst import roles import six from .models import Issue, ISSUE_TYPES, Release, Version, Spec from .line_manager import LineManager from ._version import __version__ def _log(txt, config): ""...
bitprophet/releases
releases/__init__.py
append_unreleased_entries
python
def append_unreleased_entries(app, manager, releases): for family, lines in six.iteritems(manager): for type_ in ('bugfix', 'feature'): bucket = 'unreleased_{}'.format(type_) if bucket not in lines: # Implies unstable prehistory + 0.x fam continue issues =...
Generate new abstract 'releases' for unreleased issues. There's one for each combination of bug-vs-feature & major release line. When only one major release line exists, that dimension is ignored.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L202-L221
[ "def generate_unreleased_entry(header, line, issues, manager, app):\n log = partial(_log, config=app.config)\n nodelist = [release_nodes(\n header,\n # TODO: should link to master for newest family and...what\n # exactly, for the others? Expectation isn't necessarily to\n # have a ...
import itertools import re import sys from functools import partial from docutils import nodes, utils from docutils.parsers.rst import roles import six from .models import Issue, ISSUE_TYPES, Release, Version, Spec from .line_manager import LineManager from ._version import __version__ def _log(txt, config): ""...
bitprophet/releases
releases/__init__.py
reorder_release_entries
python
def reorder_release_entries(releases): order = {'feature': 0, 'bug': 1, 'support': 2} for release in releases: entries = release['entries'][:] release['entries'] = sorted(entries, key=lambda x: order[x.type])
Mutate ``releases`` so the entrylist in each is ordered by feature/bug/etc.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L224-L231
null
import itertools import re import sys from functools import partial from docutils import nodes, utils from docutils.parsers.rst import roles import six from .models import Issue, ISSUE_TYPES, Release, Version, Spec from .line_manager import LineManager from ._version import __version__ def _log(txt, config): ""...
bitprophet/releases
releases/__init__.py
construct_entry_with_release
python
def construct_entry_with_release(focus, issues, manager, log, releases, rest): log("release for line %r" % focus.minor) # Check for explicitly listed issues first explicit = None if rest[0].children: explicit = [x.strip() for x in rest[0][0].split(',')] # Do those by themselves since they ov...
Releases 'eat' the entries in their line's list and get added to the final data structure. They also inform new release-line 'buffers'. Release lines, once the release obj is removed, should be empty or a comma-separated list of issue numbers.
train
https://github.com/bitprophet/releases/blob/97a763e41bbe7374106a1c648b89346a0d935429/releases/__init__.py#L234-L352
null
import itertools import re import sys from functools import partial from docutils import nodes, utils from docutils.parsers.rst import roles import six from .models import Issue, ISSUE_TYPES, Release, Version, Spec from .line_manager import LineManager from ._version import __version__ def _log(txt, config): ""...