partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
valid
raw_opener
Wait a little and then open a web browser page for the control panel.
bibliopixel/animation/remote/opener.py
def raw_opener(ip_address, port, delay=1): """ Wait a little and then open a web browser page for the control panel. """ def target(): time.sleep(delay) url = 'http://%s:%d' % (ip_address, port) webbrowser.open(url, new=0, autoraise=True) threading.Thread(target=target, daemon=True).start()
def raw_opener(ip_address, port, delay=1): """ Wait a little and then open a web browser page for the control panel. """ def target(): time.sleep(delay) url = 'http://%s:%d' % (ip_address, port) webbrowser.open(url, new=0, autoraise=True) threading.Thread(target=target, daemon=True).start()
[ "Wait", "a", "little", "and", "then", "open", "a", "web", "browser", "page", "for", "the", "control", "panel", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/remote/opener.py#L18-L27
[ "def", "raw_opener", "(", "ip_address", ",", "port", ",", "delay", "=", "1", ")", ":", "def", "target", "(", ")", ":", "time", ".", "sleep", "(", "delay", ")", "url", "=", "'http://%s:%d'", "%", "(", "ip_address", ",", "port", ")", "webbrowser", ".", "open", "(", "url", ",", "new", "=", "0", ",", "autoraise", "=", "True", ")", "threading", ".", "Thread", "(", "target", "=", "target", ",", "daemon", "=", "True", ")", ".", "start", "(", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Runner.start
Creates and starts the project.
bibliopixel/builder/runner.py
def start(self, threaded): """Creates and starts the project.""" self.stop() self.__class__._INSTANCE = weakref.ref(self) self.is_running = True if threaded: self.thread = runnable.LoopThread() self.thread.run_once = self._target self.thread.start() else: self._target()
def start(self, threaded): """Creates and starts the project.""" self.stop() self.__class__._INSTANCE = weakref.ref(self) self.is_running = True if threaded: self.thread = runnable.LoopThread() self.thread.run_once = self._target self.thread.start() else: self._target()
[ "Creates", "and", "starts", "the", "project", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/runner.py#L15-L26
[ "def", "start", "(", "self", ",", "threaded", ")", ":", "self", ".", "stop", "(", ")", "self", ".", "__class__", ".", "_INSTANCE", "=", "weakref", ".", "ref", "(", "self", ")", "self", ".", "is_running", "=", "True", "if", "threaded", ":", "self", ".", "thread", "=", "runnable", ".", "LoopThread", "(", ")", "self", ".", "thread", ".", "run_once", "=", "self", ".", "_target", "self", ".", "thread", ".", "start", "(", ")", "else", ":", "self", ".", "_target", "(", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Runner.stop
Stop the Runner if it's running. Called as a classmethod, stop the running instance if any.
bibliopixel/builder/runner.py
def stop(self): """ Stop the Runner if it's running. Called as a classmethod, stop the running instance if any. """ if self.is_running: log.info('Stopping') self.is_running = False self.__class__._INSTANCE = None try: self.thread and self.thread.stop() except: log.error('Error stopping thread') traceback.print_exc() self.thread = None return True
def stop(self): """ Stop the Runner if it's running. Called as a classmethod, stop the running instance if any. """ if self.is_running: log.info('Stopping') self.is_running = False self.__class__._INSTANCE = None try: self.thread and self.thread.stop() except: log.error('Error stopping thread') traceback.print_exc() self.thread = None return True
[ "Stop", "the", "Runner", "if", "it", "s", "running", ".", "Called", "as", "a", "classmethod", "stop", "the", "running", "instance", "if", "any", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/builder/runner.py#L28-L44
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "is_running", ":", "log", ".", "info", "(", "'Stopping'", ")", "self", ".", "is_running", "=", "False", "self", ".", "__class__", ".", "_INSTANCE", "=", "None", "try", ":", "self", ".", "thread", "and", "self", ".", "thread", ".", "stop", "(", ")", "except", ":", "log", ".", "error", "(", "'Error stopping thread'", ")", "traceback", ".", "print_exc", "(", ")", "self", ".", "thread", "=", "None", "return", "True" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
show_image
Display an image on a matrix.
bibliopixel/util/image/load_image.py
def show_image(setter, width, height, image_path='', image_obj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on a matrix.""" bgcolor = color_scale(bgcolor, brightness) img = image_obj if image_path and not img: from PIL import Image img = Image.open(image_path) elif not img: raise ValueError('Must provide either image_path or image_obj') w = min(width - offset[0], img.size[0]) h = min(height - offset[1], img.size[1]) ox = offset[0] oy = offset[1] for x in range(ox, w + ox): for y in range(oy, h + oy): r, g, b, a = (0, 0, 0, 255) rgba = img.getpixel((x - ox, y - oy)) if isinstance(rgba, int): raise ValueError('Image must be in RGB or RGBA format!') if len(rgba) == 3: r, g, b = rgba elif len(rgba) == 4: r, g, b, a = rgba else: raise ValueError('Image must be in RGB or RGBA format!') if a == 0: r, g, b = bgcolor else: r, g, b = color_scale((r, g, b), a) if brightness != 255: r, g, b = color_scale((r, g, b), brightness) setter(x, y, (r, g, b))
def show_image(setter, width, height, image_path='', image_obj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on a matrix.""" bgcolor = color_scale(bgcolor, brightness) img = image_obj if image_path and not img: from PIL import Image img = Image.open(image_path) elif not img: raise ValueError('Must provide either image_path or image_obj') w = min(width - offset[0], img.size[0]) h = min(height - offset[1], img.size[1]) ox = offset[0] oy = offset[1] for x in range(ox, w + ox): for y in range(oy, h + oy): r, g, b, a = (0, 0, 0, 255) rgba = img.getpixel((x - ox, y - oy)) if isinstance(rgba, int): raise ValueError('Image must be in RGB or RGBA format!') if len(rgba) == 3: r, g, b = rgba elif len(rgba) == 4: r, g, b, a = rgba else: raise ValueError('Image must be in RGB or RGBA format!') if a == 0: r, g, b = bgcolor else: r, g, b = color_scale((r, g, b), a) if brightness != 255: r, g, b = color_scale((r, g, b), brightness) setter(x, y, (r, g, b))
[ "Display", "an", "image", "on", "a", "matrix", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/load_image.py#L6-L47
[ "def", "show_image", "(", "setter", ",", "width", ",", "height", ",", "image_path", "=", "''", ",", "image_obj", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "bgcolor", "=", "COLORS", ".", "Off", ",", "brightness", "=", "255", ")", ":", "bgcolor", "=", "color_scale", "(", "bgcolor", ",", "brightness", ")", "img", "=", "image_obj", "if", "image_path", "and", "not", "img", ":", "from", "PIL", "import", "Image", "img", "=", "Image", ".", "open", "(", "image_path", ")", "elif", "not", "img", ":", "raise", "ValueError", "(", "'Must provide either image_path or image_obj'", ")", "w", "=", "min", "(", "width", "-", "offset", "[", "0", "]", ",", "img", ".", "size", "[", "0", "]", ")", "h", "=", "min", "(", "height", "-", "offset", "[", "1", "]", ",", "img", ".", "size", "[", "1", "]", ")", "ox", "=", "offset", "[", "0", "]", "oy", "=", "offset", "[", "1", "]", "for", "x", "in", "range", "(", "ox", ",", "w", "+", "ox", ")", ":", "for", "y", "in", "range", "(", "oy", ",", "h", "+", "oy", ")", ":", "r", ",", "g", ",", "b", ",", "a", "=", "(", "0", ",", "0", ",", "0", ",", "255", ")", "rgba", "=", "img", ".", "getpixel", "(", "(", "x", "-", "ox", ",", "y", "-", "oy", ")", ")", "if", "isinstance", "(", "rgba", ",", "int", ")", ":", "raise", "ValueError", "(", "'Image must be in RGB or RGBA format!'", ")", "if", "len", "(", "rgba", ")", "==", "3", ":", "r", ",", "g", ",", "b", "=", "rgba", "elif", "len", "(", "rgba", ")", "==", "4", ":", "r", ",", "g", ",", "b", ",", "a", "=", "rgba", "else", ":", "raise", "ValueError", "(", "'Image must be in RGB or RGBA format!'", ")", "if", "a", "==", "0", ":", "r", ",", "g", ",", "b", "=", "bgcolor", "else", ":", "r", ",", "g", ",", "b", "=", "color_scale", "(", "(", "r", ",", "g", ",", "b", ")", ",", "a", ")", "if", "brightness", "!=", "255", ":", "r", ",", "g", ",", "b", "=", "color_scale", "(", "(", "r", ",", "g", ",", "b", ")", ",", "brightness", ")", "setter", "(", "x", ",", "y", ",", "(", "r", ",", "g", ",", "b", ")", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
showImage
Display an image on the matrix
bibliopixel/util/image/load_image.py
def showImage(layout, imagePath="", imageObj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on the matrix""" if not isinstance(layout, Matrix): raise RuntimeError("Must use Matrix with showImage!") layout.all_off() return show_image(layout.set, layout.width, layout.height, imagePath, imageObj, offset, bgcolor, brightness)
def showImage(layout, imagePath="", imageObj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on the matrix""" if not isinstance(layout, Matrix): raise RuntimeError("Must use Matrix with showImage!") layout.all_off() return show_image(layout.set, layout.width, layout.height, imagePath, imageObj, offset, bgcolor, brightness)
[ "Display", "an", "image", "on", "the", "matrix" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/load_image.py#L50-L59
[ "def", "showImage", "(", "layout", ",", "imagePath", "=", "\"\"", ",", "imageObj", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "bgcolor", "=", "COLORS", ".", "Off", ",", "brightness", "=", "255", ")", ":", "if", "not", "isinstance", "(", "layout", ",", "Matrix", ")", ":", "raise", "RuntimeError", "(", "\"Must use Matrix with showImage!\"", ")", "layout", ".", "all_off", "(", ")", "return", "show_image", "(", "layout", ".", "set", ",", "layout", ".", "width", ",", "layout", ".", "height", ",", "imagePath", ",", "imageObj", ",", "offset", ",", "bgcolor", ",", "brightness", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
loadImage
Display an image on the matrix
bibliopixel/util/image/load_image.py
def loadImage(layout, imagePath="", imageObj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on the matrix""" if not isinstance(layout, Matrix): raise RuntimeError("Must use Matrix with loadImage!") texture = [[COLORS.Off for x in range(layout.width)] for y in range(layout.height)] def setter(x, y, pixel): if y >= 0 and x >= 0: texture[y][x] = pixel show_image(setter, layout.width, layout.height, imagePath, imageObj, offset, bgcolor, brightness) return texture
def loadImage(layout, imagePath="", imageObj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on the matrix""" if not isinstance(layout, Matrix): raise RuntimeError("Must use Matrix with loadImage!") texture = [[COLORS.Off for x in range(layout.width)] for y in range(layout.height)] def setter(x, y, pixel): if y >= 0 and x >= 0: texture[y][x] = pixel show_image(setter, layout.width, layout.height, imagePath, imageObj, offset, bgcolor, brightness) return texture
[ "Display", "an", "image", "on", "the", "matrix" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/image/load_image.py#L62-L79
[ "def", "loadImage", "(", "layout", ",", "imagePath", "=", "\"\"", ",", "imageObj", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "bgcolor", "=", "COLORS", ".", "Off", ",", "brightness", "=", "255", ")", ":", "if", "not", "isinstance", "(", "layout", ",", "Matrix", ")", ":", "raise", "RuntimeError", "(", "\"Must use Matrix with loadImage!\"", ")", "texture", "=", "[", "[", "COLORS", ".", "Off", "for", "x", "in", "range", "(", "layout", ".", "width", ")", "]", "for", "y", "in", "range", "(", "layout", ".", "height", ")", "]", "def", "setter", "(", "x", ",", "y", ",", "pixel", ")", ":", "if", "y", ">=", "0", "and", "x", ">=", "0", ":", "texture", "[", "y", "]", "[", "x", "]", "=", "pixel", "show_image", "(", "setter", ",", "layout", ".", "width", ",", "layout", ".", "height", ",", "imagePath", ",", "imageObj", ",", "offset", ",", "bgcolor", ",", "brightness", ")", "return", "texture" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
serpentine_x
Every other row is indexed in reverse.
bibliopixel/layout/geometry/index_ops.py
def serpentine_x(x, y, matrix): """Every other row is indexed in reverse.""" if y % 2: return matrix.columns - 1 - x, y return x, y
def serpentine_x(x, y, matrix): """Every other row is indexed in reverse.""" if y % 2: return matrix.columns - 1 - x, y return x, y
[ "Every", "other", "row", "is", "indexed", "in", "reverse", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/index_ops.py#L14-L18
[ "def", "serpentine_x", "(", "x", ",", "y", ",", "matrix", ")", ":", "if", "y", "%", "2", ":", "return", "matrix", ".", "columns", "-", "1", "-", "x", ",", "y", "return", "x", ",", "y" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
serpentine_y
Every other column is indexed in reverse.
bibliopixel/layout/geometry/index_ops.py
def serpentine_y(x, y, matrix): """Every other column is indexed in reverse.""" if x % 2: return x, matrix.rows - 1 - y return x, y
def serpentine_y(x, y, matrix): """Every other column is indexed in reverse.""" if x % 2: return x, matrix.rows - 1 - y return x, y
[ "Every", "other", "column", "is", "indexed", "in", "reverse", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/index_ops.py#L21-L25
[ "def", "serpentine_y", "(", "x", ",", "y", ",", "matrix", ")", ":", "if", "x", "%", "2", ":", "return", "x", ",", "matrix", ".", "rows", "-", "1", "-", "y", "return", "x", ",", "y" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
to_triplets
Coerce a list into a list of triplets. If `colors` is a list of lists or strings, return it as is. Otherwise, divide it into tuplets of length three, silently discarding any extra elements beyond a multiple of three.
bibliopixel/colors/make.py
def to_triplets(colors): """ Coerce a list into a list of triplets. If `colors` is a list of lists or strings, return it as is. Otherwise, divide it into tuplets of length three, silently discarding any extra elements beyond a multiple of three. """ try: colors[0][0] return colors except: pass # It's a 1-dimensional list extra = len(colors) % 3 if extra: colors = colors[:-extra] return list(zip(*[iter(colors)] * 3))
def to_triplets(colors): """ Coerce a list into a list of triplets. If `colors` is a list of lists or strings, return it as is. Otherwise, divide it into tuplets of length three, silently discarding any extra elements beyond a multiple of three. """ try: colors[0][0] return colors except: pass # It's a 1-dimensional list extra = len(colors) % 3 if extra: colors = colors[:-extra] return list(zip(*[iter(colors)] * 3))
[ "Coerce", "a", "list", "into", "a", "list", "of", "triplets", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/make.py#L76-L94
[ "def", "to_triplets", "(", "colors", ")", ":", "try", ":", "colors", "[", "0", "]", "[", "0", "]", "return", "colors", "except", ":", "pass", "# It's a 1-dimensional list", "extra", "=", "len", "(", "colors", ")", "%", "3", "if", "extra", ":", "colors", "=", "colors", "[", ":", "-", "extra", "]", "return", "list", "(", "zip", "(", "*", "[", "iter", "(", "colors", ")", "]", "*", "3", ")", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
colors_no_palette
Return a Palette but don't take into account Pallete Names.
bibliopixel/colors/make.py
def colors_no_palette(colors=None, **kwds): """Return a Palette but don't take into account Pallete Names.""" if isinstance(colors, str): colors = _split_colors(colors) else: colors = to_triplets(colors or ()) colors = (color(c) for c in colors or ()) return palette.Palette(colors, **kwds)
def colors_no_palette(colors=None, **kwds): """Return a Palette but don't take into account Pallete Names.""" if isinstance(colors, str): colors = _split_colors(colors) else: colors = to_triplets(colors or ()) colors = (color(c) for c in colors or ()) return palette.Palette(colors, **kwds)
[ "Return", "a", "Palette", "but", "don", "t", "take", "into", "account", "Pallete", "Names", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/colors/make.py#L111-L119
[ "def", "colors_no_palette", "(", "colors", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "isinstance", "(", "colors", ",", "str", ")", ":", "colors", "=", "_split_colors", "(", "colors", ")", "else", ":", "colors", "=", "to_triplets", "(", "colors", "or", "(", ")", ")", "colors", "=", "(", "color", "(", "c", ")", "for", "c", "in", "colors", "or", "(", ")", ")", "return", "palette", ".", "Palette", "(", "colors", ",", "*", "*", "kwds", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
flatten
:param dict master: a multilevel dictionary :return: a flattened dictionary :rtype: dict Flattens a multilevel dictionary into a single-level one so that:: {'foo': {'bar': { 'a': 1, 'b': True, 'c': 'hello', }, }, } would become:: {'foo.bar.a': 1, 'foo.bar.b': True, 'foo.bar.a': 1, } You can mix and match both input (hierarchical) and output (dotted) formats in the input without problems - and if you call flatten more than once, it has no effect.
bibliopixel/util/flatten.py
def flatten(master): """ :param dict master: a multilevel dictionary :return: a flattened dictionary :rtype: dict Flattens a multilevel dictionary into a single-level one so that:: {'foo': {'bar': { 'a': 1, 'b': True, 'c': 'hello', }, }, } would become:: {'foo.bar.a': 1, 'foo.bar.b': True, 'foo.bar.a': 1, } You can mix and match both input (hierarchical) and output (dotted) formats in the input without problems - and if you call flatten more than once, it has no effect. """ result = {} def add(value, *keys): if keys in result: raise ValueError('Duplicate key %s' % keys) result[keys] = value def recurse(value, *keys): if isinstance(value, dict): for k, v in value.items(): recurse(v, k, *keys) else: key = '.'.join(reversed(keys)) if key in result: raise ValueError('Duplicate key %s' % str(keys)) result[key] = value recurse(master) return result
def flatten(master): """ :param dict master: a multilevel dictionary :return: a flattened dictionary :rtype: dict Flattens a multilevel dictionary into a single-level one so that:: {'foo': {'bar': { 'a': 1, 'b': True, 'c': 'hello', }, }, } would become:: {'foo.bar.a': 1, 'foo.bar.b': True, 'foo.bar.a': 1, } You can mix and match both input (hierarchical) and output (dotted) formats in the input without problems - and if you call flatten more than once, it has no effect. """ result = {} def add(value, *keys): if keys in result: raise ValueError('Duplicate key %s' % keys) result[keys] = value def recurse(value, *keys): if isinstance(value, dict): for k, v in value.items(): recurse(v, k, *keys) else: key = '.'.join(reversed(keys)) if key in result: raise ValueError('Duplicate key %s' % str(keys)) result[key] = value recurse(master) return result
[ ":", "param", "dict", "master", ":", "a", "multilevel", "dictionary", ":", "return", ":", "a", "flattened", "dictionary", ":", "rtype", ":", "dict" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/flatten.py#L1-L48
[ "def", "flatten", "(", "master", ")", ":", "result", "=", "{", "}", "def", "add", "(", "value", ",", "*", "keys", ")", ":", "if", "keys", "in", "result", ":", "raise", "ValueError", "(", "'Duplicate key %s'", "%", "keys", ")", "result", "[", "keys", "]", "=", "value", "def", "recurse", "(", "value", ",", "*", "keys", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "for", "k", ",", "v", "in", "value", ".", "items", "(", ")", ":", "recurse", "(", "v", ",", "k", ",", "*", "keys", ")", "else", ":", "key", "=", "'.'", ".", "join", "(", "reversed", "(", "keys", ")", ")", "if", "key", "in", "result", ":", "raise", "ValueError", "(", "'Duplicate key %s'", "%", "str", "(", "keys", ")", ")", "result", "[", "key", "]", "=", "value", "recurse", "(", "master", ")", "return", "result" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
unflatten
:param dict master: a multilevel dictionary :return: a unflattened dictionary :rtype: dict Unflattens a single-level dictionary a multilevel into one so that:: {'foo.bar.a': 1, 'foo.bar.b': True, 'foo.bar.a': 1, } would become:: {'foo': {'bar': { 'a': 1, 'b': True, 'c': 'hello', }, }, }
bibliopixel/util/flatten.py
def unflatten(master): """ :param dict master: a multilevel dictionary :return: a unflattened dictionary :rtype: dict Unflattens a single-level dictionary a multilevel into one so that:: {'foo.bar.a': 1, 'foo.bar.b': True, 'foo.bar.a': 1, } would become:: {'foo': {'bar': { 'a': 1, 'b': True, 'c': 'hello', }, }, } """ result = {} for k, v in master.items(): *first, last = k.split('.') r = result for i in first: r = r.setdefault(i, {}) r[last] = v return result
def unflatten(master): """ :param dict master: a multilevel dictionary :return: a unflattened dictionary :rtype: dict Unflattens a single-level dictionary a multilevel into one so that:: {'foo.bar.a': 1, 'foo.bar.b': True, 'foo.bar.a': 1, } would become:: {'foo': {'bar': { 'a': 1, 'b': True, 'c': 'hello', }, }, } """ result = {} for k, v in master.items(): *first, last = k.split('.') r = result for i in first: r = r.setdefault(i, {}) r[last] = v return result
[ ":", "param", "dict", "master", ":", "a", "multilevel", "dictionary", ":", "return", ":", "a", "unflattened", "dictionary", ":", "rtype", ":", "dict" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/flatten.py#L51-L85
[ "def", "unflatten", "(", "master", ")", ":", "result", "=", "{", "}", "for", "k", ",", "v", "in", "master", ".", "items", "(", ")", ":", "*", "first", ",", "last", "=", "k", ".", "split", "(", "'.'", ")", "r", "=", "result", "for", "i", "in", "first", ":", "r", "=", "r", ".", "setdefault", "(", "i", ",", "{", "}", ")", "r", "[", "last", "]", "=", "v", "return", "result" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Editor.receive
Receives a message, and either sets it immediately, or puts it on the edit queue if there is one.
bibliopixel/control/editor.py
def receive(self, msg): """ Receives a message, and either sets it immediately, or puts it on the edit queue if there is one. """ if self.edit_queue: self.edit_queue.put_edit(self._set, msg) else: self._set(msg)
def receive(self, msg): """ Receives a message, and either sets it immediately, or puts it on the edit queue if there is one. """ if self.edit_queue: self.edit_queue.put_edit(self._set, msg) else: self._set(msg)
[ "Receives", "a", "message", "and", "either", "sets", "it", "immediately", "or", "puts", "it", "on", "the", "edit", "queue", "if", "there", "is", "one", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/control/editor.py#L32-L41
[ "def", "receive", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "edit_queue", ":", "self", ".", "edit_queue", ".", "put_edit", "(", "self", ".", "_set", ",", "msg", ")", "else", ":", "self", ".", "_set", "(", "msg", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
make_matrix_coord_map
Helper method to generate X,Y coordinate maps for strips
bibliopixel/layout/geometry/matrix.py
def make_matrix_coord_map( dx, dy, serpentine=True, offset=0, rotation=0, y_flip=False): """Helper method to generate X,Y coordinate maps for strips""" result = [] for y in range(dy): if not serpentine or y % 2 == 0: result.append([(dx * y) + x + offset for x in range(dx)]) else: result.append([dx * (y + 1) - 1 - x + offset for x in range(dx)]) result = rotate_and_flip(result, rotation, y_flip) return result
def make_matrix_coord_map( dx, dy, serpentine=True, offset=0, rotation=0, y_flip=False): """Helper method to generate X,Y coordinate maps for strips""" result = [] for y in range(dy): if not serpentine or y % 2 == 0: result.append([(dx * y) + x + offset for x in range(dx)]) else: result.append([dx * (y + 1) - 1 - x + offset for x in range(dx)]) result = rotate_and_flip(result, rotation, y_flip) return result
[ "Helper", "method", "to", "generate", "X", "Y", "coordinate", "maps", "for", "strips" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/layout/geometry/matrix.py#L49-L61
[ "def", "make_matrix_coord_map", "(", "dx", ",", "dy", ",", "serpentine", "=", "True", ",", "offset", "=", "0", ",", "rotation", "=", "0", ",", "y_flip", "=", "False", ")", ":", "result", "=", "[", "]", "for", "y", "in", "range", "(", "dy", ")", ":", "if", "not", "serpentine", "or", "y", "%", "2", "==", "0", ":", "result", ".", "append", "(", "[", "(", "dx", "*", "y", ")", "+", "x", "+", "offset", "for", "x", "in", "range", "(", "dx", ")", "]", ")", "else", ":", "result", ".", "append", "(", "[", "dx", "*", "(", "y", "+", "1", ")", "-", "1", "-", "x", "+", "offset", "for", "x", "in", "range", "(", "dx", ")", "]", ")", "result", "=", "rotate_and_flip", "(", "result", ",", "rotation", ",", "y_flip", ")", "return", "result" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
make_object
Make an object from a symbol.
bibliopixel/project/importer.py
def make_object(*args, typename=None, python_path=None, datatype=None, **kwds): """Make an object from a symbol.""" datatype = datatype or import_symbol(typename, python_path) field_types = getattr(datatype, 'FIELD_TYPES', fields.FIELD_TYPES) return datatype(*args, **fields.component(kwds, field_types))
def make_object(*args, typename=None, python_path=None, datatype=None, **kwds): """Make an object from a symbol.""" datatype = datatype or import_symbol(typename, python_path) field_types = getattr(datatype, 'FIELD_TYPES', fields.FIELD_TYPES) return datatype(*args, **fields.component(kwds, field_types))
[ "Make", "an", "object", "from", "a", "symbol", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/importer.py#L55-L59
[ "def", "make_object", "(", "*", "args", ",", "typename", "=", "None", ",", "python_path", "=", "None", ",", "datatype", "=", "None", ",", "*", "*", "kwds", ")", ":", "datatype", "=", "datatype", "or", "import_symbol", "(", "typename", ",", "python_path", ")", "field_types", "=", "getattr", "(", "datatype", ",", "'FIELD_TYPES'", ",", "fields", ".", "FIELD_TYPES", ")", "return", "datatype", "(", "*", "args", ",", "*", "*", "fields", ".", "component", "(", "kwds", ",", "field_types", ")", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
pid_context
For the duration of this context manager, put the PID for this process into `pid_filename`, and then remove the file at the end.
bibliopixel/util/pid_context.py
def pid_context(pid_filename=None): """ For the duration of this context manager, put the PID for this process into `pid_filename`, and then remove the file at the end. """ pid_filename = pid_filename or DEFAULT_PID_FILENAME if os.path.exists(pid_filename): contents = open(pid_filename).read(16) log.warning('pid_filename %s already exists with contents %s', pid_filename, contents) with open(pid_filename, 'w') as fp: fp.write(str(os.getpid())) fp.write('\n') try: yield finally: try: os.remove(pid_filename) except Exception as e: log.error('Got an exception %s deleting the pid_filename %s', e, pid_filename)
def pid_context(pid_filename=None): """ For the duration of this context manager, put the PID for this process into `pid_filename`, and then remove the file at the end. """ pid_filename = pid_filename or DEFAULT_PID_FILENAME if os.path.exists(pid_filename): contents = open(pid_filename).read(16) log.warning('pid_filename %s already exists with contents %s', pid_filename, contents) with open(pid_filename, 'w') as fp: fp.write(str(os.getpid())) fp.write('\n') try: yield finally: try: os.remove(pid_filename) except Exception as e: log.error('Got an exception %s deleting the pid_filename %s', e, pid_filename)
[ "For", "the", "duration", "of", "this", "context", "manager", "put", "the", "PID", "for", "this", "process", "into", "pid_filename", "and", "then", "remove", "the", "file", "at", "the", "end", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/pid_context.py#L14-L36
[ "def", "pid_context", "(", "pid_filename", "=", "None", ")", ":", "pid_filename", "=", "pid_filename", "or", "DEFAULT_PID_FILENAME", "if", "os", ".", "path", ".", "exists", "(", "pid_filename", ")", ":", "contents", "=", "open", "(", "pid_filename", ")", ".", "read", "(", "16", ")", "log", ".", "warning", "(", "'pid_filename %s already exists with contents %s'", ",", "pid_filename", ",", "contents", ")", "with", "open", "(", "pid_filename", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "str", "(", "os", ".", "getpid", "(", ")", ")", ")", "fp", ".", "write", "(", "'\\n'", ")", "try", ":", "yield", "finally", ":", "try", ":", "os", ".", "remove", "(", "pid_filename", ")", "except", "Exception", "as", "e", ":", "log", ".", "error", "(", "'Got an exception %s deleting the pid_filename %s'", ",", "e", ",", "pid_filename", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
OffsetRange.index
Return an integer index or None
bibliopixel/util/offset_range.py
def index(self, i, length=None): """Return an integer index or None""" if self.begin <= i <= self.end: index = i - self.BEGIN - self.offset if length is None: length = self.full_range() else: length = min(length, self.full_range()) if 0 <= index < length: return index
def index(self, i, length=None): """Return an integer index or None""" if self.begin <= i <= self.end: index = i - self.BEGIN - self.offset if length is None: length = self.full_range() else: length = min(length, self.full_range()) if 0 <= index < length: return index
[ "Return", "an", "integer", "index", "or", "None" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/offset_range.py#L26-L36
[ "def", "index", "(", "self", ",", "i", ",", "length", "=", "None", ")", ":", "if", "self", ".", "begin", "<=", "i", "<=", "self", ".", "end", ":", "index", "=", "i", "-", "self", ".", "BEGIN", "-", "self", ".", "offset", "if", "length", "is", "None", ":", "length", "=", "self", ".", "full_range", "(", ")", "else", ":", "length", "=", "min", "(", "length", ",", "self", ".", "full_range", "(", ")", ")", "if", "0", "<=", "index", "<", "length", ":", "return", "index" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
OffsetRange.read_from
Returns a generator with the elements "data" taken by offset, restricted by self.begin and self.end, and padded on either end by `pad` to get back to the original length of `data`
bibliopixel/util/offset_range.py
def read_from(self, data, pad=0): """ Returns a generator with the elements "data" taken by offset, restricted by self.begin and self.end, and padded on either end by `pad` to get back to the original length of `data` """ for i in range(self.BEGIN, self.END + 1): index = self.index(i, len(data)) yield pad if index is None else data[index]
def read_from(self, data, pad=0): """ Returns a generator with the elements "data" taken by offset, restricted by self.begin and self.end, and padded on either end by `pad` to get back to the original length of `data` """ for i in range(self.BEGIN, self.END + 1): index = self.index(i, len(data)) yield pad if index is None else data[index]
[ "Returns", "a", "generator", "with", "the", "elements", "data", "taken", "by", "offset", "restricted", "by", "self", ".", "begin", "and", "self", ".", "end", "and", "padded", "on", "either", "end", "by", "pad", "to", "get", "back", "to", "the", "original", "length", "of", "data" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/util/offset_range.py#L38-L46
[ "def", "read_from", "(", "self", ",", "data", ",", "pad", "=", "0", ")", ":", "for", "i", "in", "range", "(", "self", ".", "BEGIN", ",", "self", ".", "END", "+", "1", ")", ":", "index", "=", "self", ".", "index", "(", "i", ",", "len", "(", "data", ")", ")", "yield", "pad", "if", "index", "is", "None", "else", "data", "[", "index", "]" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
_clean_animation
Cleans up all sorts of special cases that humans want when entering an animation from a yaml file. 1. Loading it from a file 2. Using just a typename instead of a dict 3. A single dict representing an animation, with a run: section. 4. (Legacy) Having a dict with parallel elements run: and animation: 5. (Legacy) A tuple or list: (animation, run )
bibliopixel/animation/collection.py
def _clean_animation(desc, parent): """ Cleans up all sorts of special cases that humans want when entering an animation from a yaml file. 1. Loading it from a file 2. Using just a typename instead of a dict 3. A single dict representing an animation, with a run: section. 4. (Legacy) Having a dict with parallel elements run: and animation: 5. (Legacy) A tuple or list: (animation, run ) """ desc = load.load_if_filename(desc) or desc if isinstance(desc, str): animation = {'typename': desc} elif not isinstance(desc, dict): raise TypeError('Unexpected type %s in collection' % type(desc)) elif 'typename' in desc or 'animation' not in desc: animation = desc else: animation = desc.pop('animation', {}) if isinstance(animation, str): animation = {'typename': animation} animation['run'] = desc.pop('run', {}) if desc: raise ValueError('Extra animation fields: ' + ', '.join(desc)) animation.setdefault('typename', DEFAULT_ANIMATION) animation = construct.to_type_constructor(animation, ANIMATION_PATH) datatype = animation.setdefault('datatype', failed.Failed) animation.setdefault('name', datatype.__name__) # Children without fps or sleep_time get it from their parents. # TODO: We shouldn't have to rewrite our descriptions here! The # animation engine should be smart enough to figure out the right # speed to run a subanimation without a run: section. run = animation.setdefault('run', {}) run_parent = parent.setdefault('run', {}) if not ('fps' in run or 'sleep_time' in run): if 'fps' in run_parent: run.update(fps=run_parent['fps']) elif 'sleep_time' in run_parent: run.update(sleep_time=run_parent['sleep_time']) return animation
def _clean_animation(desc, parent): """ Cleans up all sorts of special cases that humans want when entering an animation from a yaml file. 1. Loading it from a file 2. Using just a typename instead of a dict 3. A single dict representing an animation, with a run: section. 4. (Legacy) Having a dict with parallel elements run: and animation: 5. (Legacy) A tuple or list: (animation, run ) """ desc = load.load_if_filename(desc) or desc if isinstance(desc, str): animation = {'typename': desc} elif not isinstance(desc, dict): raise TypeError('Unexpected type %s in collection' % type(desc)) elif 'typename' in desc or 'animation' not in desc: animation = desc else: animation = desc.pop('animation', {}) if isinstance(animation, str): animation = {'typename': animation} animation['run'] = desc.pop('run', {}) if desc: raise ValueError('Extra animation fields: ' + ', '.join(desc)) animation.setdefault('typename', DEFAULT_ANIMATION) animation = construct.to_type_constructor(animation, ANIMATION_PATH) datatype = animation.setdefault('datatype', failed.Failed) animation.setdefault('name', datatype.__name__) # Children without fps or sleep_time get it from their parents. # TODO: We shouldn't have to rewrite our descriptions here! The # animation engine should be smart enough to figure out the right # speed to run a subanimation without a run: section. run = animation.setdefault('run', {}) run_parent = parent.setdefault('run', {}) if not ('fps' in run or 'sleep_time' in run): if 'fps' in run_parent: run.update(fps=run_parent['fps']) elif 'sleep_time' in run_parent: run.update(sleep_time=run_parent['sleep_time']) return animation
[ "Cleans", "up", "all", "sorts", "of", "special", "cases", "that", "humans", "want", "when", "entering", "an", "animation", "from", "a", "yaml", "file", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/collection.py#L113-L162
[ "def", "_clean_animation", "(", "desc", ",", "parent", ")", ":", "desc", "=", "load", ".", "load_if_filename", "(", "desc", ")", "or", "desc", "if", "isinstance", "(", "desc", ",", "str", ")", ":", "animation", "=", "{", "'typename'", ":", "desc", "}", "elif", "not", "isinstance", "(", "desc", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Unexpected type %s in collection'", "%", "type", "(", "desc", ")", ")", "elif", "'typename'", "in", "desc", "or", "'animation'", "not", "in", "desc", ":", "animation", "=", "desc", "else", ":", "animation", "=", "desc", ".", "pop", "(", "'animation'", ",", "{", "}", ")", "if", "isinstance", "(", "animation", ",", "str", ")", ":", "animation", "=", "{", "'typename'", ":", "animation", "}", "animation", "[", "'run'", "]", "=", "desc", ".", "pop", "(", "'run'", ",", "{", "}", ")", "if", "desc", ":", "raise", "ValueError", "(", "'Extra animation fields: '", "+", "', '", ".", "join", "(", "desc", ")", ")", "animation", ".", "setdefault", "(", "'typename'", ",", "DEFAULT_ANIMATION", ")", "animation", "=", "construct", ".", "to_type_constructor", "(", "animation", ",", "ANIMATION_PATH", ")", "datatype", "=", "animation", ".", "setdefault", "(", "'datatype'", ",", "failed", ".", "Failed", ")", "animation", ".", "setdefault", "(", "'name'", ",", "datatype", ".", "__name__", ")", "# Children without fps or sleep_time get it from their parents.", "# TODO: We shouldn't have to rewrite our descriptions here! The", "# animation engine should be smart enough to figure out the right", "# speed to run a subanimation without a run: section.", "run", "=", "animation", ".", "setdefault", "(", "'run'", ",", "{", "}", ")", "run_parent", "=", "parent", ".", "setdefault", "(", "'run'", ",", "{", "}", ")", "if", "not", "(", "'fps'", "in", "run", "or", "'sleep_time'", "in", "run", ")", ":", "if", "'fps'", "in", "run_parent", ":", "run", ".", "update", "(", "fps", "=", "run_parent", "[", "'fps'", "]", ")", "elif", "'sleep_time'", "in", "run_parent", ":", "run", ".", "update", "(", "sleep_time", "=", "run_parent", "[", "'sleep_time'", "]", ")", "return", "animation" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
_make_names_unique
Given a list of animations, some of which might have duplicate names, rename the first one to be <duplicate>_0, the second <duplicate>_1, <duplicate>_2, etc.
bibliopixel/animation/collection.py
def _make_names_unique(animations): """ Given a list of animations, some of which might have duplicate names, rename the first one to be <duplicate>_0, the second <duplicate>_1, <duplicate>_2, etc.""" counts = {} for a in animations: c = counts.get(a['name'], 0) + 1 counts[a['name']] = c if c > 1: a['name'] += '_' + str(c - 1) dupes = set(k for k, v in counts.items() if v > 1) for a in animations: if a['name'] in dupes: a['name'] += '_0'
def _make_names_unique(animations): """ Given a list of animations, some of which might have duplicate names, rename the first one to be <duplicate>_0, the second <duplicate>_1, <duplicate>_2, etc.""" counts = {} for a in animations: c = counts.get(a['name'], 0) + 1 counts[a['name']] = c if c > 1: a['name'] += '_' + str(c - 1) dupes = set(k for k, v in counts.items() if v > 1) for a in animations: if a['name'] in dupes: a['name'] += '_0'
[ "Given", "a", "list", "of", "animations", "some", "of", "which", "might", "have", "duplicate", "names", "rename", "the", "first", "one", "to", "be", "<duplicate", ">", "_0", "the", "second", "<duplicate", ">", "_1", "<duplicate", ">", "_2", "etc", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/collection.py#L165-L180
[ "def", "_make_names_unique", "(", "animations", ")", ":", "counts", "=", "{", "}", "for", "a", "in", "animations", ":", "c", "=", "counts", ".", "get", "(", "a", "[", "'name'", "]", ",", "0", ")", "+", "1", "counts", "[", "a", "[", "'name'", "]", "]", "=", "c", "if", "c", ">", "1", ":", "a", "[", "'name'", "]", "+=", "'_'", "+", "str", "(", "c", "-", "1", ")", "dupes", "=", "set", "(", "k", "for", "k", ",", "v", "in", "counts", ".", "items", "(", ")", "if", "v", ">", "1", ")", "for", "a", "in", "animations", ":", "if", "a", "[", "'name'", "]", "in", "dupes", ":", "a", "[", "'name'", "]", "+=", "'_0'" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Collection.detach
Give each animation a unique, mutable layout so they can run independently.
bibliopixel/animation/collection.py
def detach(self, overlay): """ Give each animation a unique, mutable layout so they can run independently. """ # See #868 for i, a in enumerate(self.animations): a.layout = a.layout.clone() if overlay and i: a.preclear = False
def detach(self, overlay): """ Give each animation a unique, mutable layout so they can run independently. """ # See #868 for i, a in enumerate(self.animations): a.layout = a.layout.clone() if overlay and i: a.preclear = False
[ "Give", "each", "animation", "a", "unique", "mutable", "layout", "so", "they", "can", "run", "independently", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/animation/collection.py#L55-L64
[ "def", "detach", "(", "self", ",", "overlay", ")", ":", "# See #868", "for", "i", ",", "a", "in", "enumerate", "(", "self", ".", "animations", ")", ":", "a", ".", "layout", "=", "a", ".", "layout", ".", "clone", "(", ")", "if", "overlay", "and", "i", ":", "a", ".", "preclear", "=", "False" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Curses.main
If a project has a Curses driver, the section "main" in the section "run" must be "bibliopixel.drivers.curses.Curses.main".
bibliopixel/drivers/curses.py
def main(): """ If a project has a Curses driver, the section "main" in the section "run" must be "bibliopixel.drivers.curses.Curses.main". """ if not _curses: # https://stackoverflow.com/a/1325587/43839 if os.name == 'nt': raise ValueError('curses is not supported under Windows') raise ValueError('Your platform does not support curses.') try: driver = next(iter(Curses.DRIVERS)) except: raise ValueError('No Curses driver in project') _curses.wrapper(driver.run_in_curses)
def main(): """ If a project has a Curses driver, the section "main" in the section "run" must be "bibliopixel.drivers.curses.Curses.main". """ if not _curses: # https://stackoverflow.com/a/1325587/43839 if os.name == 'nt': raise ValueError('curses is not supported under Windows') raise ValueError('Your platform does not support curses.') try: driver = next(iter(Curses.DRIVERS)) except: raise ValueError('No Curses driver in project') _curses.wrapper(driver.run_in_curses)
[ "If", "a", "project", "has", "a", "Curses", "driver", "the", "section", "main", "in", "the", "section", "run", "must", "be", "bibliopixel", ".", "drivers", ".", "curses", ".", "Curses", ".", "main", "." ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/drivers/curses.py#L55-L71
[ "def", "main", "(", ")", ":", "if", "not", "_curses", ":", "# https://stackoverflow.com/a/1325587/43839", "if", "os", ".", "name", "==", "'nt'", ":", "raise", "ValueError", "(", "'curses is not supported under Windows'", ")", "raise", "ValueError", "(", "'Your platform does not support curses.'", ")", "try", ":", "driver", "=", "next", "(", "iter", "(", "Curses", ".", "DRIVERS", ")", ")", "except", ":", "raise", "ValueError", "(", "'No Curses driver in project'", ")", "_curses", ".", "wrapper", "(", "driver", ".", "run_in_curses", ")" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
merge
Merge zero or more dictionaries representing projects with the default project dictionary and return the result
bibliopixel/project/merge.py
def merge(*projects): """ Merge zero or more dictionaries representing projects with the default project dictionary and return the result """ result = {} for project in projects: for name, section in (project or {}).items(): if name not in PROJECT_SECTIONS: raise ValueError(UNKNOWN_SECTION_ERROR % name) if section is None: result[name] = type(result[name])() continue if name in NOT_MERGEABLE + SPECIAL_CASE: result[name] = section continue if section and not isinstance(section, (dict, str)): cname = section.__class__.__name__ raise ValueError(SECTION_ISNT_DICT_ERROR % (name, cname)) if name == 'animation': # Useful hack to allow you to load projects as animations. adesc = load.load_if_filename(section) if adesc: section = adesc.get('animation', {}) section['run'] = adesc.get('run', {}) result_section = result.setdefault(name, {}) section = construct.to_type(section) for k, v in section.items(): if v is None: result_section.pop(k, None) else: result_section[k] = v return result
def merge(*projects): """ Merge zero or more dictionaries representing projects with the default project dictionary and return the result """ result = {} for project in projects: for name, section in (project or {}).items(): if name not in PROJECT_SECTIONS: raise ValueError(UNKNOWN_SECTION_ERROR % name) if section is None: result[name] = type(result[name])() continue if name in NOT_MERGEABLE + SPECIAL_CASE: result[name] = section continue if section and not isinstance(section, (dict, str)): cname = section.__class__.__name__ raise ValueError(SECTION_ISNT_DICT_ERROR % (name, cname)) if name == 'animation': # Useful hack to allow you to load projects as animations. adesc = load.load_if_filename(section) if adesc: section = adesc.get('animation', {}) section['run'] = adesc.get('run', {}) result_section = result.setdefault(name, {}) section = construct.to_type(section) for k, v in section.items(): if v is None: result_section.pop(k, None) else: result_section[k] = v return result
[ "Merge", "zero", "or", "more", "dictionaries", "representing", "projects", "with", "the", "default", "project", "dictionary", "and", "return", "the", "result" ]
ManiacalLabs/BiblioPixel
python
https://github.com/ManiacalLabs/BiblioPixel/blob/fd97e6c651a4bbcade64733847f4eec8f7704b7c/bibliopixel/project/merge.py#L36-L73
[ "def", "merge", "(", "*", "projects", ")", ":", "result", "=", "{", "}", "for", "project", "in", "projects", ":", "for", "name", ",", "section", "in", "(", "project", "or", "{", "}", ")", ".", "items", "(", ")", ":", "if", "name", "not", "in", "PROJECT_SECTIONS", ":", "raise", "ValueError", "(", "UNKNOWN_SECTION_ERROR", "%", "name", ")", "if", "section", "is", "None", ":", "result", "[", "name", "]", "=", "type", "(", "result", "[", "name", "]", ")", "(", ")", "continue", "if", "name", "in", "NOT_MERGEABLE", "+", "SPECIAL_CASE", ":", "result", "[", "name", "]", "=", "section", "continue", "if", "section", "and", "not", "isinstance", "(", "section", ",", "(", "dict", ",", "str", ")", ")", ":", "cname", "=", "section", ".", "__class__", ".", "__name__", "raise", "ValueError", "(", "SECTION_ISNT_DICT_ERROR", "%", "(", "name", ",", "cname", ")", ")", "if", "name", "==", "'animation'", ":", "# Useful hack to allow you to load projects as animations.", "adesc", "=", "load", ".", "load_if_filename", "(", "section", ")", "if", "adesc", ":", "section", "=", "adesc", ".", "get", "(", "'animation'", ",", "{", "}", ")", "section", "[", "'run'", "]", "=", "adesc", ".", "get", "(", "'run'", ",", "{", "}", ")", "result_section", "=", "result", ".", "setdefault", "(", "name", ",", "{", "}", ")", "section", "=", "construct", ".", "to_type", "(", "section", ")", "for", "k", ",", "v", "in", "section", ".", "items", "(", ")", ":", "if", "v", "is", "None", ":", "result_section", ".", "pop", "(", "k", ",", "None", ")", "else", ":", "result_section", "[", "k", "]", "=", "v", "return", "result" ]
fd97e6c651a4bbcade64733847f4eec8f7704b7c
valid
Amount.copy
Copy the instance and make sure not to use a reference
graphenecommon/amount.py
def copy(self): """ Copy the instance and make sure not to use a reference """ return self.__class__( amount=self["amount"], asset=self["asset"].copy(), blockchain_instance=self.blockchain, )
def copy(self): """ Copy the instance and make sure not to use a reference """ return self.__class__( amount=self["amount"], asset=self["asset"].copy(), blockchain_instance=self.blockchain, )
[ "Copy", "the", "instance", "and", "make", "sure", "not", "to", "use", "a", "reference" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/amount.py#L134-L141
[ "def", "copy", "(", "self", ")", ":", "return", "self", ".", "__class__", "(", "amount", "=", "self", "[", "\"amount\"", "]", ",", "asset", "=", "self", "[", "\"asset\"", "]", ".", "copy", "(", ")", ",", "blockchain_instance", "=", "self", ".", "blockchain", ",", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Amount.asset
Returns the asset as instance of :class:`.asset.Asset`
graphenecommon/amount.py
def asset(self): """ Returns the asset as instance of :class:`.asset.Asset` """ if not self["asset"]: self["asset"] = self.asset_class( self["symbol"], blockchain_instance=self.blockchain ) return self["asset"]
def asset(self): """ Returns the asset as instance of :class:`.asset.Asset` """ if not self["asset"]: self["asset"] = self.asset_class( self["symbol"], blockchain_instance=self.blockchain ) return self["asset"]
[ "Returns", "the", "asset", "as", "instance", "of", ":", "class", ":", ".", "asset", ".", "Asset" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/amount.py#L159-L166
[ "def", "asset", "(", "self", ")", ":", "if", "not", "self", "[", "\"asset\"", "]", ":", "self", "[", "\"asset\"", "]", "=", "self", ".", "asset_class", "(", "self", "[", "\"symbol\"", "]", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "return", "self", "[", "\"asset\"", "]" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.refresh
Refresh/Obtain an account's data from the API server
graphenecommon/account.py
def refresh(self): """ Refresh/Obtain an account's data from the API server """ import re if re.match(r"^1\.2\.[0-9]*$", self.identifier): account = self.blockchain.rpc.get_objects([self.identifier])[0] else: account = self.blockchain.rpc.lookup_account_names([self.identifier])[0] if not account: raise AccountDoesNotExistsException(self.identifier) self.store(account, "name") if self.full: # pragma: no cover accounts = self.blockchain.rpc.get_full_accounts([account["id"]], False) if accounts and isinstance(accounts, list): account = accounts[0][1] else: raise AccountDoesNotExistsException(self.identifier) super(Account, self).__init__( account["account"], blockchain_instance=self.blockchain ) for k, v in account.items(): if k != "account": self[k] = v else: super(Account, self).__init__(account, blockchain_instance=self.blockchain)
def refresh(self): """ Refresh/Obtain an account's data from the API server """ import re if re.match(r"^1\.2\.[0-9]*$", self.identifier): account = self.blockchain.rpc.get_objects([self.identifier])[0] else: account = self.blockchain.rpc.lookup_account_names([self.identifier])[0] if not account: raise AccountDoesNotExistsException(self.identifier) self.store(account, "name") if self.full: # pragma: no cover accounts = self.blockchain.rpc.get_full_accounts([account["id"]], False) if accounts and isinstance(accounts, list): account = accounts[0][1] else: raise AccountDoesNotExistsException(self.identifier) super(Account, self).__init__( account["account"], blockchain_instance=self.blockchain ) for k, v in account.items(): if k != "account": self[k] = v else: super(Account, self).__init__(account, blockchain_instance=self.blockchain)
[ "Refresh", "/", "Obtain", "an", "account", "s", "data", "from", "the", "API", "server" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L51-L77
[ "def", "refresh", "(", "self", ")", ":", "import", "re", "if", "re", ".", "match", "(", "r\"^1\\.2\\.[0-9]*$\"", ",", "self", ".", "identifier", ")", ":", "account", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_objects", "(", "[", "self", ".", "identifier", "]", ")", "[", "0", "]", "else", ":", "account", "=", "self", ".", "blockchain", ".", "rpc", ".", "lookup_account_names", "(", "[", "self", ".", "identifier", "]", ")", "[", "0", "]", "if", "not", "account", ":", "raise", "AccountDoesNotExistsException", "(", "self", ".", "identifier", ")", "self", ".", "store", "(", "account", ",", "\"name\"", ")", "if", "self", ".", "full", ":", "# pragma: no cover", "accounts", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_full_accounts", "(", "[", "account", "[", "\"id\"", "]", "]", ",", "False", ")", "if", "accounts", "and", "isinstance", "(", "accounts", ",", "list", ")", ":", "account", "=", "accounts", "[", "0", "]", "[", "1", "]", "else", ":", "raise", "AccountDoesNotExistsException", "(", "self", ".", "identifier", ")", "super", "(", "Account", ",", "self", ")", ".", "__init__", "(", "account", "[", "\"account\"", "]", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "for", "k", ",", "v", "in", "account", ".", "items", "(", ")", ":", "if", "k", "!=", "\"account\"", ":", "self", "[", "k", "]", "=", "v", "else", ":", "super", "(", "Account", ",", "self", ")", ".", "__init__", "(", "account", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.balances
List balances of an account. This call returns instances of :class:`amount.Amount`.
graphenecommon/account.py
def balances(self): """ List balances of an account. This call returns instances of :class:`amount.Amount`. """ balances = self.blockchain.rpc.get_account_balances(self["id"], []) return [ self.amount_class(b, blockchain_instance=self.blockchain) for b in balances if int(b["amount"]) > 0 ]
def balances(self): """ List balances of an account. This call returns instances of :class:`amount.Amount`. """ balances = self.blockchain.rpc.get_account_balances(self["id"], []) return [ self.amount_class(b, blockchain_instance=self.blockchain) for b in balances if int(b["amount"]) > 0 ]
[ "List", "balances", "of", "an", "account", ".", "This", "call", "returns", "instances", "of", ":", "class", ":", "amount", ".", "Amount", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L101-L110
[ "def", "balances", "(", "self", ")", ":", "balances", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_account_balances", "(", "self", "[", "\"id\"", "]", ",", "[", "]", ")", "return", "[", "self", ".", "amount_class", "(", "b", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "for", "b", "in", "balances", "if", "int", "(", "b", "[", "\"amount\"", "]", ")", ">", "0", "]" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.balance
Obtain the balance of a specific Asset. This call returns instances of :class:`amount.Amount`.
graphenecommon/account.py
def balance(self, symbol): """ Obtain the balance of a specific Asset. This call returns instances of :class:`amount.Amount`. """ if isinstance(symbol, dict) and "symbol" in symbol: symbol = symbol["symbol"] balances = self.balances for b in balances: if b["symbol"] == symbol: return b return self.amount_class(0, symbol, blockchain_instance=self.blockchain)
def balance(self, symbol): """ Obtain the balance of a specific Asset. This call returns instances of :class:`amount.Amount`. """ if isinstance(symbol, dict) and "symbol" in symbol: symbol = symbol["symbol"] balances = self.balances for b in balances: if b["symbol"] == symbol: return b return self.amount_class(0, symbol, blockchain_instance=self.blockchain)
[ "Obtain", "the", "balance", "of", "a", "specific", "Asset", ".", "This", "call", "returns", "instances", "of", ":", "class", ":", "amount", ".", "Amount", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L112-L122
[ "def", "balance", "(", "self", ",", "symbol", ")", ":", "if", "isinstance", "(", "symbol", ",", "dict", ")", "and", "\"symbol\"", "in", "symbol", ":", "symbol", "=", "symbol", "[", "\"symbol\"", "]", "balances", "=", "self", ".", "balances", "for", "b", "in", "balances", ":", "if", "b", "[", "\"symbol\"", "]", "==", "symbol", ":", "return", "b", "return", "self", ".", "amount_class", "(", "0", ",", "symbol", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.history
Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a ``for`` loop. :param int first: sequence number of the first transaction to return (*optional*) :param int last: sequence number of the last transaction to return (*optional*) :param int limit: limit number of transactions to return (*optional*) :param array only_ops: Limit generator by these operations (*optional*) :param array exclude_ops: Exclude these operations from generator (*optional*). ... note:: only_ops and exclude_ops takes an array of strings: The full list of operation ID's can be found in operationids.py. Example: ['transfer', 'fill_order']
graphenecommon/account.py
def history(self, first=0, last=0, limit=-1, only_ops=[], exclude_ops=[]): """ Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a ``for`` loop. :param int first: sequence number of the first transaction to return (*optional*) :param int last: sequence number of the last transaction to return (*optional*) :param int limit: limit number of transactions to return (*optional*) :param array only_ops: Limit generator by these operations (*optional*) :param array exclude_ops: Exclude these operations from generator (*optional*). ... note:: only_ops and exclude_ops takes an array of strings: The full list of operation ID's can be found in operationids.py. Example: ['transfer', 'fill_order'] """ _limit = 100 cnt = 0 if first < 0: first = 0 while True: # RPC call txs = self.blockchain.rpc.get_account_history( self["id"], "1.11.{}".format(last), _limit, "1.11.{}".format(first - 1), api="history", ) for i in txs: if ( exclude_ops and self.operations.getOperationNameForId(i["op"][0]) in exclude_ops ): continue if ( not only_ops or self.operations.getOperationNameForId(i["op"][0]) in only_ops ): cnt += 1 yield i if limit >= 0 and cnt >= limit: # pragma: no cover return if not txs: log.info("No more history returned from API node") break if len(txs) < _limit: log.info("Less than {} have been returned.".format(_limit)) break first = int(txs[-1]["id"].split(".")[2])
def history(self, first=0, last=0, limit=-1, only_ops=[], exclude_ops=[]): """ Returns a generator for individual account transactions. The latest operation will be first. This call can be used in a ``for`` loop. :param int first: sequence number of the first transaction to return (*optional*) :param int last: sequence number of the last transaction to return (*optional*) :param int limit: limit number of transactions to return (*optional*) :param array only_ops: Limit generator by these operations (*optional*) :param array exclude_ops: Exclude these operations from generator (*optional*). ... note:: only_ops and exclude_ops takes an array of strings: The full list of operation ID's can be found in operationids.py. Example: ['transfer', 'fill_order'] """ _limit = 100 cnt = 0 if first < 0: first = 0 while True: # RPC call txs = self.blockchain.rpc.get_account_history( self["id"], "1.11.{}".format(last), _limit, "1.11.{}".format(first - 1), api="history", ) for i in txs: if ( exclude_ops and self.operations.getOperationNameForId(i["op"][0]) in exclude_ops ): continue if ( not only_ops or self.operations.getOperationNameForId(i["op"][0]) in only_ops ): cnt += 1 yield i if limit >= 0 and cnt >= limit: # pragma: no cover return if not txs: log.info("No more history returned from API node") break if len(txs) < _limit: log.info("Less than {} have been returned.".format(_limit)) break first = int(txs[-1]["id"].split(".")[2])
[ "Returns", "a", "generator", "for", "individual", "account", "transactions", ".", "The", "latest", "operation", "will", "be", "first", ".", "This", "call", "can", "be", "used", "in", "a", "for", "loop", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L124-L182
[ "def", "history", "(", "self", ",", "first", "=", "0", ",", "last", "=", "0", ",", "limit", "=", "-", "1", ",", "only_ops", "=", "[", "]", ",", "exclude_ops", "=", "[", "]", ")", ":", "_limit", "=", "100", "cnt", "=", "0", "if", "first", "<", "0", ":", "first", "=", "0", "while", "True", ":", "# RPC call", "txs", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_account_history", "(", "self", "[", "\"id\"", "]", ",", "\"1.11.{}\"", ".", "format", "(", "last", ")", ",", "_limit", ",", "\"1.11.{}\"", ".", "format", "(", "first", "-", "1", ")", ",", "api", "=", "\"history\"", ",", ")", "for", "i", "in", "txs", ":", "if", "(", "exclude_ops", "and", "self", ".", "operations", ".", "getOperationNameForId", "(", "i", "[", "\"op\"", "]", "[", "0", "]", ")", "in", "exclude_ops", ")", ":", "continue", "if", "(", "not", "only_ops", "or", "self", ".", "operations", ".", "getOperationNameForId", "(", "i", "[", "\"op\"", "]", "[", "0", "]", ")", "in", "only_ops", ")", ":", "cnt", "+=", "1", "yield", "i", "if", "limit", ">=", "0", "and", "cnt", ">=", "limit", ":", "# pragma: no cover", "return", "if", "not", "txs", ":", "log", ".", "info", "(", "\"No more history returned from API node\"", ")", "break", "if", "len", "(", "txs", ")", "<", "_limit", ":", "log", ".", "info", "(", "\"Less than {} have been returned.\"", ".", "format", "(", "_limit", ")", ")", "break", "first", "=", "int", "(", "txs", "[", "-", "1", "]", "[", "\"id\"", "]", ".", "split", "(", "\".\"", ")", "[", "2", "]", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.upgrade
Upgrade account to life time member
graphenecommon/account.py
def upgrade(self): # pragma: no cover """ Upgrade account to life time member """ assert callable(self.blockchain.upgrade_account) return self.blockchain.upgrade_account(account=self)
def upgrade(self): # pragma: no cover """ Upgrade account to life time member """ assert callable(self.blockchain.upgrade_account) return self.blockchain.upgrade_account(account=self)
[ "Upgrade", "account", "to", "life", "time", "member" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L184-L188
[ "def", "upgrade", "(", "self", ")", ":", "# pragma: no cover", "assert", "callable", "(", "self", ".", "blockchain", ".", "upgrade_account", ")", "return", "self", ".", "blockchain", ".", "upgrade_account", "(", "account", "=", "self", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.whitelist
Add an other account to the whitelist of this account
graphenecommon/account.py
def whitelist(self, account): # pragma: no cover """ Add an other account to the whitelist of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=["white"], account=self)
def whitelist(self, account): # pragma: no cover """ Add an other account to the whitelist of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=["white"], account=self)
[ "Add", "an", "other", "account", "to", "the", "whitelist", "of", "this", "account" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L190-L194
[ "def", "whitelist", "(", "self", ",", "account", ")", ":", "# pragma: no cover", "assert", "callable", "(", "self", ".", "blockchain", ".", "account_whitelist", ")", "return", "self", ".", "blockchain", ".", "account_whitelist", "(", "account", ",", "lists", "=", "[", "\"white\"", "]", ",", "account", "=", "self", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.blacklist
Add an other account to the blacklist of this account
graphenecommon/account.py
def blacklist(self, account): # pragma: no cover """ Add an other account to the blacklist of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=["black"], account=self)
def blacklist(self, account): # pragma: no cover """ Add an other account to the blacklist of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=["black"], account=self)
[ "Add", "an", "other", "account", "to", "the", "blacklist", "of", "this", "account" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L196-L200
[ "def", "blacklist", "(", "self", ",", "account", ")", ":", "# pragma: no cover", "assert", "callable", "(", "self", ".", "blockchain", ".", "account_whitelist", ")", "return", "self", ".", "blockchain", ".", "account_whitelist", "(", "account", ",", "lists", "=", "[", "\"black\"", "]", ",", "account", "=", "self", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Account.nolist
Remove an other account from any list of this account
graphenecommon/account.py
def nolist(self, account): # pragma: no cover """ Remove an other account from any list of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=[], account=self)
def nolist(self, account): # pragma: no cover """ Remove an other account from any list of this account """ assert callable(self.blockchain.account_whitelist) return self.blockchain.account_whitelist(account, lists=[], account=self)
[ "Remove", "an", "other", "account", "from", "any", "list", "of", "this", "account" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L202-L206
[ "def", "nolist", "(", "self", ",", "account", ")", ":", "# pragma: no cover", "assert", "callable", "(", "self", ".", "blockchain", ".", "account_whitelist", ")", "return", "self", ".", "blockchain", ".", "account_whitelist", "(", "account", ",", "lists", "=", "[", "]", ",", "account", "=", "self", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
AccountUpdate.account
In oder to obtain the actual :class:`account.Account` from this class, you can use the ``account`` attribute.
graphenecommon/account.py
def account(self): """ In oder to obtain the actual :class:`account.Account` from this class, you can use the ``account`` attribute. """ account = self.account_class(self["owner"], blockchain_instance=self.blockchain) # account.refresh() return account
def account(self): """ In oder to obtain the actual :class:`account.Account` from this class, you can use the ``account`` attribute. """ account = self.account_class(self["owner"], blockchain_instance=self.blockchain) # account.refresh() return account
[ "In", "oder", "to", "obtain", "the", "actual", ":", "class", ":", "account", ".", "Account", "from", "this", "class", "you", "can", "use", "the", "account", "attribute", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/account.py#L242-L249
[ "def", "account", "(", "self", ")", ":", "account", "=", "self", ".", "account_class", "(", "self", "[", "\"owner\"", "]", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "# account.refresh()", "return", "account" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
recover_public_key
Recover the public key from the the signature
graphenebase/ecdsa.py
def recover_public_key(digest, signature, i, message=None): """ Recover the public key from the the signature """ # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily curve = ecdsa.SECP256k1.curve G = ecdsa.SECP256k1.generator order = ecdsa.SECP256k1.order yp = i % 2 r, s = ecdsa.util.sigdecode_string(signature, order) # 1.1 x = r + (i // 2) * order # 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified. # This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve. alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p() beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p()) y = beta if (beta - yp) % 2 == 0 else curve.p() - beta # 1.4 Constructor of Point is supposed to check if nR is at infinity. R = ecdsa.ellipticcurve.Point(curve, x, y, order) # 1.5 Compute e e = ecdsa.util.string_to_number(digest) # 1.6 Compute Q = r^-1(sR - eG) Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G) if SECP256K1_MODULE == "cryptography" and message is not None: if not isinstance(message, bytes): message = bytes(message, "utf-8") # pragma: no cover sigder = encode_dss_signature(r, s) public_key = ec.EllipticCurvePublicNumbers( Q._Point__x, Q._Point__y, ec.SECP256K1() ).public_key(default_backend()) public_key.verify(sigder, message, ec.ECDSA(hashes.SHA256())) return public_key else: # Not strictly necessary, but let's verify the message for paranoia's sake. if not ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1 ).verify_digest( signature, digest, sigdecode=ecdsa.util.sigdecode_string ): # pragma: no cover return None # pragma: no cover return ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1 )
def recover_public_key(digest, signature, i, message=None): """ Recover the public key from the the signature """ # See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily curve = ecdsa.SECP256k1.curve G = ecdsa.SECP256k1.generator order = ecdsa.SECP256k1.order yp = i % 2 r, s = ecdsa.util.sigdecode_string(signature, order) # 1.1 x = r + (i // 2) * order # 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified. # This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve. alpha = ((x * x * x) + (curve.a() * x) + curve.b()) % curve.p() beta = ecdsa.numbertheory.square_root_mod_prime(alpha, curve.p()) y = beta if (beta - yp) % 2 == 0 else curve.p() - beta # 1.4 Constructor of Point is supposed to check if nR is at infinity. R = ecdsa.ellipticcurve.Point(curve, x, y, order) # 1.5 Compute e e = ecdsa.util.string_to_number(digest) # 1.6 Compute Q = r^-1(sR - eG) Q = ecdsa.numbertheory.inverse_mod(r, order) * (s * R + (-e % order) * G) if SECP256K1_MODULE == "cryptography" and message is not None: if not isinstance(message, bytes): message = bytes(message, "utf-8") # pragma: no cover sigder = encode_dss_signature(r, s) public_key = ec.EllipticCurvePublicNumbers( Q._Point__x, Q._Point__y, ec.SECP256K1() ).public_key(default_backend()) public_key.verify(sigder, message, ec.ECDSA(hashes.SHA256())) return public_key else: # Not strictly necessary, but let's verify the message for paranoia's sake. if not ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1 ).verify_digest( signature, digest, sigdecode=ecdsa.util.sigdecode_string ): # pragma: no cover return None # pragma: no cover return ecdsa.VerifyingKey.from_public_point( Q, curve=ecdsa.SECP256k1 )
[ "Recover", "the", "public", "key", "from", "the", "the", "signature" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/ecdsa.py#L80-L123
[ "def", "recover_public_key", "(", "digest", ",", "signature", ",", "i", ",", "message", "=", "None", ")", ":", "# See http: //www.secg.org/download/aid-780/sec1-v2.pdf section 4.1.6 primarily", "curve", "=", "ecdsa", ".", "SECP256k1", ".", "curve", "G", "=", "ecdsa", ".", "SECP256k1", ".", "generator", "order", "=", "ecdsa", ".", "SECP256k1", ".", "order", "yp", "=", "i", "%", "2", "r", ",", "s", "=", "ecdsa", ".", "util", ".", "sigdecode_string", "(", "signature", ",", "order", ")", "# 1.1", "x", "=", "r", "+", "(", "i", "//", "2", ")", "*", "order", "# 1.3. This actually calculates for either effectively 02||X or 03||X depending on 'k' instead of always for 02||X as specified.", "# This substitutes for the lack of reversing R later on. -R actually is defined to be just flipping the y-coordinate in the elliptic curve.", "alpha", "=", "(", "(", "x", "*", "x", "*", "x", ")", "+", "(", "curve", ".", "a", "(", ")", "*", "x", ")", "+", "curve", ".", "b", "(", ")", ")", "%", "curve", ".", "p", "(", ")", "beta", "=", "ecdsa", ".", "numbertheory", ".", "square_root_mod_prime", "(", "alpha", ",", "curve", ".", "p", "(", ")", ")", "y", "=", "beta", "if", "(", "beta", "-", "yp", ")", "%", "2", "==", "0", "else", "curve", ".", "p", "(", ")", "-", "beta", "# 1.4 Constructor of Point is supposed to check if nR is at infinity.", "R", "=", "ecdsa", ".", "ellipticcurve", ".", "Point", "(", "curve", ",", "x", ",", "y", ",", "order", ")", "# 1.5 Compute e", "e", "=", "ecdsa", ".", "util", ".", "string_to_number", "(", "digest", ")", "# 1.6 Compute Q = r^-1(sR - eG)", "Q", "=", "ecdsa", ".", "numbertheory", ".", "inverse_mod", "(", "r", ",", "order", ")", "*", "(", "s", "*", "R", "+", "(", "-", "e", "%", "order", ")", "*", "G", ")", "if", "SECP256K1_MODULE", "==", "\"cryptography\"", "and", "message", "is", "not", "None", ":", "if", "not", "isinstance", "(", "message", ",", "bytes", ")", ":", "message", "=", "bytes", "(", "message", ",", "\"utf-8\"", ")", "# pragma: no cover", "sigder", "=", "encode_dss_signature", "(", "r", ",", "s", ")", "public_key", "=", "ec", ".", "EllipticCurvePublicNumbers", "(", "Q", ".", "_Point__x", ",", "Q", ".", "_Point__y", ",", "ec", ".", "SECP256K1", "(", ")", ")", ".", "public_key", "(", "default_backend", "(", ")", ")", "public_key", ".", "verify", "(", "sigder", ",", "message", ",", "ec", ".", "ECDSA", "(", "hashes", ".", "SHA256", "(", ")", ")", ")", "return", "public_key", "else", ":", "# Not strictly necessary, but let's verify the message for paranoia's sake.", "if", "not", "ecdsa", ".", "VerifyingKey", ".", "from_public_point", "(", "Q", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "verify_digest", "(", "signature", ",", "digest", ",", "sigdecode", "=", "ecdsa", ".", "util", ".", "sigdecode_string", ")", ":", "# pragma: no cover", "return", "None", "# pragma: no cover", "return", "ecdsa", ".", "VerifyingKey", ".", "from_public_point", "(", "Q", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
recoverPubkeyParameter
Use to derive a number that allows to easily recover the public key from the signature
graphenebase/ecdsa.py
def recoverPubkeyParameter(message, digest, signature, pubkey): """ Use to derive a number that allows to easily recover the public key from the signature """ if not isinstance(message, bytes): message = bytes(message, "utf-8") # pragma: no cover for i in range(0, 4): if SECP256K1_MODULE == "secp256k1": # pragma: no cover sig = pubkey.ecdsa_recoverable_deserialize(signature, i) p = secp256k1.PublicKey(pubkey.ecdsa_recover(message, sig)) if p.serialize() == pubkey.serialize(): return i elif SECP256K1_MODULE == "cryptography" and not isinstance(pubkey, PublicKey): p = recover_public_key(digest, signature, i, message) p_comp = hexlify(compressedPubkey(p)) pubkey_comp = hexlify(compressedPubkey(pubkey)) if p_comp == pubkey_comp: return i else: # pragma: no cover p = recover_public_key(digest, signature, i) p_comp = hexlify(compressedPubkey(p)) p_string = hexlify(p.to_string()) if isinstance(pubkey, PublicKey): # pragma: no cover pubkey_string = bytes(repr(pubkey), "ascii") else: # pragma: no cover pubkey_string = hexlify(pubkey.to_string()) if p_string == pubkey_string or p_comp == pubkey_string: # pragma: no cover return i
def recoverPubkeyParameter(message, digest, signature, pubkey): """ Use to derive a number that allows to easily recover the public key from the signature """ if not isinstance(message, bytes): message = bytes(message, "utf-8") # pragma: no cover for i in range(0, 4): if SECP256K1_MODULE == "secp256k1": # pragma: no cover sig = pubkey.ecdsa_recoverable_deserialize(signature, i) p = secp256k1.PublicKey(pubkey.ecdsa_recover(message, sig)) if p.serialize() == pubkey.serialize(): return i elif SECP256K1_MODULE == "cryptography" and not isinstance(pubkey, PublicKey): p = recover_public_key(digest, signature, i, message) p_comp = hexlify(compressedPubkey(p)) pubkey_comp = hexlify(compressedPubkey(pubkey)) if p_comp == pubkey_comp: return i else: # pragma: no cover p = recover_public_key(digest, signature, i) p_comp = hexlify(compressedPubkey(p)) p_string = hexlify(p.to_string()) if isinstance(pubkey, PublicKey): # pragma: no cover pubkey_string = bytes(repr(pubkey), "ascii") else: # pragma: no cover pubkey_string = hexlify(pubkey.to_string()) if p_string == pubkey_string or p_comp == pubkey_string: # pragma: no cover return i
[ "Use", "to", "derive", "a", "number", "that", "allows", "to", "easily", "recover", "the", "public", "key", "from", "the", "signature" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/ecdsa.py#L126-L153
[ "def", "recoverPubkeyParameter", "(", "message", ",", "digest", ",", "signature", ",", "pubkey", ")", ":", "if", "not", "isinstance", "(", "message", ",", "bytes", ")", ":", "message", "=", "bytes", "(", "message", ",", "\"utf-8\"", ")", "# pragma: no cover", "for", "i", "in", "range", "(", "0", ",", "4", ")", ":", "if", "SECP256K1_MODULE", "==", "\"secp256k1\"", ":", "# pragma: no cover", "sig", "=", "pubkey", ".", "ecdsa_recoverable_deserialize", "(", "signature", ",", "i", ")", "p", "=", "secp256k1", ".", "PublicKey", "(", "pubkey", ".", "ecdsa_recover", "(", "message", ",", "sig", ")", ")", "if", "p", ".", "serialize", "(", ")", "==", "pubkey", ".", "serialize", "(", ")", ":", "return", "i", "elif", "SECP256K1_MODULE", "==", "\"cryptography\"", "and", "not", "isinstance", "(", "pubkey", ",", "PublicKey", ")", ":", "p", "=", "recover_public_key", "(", "digest", ",", "signature", ",", "i", ",", "message", ")", "p_comp", "=", "hexlify", "(", "compressedPubkey", "(", "p", ")", ")", "pubkey_comp", "=", "hexlify", "(", "compressedPubkey", "(", "pubkey", ")", ")", "if", "p_comp", "==", "pubkey_comp", ":", "return", "i", "else", ":", "# pragma: no cover", "p", "=", "recover_public_key", "(", "digest", ",", "signature", ",", "i", ")", "p_comp", "=", "hexlify", "(", "compressedPubkey", "(", "p", ")", ")", "p_string", "=", "hexlify", "(", "p", ".", "to_string", "(", ")", ")", "if", "isinstance", "(", "pubkey", ",", "PublicKey", ")", ":", "# pragma: no cover", "pubkey_string", "=", "bytes", "(", "repr", "(", "pubkey", ")", ",", "\"ascii\"", ")", "else", ":", "# pragma: no cover", "pubkey_string", "=", "hexlify", "(", "pubkey", ".", "to_string", "(", ")", ")", "if", "p_string", "==", "pubkey_string", "or", "p_comp", "==", "pubkey_string", ":", "# pragma: no cover", "return", "i" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
sign_message
Sign a digest with a wif key :param str wif: Private key in
graphenebase/ecdsa.py
def sign_message(message, wif, hashfn=hashlib.sha256): """ Sign a digest with a wif key :param str wif: Private key in """ if not isinstance(message, bytes): message = bytes(message, "utf-8") digest = hashfn(message).digest() priv_key = PrivateKey(wif) p = bytes(priv_key) if SECP256K1_MODULE == "secp256k1": ndata = secp256k1.ffi.new("const int *ndata") ndata[0] = 0 while True: ndata[0] += 1 privkey = secp256k1.PrivateKey(p, raw=True) sig = secp256k1.ffi.new("secp256k1_ecdsa_recoverable_signature *") signed = secp256k1.lib.secp256k1_ecdsa_sign_recoverable( privkey.ctx, sig, digest, privkey.private_key, secp256k1.ffi.NULL, ndata ) if not signed == 1: # pragma: no cover raise AssertionError() signature, i = privkey.ecdsa_recoverable_serialize(sig) if _is_canonical(signature): i += 4 # compressed i += 27 # compact break elif SECP256K1_MODULE == "cryptography": cnt = 0 private_key = ec.derive_private_key( int(repr(priv_key), 16), ec.SECP256K1(), default_backend() ) public_key = private_key.public_key() while True: cnt += 1 if not cnt % 20: # pragma: no cover log.info( "Still searching for a canonical signature. Tried %d times already!" % cnt ) order = ecdsa.SECP256k1.order # signer = private_key.signer(ec.ECDSA(hashes.SHA256())) # signer.update(message) # sigder = signer.finalize() sigder = private_key.sign(message, ec.ECDSA(hashes.SHA256())) r, s = decode_dss_signature(sigder) signature = ecdsa.util.sigencode_string(r, s, order) # Make sure signature is canonical! # sigder = bytearray(sigder) lenR = sigder[3] lenS = sigder[5 + lenR] if lenR is 32 and lenS is 32: # Derive the recovery parameter # i = recoverPubkeyParameter(message, digest, signature, public_key) i += 4 # compressed i += 27 # compact break else: # pragma: no branch # pragma: no cover cnt = 0 sk = ecdsa.SigningKey.from_string(p, curve=ecdsa.SECP256k1) while 1: cnt += 1 if not cnt % 20: # pragma: no branch log.info( "Still searching for a canonical signature. Tried %d times already!" % cnt ) # Deterministic k # k = ecdsa.rfc6979.generate_k( sk.curve.generator.order(), sk.privkey.secret_multiplier, hashlib.sha256, hashlib.sha256( digest + struct.pack( "d", time.time() ) # use the local time to randomize the signature ).digest(), ) # Sign message # sigder = sk.sign_digest(digest, sigencode=ecdsa.util.sigencode_der, k=k) # Reformating of signature # r, s = ecdsa.util.sigdecode_der(sigder, sk.curve.generator.order()) signature = ecdsa.util.sigencode_string(r, s, sk.curve.generator.order()) # Make sure signature is canonical! # sigder = bytearray(sigder) lenR = sigder[3] lenS = sigder[5 + lenR] if lenR is 32 and lenS is 32: # Derive the recovery parameter # i = recoverPubkeyParameter( message, digest, signature, sk.get_verifying_key() ) i += 4 # compressed i += 27 # compact break # pack signature # sigstr = struct.pack("<B", i) sigstr += signature return sigstr
def sign_message(message, wif, hashfn=hashlib.sha256): """ Sign a digest with a wif key :param str wif: Private key in """ if not isinstance(message, bytes): message = bytes(message, "utf-8") digest = hashfn(message).digest() priv_key = PrivateKey(wif) p = bytes(priv_key) if SECP256K1_MODULE == "secp256k1": ndata = secp256k1.ffi.new("const int *ndata") ndata[0] = 0 while True: ndata[0] += 1 privkey = secp256k1.PrivateKey(p, raw=True) sig = secp256k1.ffi.new("secp256k1_ecdsa_recoverable_signature *") signed = secp256k1.lib.secp256k1_ecdsa_sign_recoverable( privkey.ctx, sig, digest, privkey.private_key, secp256k1.ffi.NULL, ndata ) if not signed == 1: # pragma: no cover raise AssertionError() signature, i = privkey.ecdsa_recoverable_serialize(sig) if _is_canonical(signature): i += 4 # compressed i += 27 # compact break elif SECP256K1_MODULE == "cryptography": cnt = 0 private_key = ec.derive_private_key( int(repr(priv_key), 16), ec.SECP256K1(), default_backend() ) public_key = private_key.public_key() while True: cnt += 1 if not cnt % 20: # pragma: no cover log.info( "Still searching for a canonical signature. Tried %d times already!" % cnt ) order = ecdsa.SECP256k1.order # signer = private_key.signer(ec.ECDSA(hashes.SHA256())) # signer.update(message) # sigder = signer.finalize() sigder = private_key.sign(message, ec.ECDSA(hashes.SHA256())) r, s = decode_dss_signature(sigder) signature = ecdsa.util.sigencode_string(r, s, order) # Make sure signature is canonical! # sigder = bytearray(sigder) lenR = sigder[3] lenS = sigder[5 + lenR] if lenR is 32 and lenS is 32: # Derive the recovery parameter # i = recoverPubkeyParameter(message, digest, signature, public_key) i += 4 # compressed i += 27 # compact break else: # pragma: no branch # pragma: no cover cnt = 0 sk = ecdsa.SigningKey.from_string(p, curve=ecdsa.SECP256k1) while 1: cnt += 1 if not cnt % 20: # pragma: no branch log.info( "Still searching for a canonical signature. Tried %d times already!" % cnt ) # Deterministic k # k = ecdsa.rfc6979.generate_k( sk.curve.generator.order(), sk.privkey.secret_multiplier, hashlib.sha256, hashlib.sha256( digest + struct.pack( "d", time.time() ) # use the local time to randomize the signature ).digest(), ) # Sign message # sigder = sk.sign_digest(digest, sigencode=ecdsa.util.sigencode_der, k=k) # Reformating of signature # r, s = ecdsa.util.sigdecode_der(sigder, sk.curve.generator.order()) signature = ecdsa.util.sigencode_string(r, s, sk.curve.generator.order()) # Make sure signature is canonical! # sigder = bytearray(sigder) lenR = sigder[3] lenS = sigder[5 + lenR] if lenR is 32 and lenS is 32: # Derive the recovery parameter # i = recoverPubkeyParameter( message, digest, signature, sk.get_verifying_key() ) i += 4 # compressed i += 27 # compact break # pack signature # sigstr = struct.pack("<B", i) sigstr += signature return sigstr
[ "Sign", "a", "digest", "with", "a", "wif", "key" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/ecdsa.py#L156-L272
[ "def", "sign_message", "(", "message", ",", "wif", ",", "hashfn", "=", "hashlib", ".", "sha256", ")", ":", "if", "not", "isinstance", "(", "message", ",", "bytes", ")", ":", "message", "=", "bytes", "(", "message", ",", "\"utf-8\"", ")", "digest", "=", "hashfn", "(", "message", ")", ".", "digest", "(", ")", "priv_key", "=", "PrivateKey", "(", "wif", ")", "p", "=", "bytes", "(", "priv_key", ")", "if", "SECP256K1_MODULE", "==", "\"secp256k1\"", ":", "ndata", "=", "secp256k1", ".", "ffi", ".", "new", "(", "\"const int *ndata\"", ")", "ndata", "[", "0", "]", "=", "0", "while", "True", ":", "ndata", "[", "0", "]", "+=", "1", "privkey", "=", "secp256k1", ".", "PrivateKey", "(", "p", ",", "raw", "=", "True", ")", "sig", "=", "secp256k1", ".", "ffi", ".", "new", "(", "\"secp256k1_ecdsa_recoverable_signature *\"", ")", "signed", "=", "secp256k1", ".", "lib", ".", "secp256k1_ecdsa_sign_recoverable", "(", "privkey", ".", "ctx", ",", "sig", ",", "digest", ",", "privkey", ".", "private_key", ",", "secp256k1", ".", "ffi", ".", "NULL", ",", "ndata", ")", "if", "not", "signed", "==", "1", ":", "# pragma: no cover", "raise", "AssertionError", "(", ")", "signature", ",", "i", "=", "privkey", ".", "ecdsa_recoverable_serialize", "(", "sig", ")", "if", "_is_canonical", "(", "signature", ")", ":", "i", "+=", "4", "# compressed", "i", "+=", "27", "# compact", "break", "elif", "SECP256K1_MODULE", "==", "\"cryptography\"", ":", "cnt", "=", "0", "private_key", "=", "ec", ".", "derive_private_key", "(", "int", "(", "repr", "(", "priv_key", ")", ",", "16", ")", ",", "ec", ".", "SECP256K1", "(", ")", ",", "default_backend", "(", ")", ")", "public_key", "=", "private_key", ".", "public_key", "(", ")", "while", "True", ":", "cnt", "+=", "1", "if", "not", "cnt", "%", "20", ":", "# pragma: no cover", "log", ".", "info", "(", "\"Still searching for a canonical signature. Tried %d times already!\"", "%", "cnt", ")", "order", "=", "ecdsa", ".", "SECP256k1", ".", "order", "# signer = private_key.signer(ec.ECDSA(hashes.SHA256()))", "# signer.update(message)", "# sigder = signer.finalize()", "sigder", "=", "private_key", ".", "sign", "(", "message", ",", "ec", ".", "ECDSA", "(", "hashes", ".", "SHA256", "(", ")", ")", ")", "r", ",", "s", "=", "decode_dss_signature", "(", "sigder", ")", "signature", "=", "ecdsa", ".", "util", ".", "sigencode_string", "(", "r", ",", "s", ",", "order", ")", "# Make sure signature is canonical!", "#", "sigder", "=", "bytearray", "(", "sigder", ")", "lenR", "=", "sigder", "[", "3", "]", "lenS", "=", "sigder", "[", "5", "+", "lenR", "]", "if", "lenR", "is", "32", "and", "lenS", "is", "32", ":", "# Derive the recovery parameter", "#", "i", "=", "recoverPubkeyParameter", "(", "message", ",", "digest", ",", "signature", ",", "public_key", ")", "i", "+=", "4", "# compressed", "i", "+=", "27", "# compact", "break", "else", ":", "# pragma: no branch # pragma: no cover", "cnt", "=", "0", "sk", "=", "ecdsa", ".", "SigningKey", ".", "from_string", "(", "p", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", "while", "1", ":", "cnt", "+=", "1", "if", "not", "cnt", "%", "20", ":", "# pragma: no branch", "log", ".", "info", "(", "\"Still searching for a canonical signature. Tried %d times already!\"", "%", "cnt", ")", "# Deterministic k", "#", "k", "=", "ecdsa", ".", "rfc6979", ".", "generate_k", "(", "sk", ".", "curve", ".", "generator", ".", "order", "(", ")", ",", "sk", ".", "privkey", ".", "secret_multiplier", ",", "hashlib", ".", "sha256", ",", "hashlib", ".", "sha256", "(", "digest", "+", "struct", ".", "pack", "(", "\"d\"", ",", "time", ".", "time", "(", ")", ")", "# use the local time to randomize the signature", ")", ".", "digest", "(", ")", ",", ")", "# Sign message", "#", "sigder", "=", "sk", ".", "sign_digest", "(", "digest", ",", "sigencode", "=", "ecdsa", ".", "util", ".", "sigencode_der", ",", "k", "=", "k", ")", "# Reformating of signature", "#", "r", ",", "s", "=", "ecdsa", ".", "util", ".", "sigdecode_der", "(", "sigder", ",", "sk", ".", "curve", ".", "generator", ".", "order", "(", ")", ")", "signature", "=", "ecdsa", ".", "util", ".", "sigencode_string", "(", "r", ",", "s", ",", "sk", ".", "curve", ".", "generator", ".", "order", "(", ")", ")", "# Make sure signature is canonical!", "#", "sigder", "=", "bytearray", "(", "sigder", ")", "lenR", "=", "sigder", "[", "3", "]", "lenS", "=", "sigder", "[", "5", "+", "lenR", "]", "if", "lenR", "is", "32", "and", "lenS", "is", "32", ":", "# Derive the recovery parameter", "#", "i", "=", "recoverPubkeyParameter", "(", "message", ",", "digest", ",", "signature", ",", "sk", ".", "get_verifying_key", "(", ")", ")", "i", "+=", "4", "# compressed", "i", "+=", "27", "# compact", "break", "# pack signature", "#", "sigstr", "=", "struct", ".", "pack", "(", "\"<B\"", ",", "i", ")", "sigstr", "+=", "signature", "return", "sigstr" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
getBlockParams
Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node!
graphenebase/transactions.py
def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = struct.unpack_from( "<I", unhexlify(dynBCParams["head_block_id"]), 4 )[0] return ref_block_num, ref_block_prefix
def getBlockParams(ws): """ Auxiliary method to obtain ``ref_block_num`` and ``ref_block_prefix``. Requires a websocket connection to a witness node! """ dynBCParams = ws.get_dynamic_global_properties() ref_block_num = dynBCParams["head_block_number"] & 0xFFFF ref_block_prefix = struct.unpack_from( "<I", unhexlify(dynBCParams["head_block_id"]), 4 )[0] return ref_block_num, ref_block_prefix
[ "Auxiliary", "method", "to", "obtain", "ref_block_num", "and", "ref_block_prefix", ".", "Requires", "a", "websocket", "connection", "to", "a", "witness", "node!" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/transactions.py#L19-L29
[ "def", "getBlockParams", "(", "ws", ")", ":", "dynBCParams", "=", "ws", ".", "get_dynamic_global_properties", "(", ")", "ref_block_num", "=", "dynBCParams", "[", "\"head_block_number\"", "]", "&", "0xFFFF", "ref_block_prefix", "=", "struct", ".", "unpack_from", "(", "\"<I\"", ",", "unhexlify", "(", "dynBCParams", "[", "\"head_block_id\"", "]", ")", ",", "4", ")", "[", "0", "]", "return", "ref_block_num", ",", "ref_block_prefix" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
formatTimeFromNow
Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str
graphenebase/transactions.py
def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
def formatTimeFromNow(secs=0): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs)).strftime(timeformat)
[ "Properly", "Format", "Time", "that", "is", "x", "seconds", "in", "the", "future" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/transactions.py#L32-L40
[ "def", "formatTimeFromNow", "(", "secs", "=", "0", ")", ":", "return", "datetime", ".", "utcfromtimestamp", "(", "time", ".", "time", "(", ")", "+", "int", "(", "secs", ")", ")", ".", "strftime", "(", "timeformat", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.block_time
Returns a datetime of the block with the given block number. :param int block_num: Block number
graphenecommon/blockchain.py
def block_time(self, block_num): """ Returns a datetime of the block with the given block number. :param int block_num: Block number """ return self.block_class(block_num, blockchain_instance=self.blockchain).time()
def block_time(self, block_num): """ Returns a datetime of the block with the given block number. :param int block_num: Block number """ return self.block_class(block_num, blockchain_instance=self.blockchain).time()
[ "Returns", "a", "datetime", "of", "the", "block", "with", "the", "given", "block", "number", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L105-L111
[ "def", "block_time", "(", "self", ",", "block_num", ")", ":", "return", "self", ".", "block_class", "(", "block_num", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", ".", "time", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.block_timestamp
Returns the timestamp of the block with the given block number. :param int block_num: Block number
graphenecommon/blockchain.py
def block_timestamp(self, block_num): """ Returns the timestamp of the block with the given block number. :param int block_num: Block number """ return int( self.block_class(block_num, blockchain_instance=self.blockchain) .time() .timestamp() )
def block_timestamp(self, block_num): """ Returns the timestamp of the block with the given block number. :param int block_num: Block number """ return int( self.block_class(block_num, blockchain_instance=self.blockchain) .time() .timestamp() )
[ "Returns", "the", "timestamp", "of", "the", "block", "with", "the", "given", "block", "number", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L113-L123
[ "def", "block_timestamp", "(", "self", ",", "block_num", ")", ":", "return", "int", "(", "self", ".", "block_class", "(", "block_num", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", ".", "time", "(", ")", ".", "timestamp", "(", ")", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.blocks
Yields blocks starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "head" (the last block) and "irreversible" (the block that is confirmed by 2/3 of all block producers and is thus irreversible)
graphenecommon/blockchain.py
def blocks(self, start=None, stop=None): """ Yields blocks starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "head" (the last block) and "irreversible" (the block that is confirmed by 2/3 of all block producers and is thus irreversible) """ # Let's find out how often blocks are generated! self.block_interval = self.get_block_interval() if not start: start = self.get_current_block_num() # We are going to loop indefinitely while True: # Get chain properies to identify the if stop: head_block = stop else: head_block = self.get_current_block_num() # Blocks from start until head block for blocknum in range(start, head_block + 1): # Get full block block = self.wait_for_and_get_block(blocknum) block.update({"block_num": blocknum}) yield block # Set new start start = head_block + 1 if stop and start > stop: # raise StopIteration return # Sleep for one block time.sleep(self.block_interval)
def blocks(self, start=None, stop=None): """ Yields blocks starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "head" (the last block) and "irreversible" (the block that is confirmed by 2/3 of all block producers and is thus irreversible) """ # Let's find out how often blocks are generated! self.block_interval = self.get_block_interval() if not start: start = self.get_current_block_num() # We are going to loop indefinitely while True: # Get chain properies to identify the if stop: head_block = stop else: head_block = self.get_current_block_num() # Blocks from start until head block for blocknum in range(start, head_block + 1): # Get full block block = self.wait_for_and_get_block(blocknum) block.update({"block_num": blocknum}) yield block # Set new start start = head_block + 1 if stop and start > stop: # raise StopIteration return # Sleep for one block time.sleep(self.block_interval)
[ "Yields", "blocks", "starting", "from", "start", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L125-L163
[ "def", "blocks", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ")", ":", "# Let's find out how often blocks are generated!", "self", ".", "block_interval", "=", "self", ".", "get_block_interval", "(", ")", "if", "not", "start", ":", "start", "=", "self", ".", "get_current_block_num", "(", ")", "# We are going to loop indefinitely", "while", "True", ":", "# Get chain properies to identify the", "if", "stop", ":", "head_block", "=", "stop", "else", ":", "head_block", "=", "self", ".", "get_current_block_num", "(", ")", "# Blocks from start until head block", "for", "blocknum", "in", "range", "(", "start", ",", "head_block", "+", "1", ")", ":", "# Get full block", "block", "=", "self", ".", "wait_for_and_get_block", "(", "blocknum", ")", "block", ".", "update", "(", "{", "\"block_num\"", ":", "blocknum", "}", ")", "yield", "block", "# Set new start", "start", "=", "head_block", "+", "1", "if", "stop", "and", "start", ">", "stop", ":", "# raise StopIteration", "return", "# Sleep for one block", "time", ".", "sleep", "(", "self", ".", "block_interval", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.wait_for_and_get_block
Get the desired block from the chain, if the current head block is smaller (for both head and irreversible) then we wait, but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before failure. :param int block_number: desired block number :param int blocks_waiting_for: (default) difference between block_number and current head how many blocks we are willing to wait, positive int
graphenecommon/blockchain.py
def wait_for_and_get_block(self, block_number, blocks_waiting_for=None): """ Get the desired block from the chain, if the current head block is smaller (for both head and irreversible) then we wait, but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before failure. :param int block_number: desired block number :param int blocks_waiting_for: (default) difference between block_number and current head how many blocks we are willing to wait, positive int """ if not blocks_waiting_for: blocks_waiting_for = max(1, block_number - self.get_current_block_num()) repetition = 0 # can't return the block before the chain has reached it (support # future block_num) while self.get_current_block_num() < block_number: repetition += 1 time.sleep(self.block_interval) if repetition > blocks_waiting_for * self.max_block_wait_repetition: raise Exception("Wait time for new block exceeded, aborting") # block has to be returned properly block = self.blockchain.rpc.get_block(block_number) repetition = 0 while not block: repetition += 1 time.sleep(self.block_interval) if repetition > self.max_block_wait_repetition: raise Exception("Wait time for new block exceeded, aborting") block = self.blockchain.rpc.get_block(block_number) return block
def wait_for_and_get_block(self, block_number, blocks_waiting_for=None): """ Get the desired block from the chain, if the current head block is smaller (for both head and irreversible) then we wait, but a maxmimum of blocks_waiting_for * max_block_wait_repetition time before failure. :param int block_number: desired block number :param int blocks_waiting_for: (default) difference between block_number and current head how many blocks we are willing to wait, positive int """ if not blocks_waiting_for: blocks_waiting_for = max(1, block_number - self.get_current_block_num()) repetition = 0 # can't return the block before the chain has reached it (support # future block_num) while self.get_current_block_num() < block_number: repetition += 1 time.sleep(self.block_interval) if repetition > blocks_waiting_for * self.max_block_wait_repetition: raise Exception("Wait time for new block exceeded, aborting") # block has to be returned properly block = self.blockchain.rpc.get_block(block_number) repetition = 0 while not block: repetition += 1 time.sleep(self.block_interval) if repetition > self.max_block_wait_repetition: raise Exception("Wait time for new block exceeded, aborting") block = self.blockchain.rpc.get_block(block_number) return block
[ "Get", "the", "desired", "block", "from", "the", "chain", "if", "the", "current", "head", "block", "is", "smaller", "(", "for", "both", "head", "and", "irreversible", ")", "then", "we", "wait", "but", "a", "maxmimum", "of", "blocks_waiting_for", "*", "max_block_wait_repetition", "time", "before", "failure", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L165-L196
[ "def", "wait_for_and_get_block", "(", "self", ",", "block_number", ",", "blocks_waiting_for", "=", "None", ")", ":", "if", "not", "blocks_waiting_for", ":", "blocks_waiting_for", "=", "max", "(", "1", ",", "block_number", "-", "self", ".", "get_current_block_num", "(", ")", ")", "repetition", "=", "0", "# can't return the block before the chain has reached it (support", "# future block_num)", "while", "self", ".", "get_current_block_num", "(", ")", "<", "block_number", ":", "repetition", "+=", "1", "time", ".", "sleep", "(", "self", ".", "block_interval", ")", "if", "repetition", ">", "blocks_waiting_for", "*", "self", ".", "max_block_wait_repetition", ":", "raise", "Exception", "(", "\"Wait time for new block exceeded, aborting\"", ")", "# block has to be returned properly", "block", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_block", "(", "block_number", ")", "repetition", "=", "0", "while", "not", "block", ":", "repetition", "+=", "1", "time", ".", "sleep", "(", "self", ".", "block_interval", ")", "if", "repetition", ">", "self", ".", "max_block_wait_repetition", ":", "raise", "Exception", "(", "\"Wait time for new block exceeded, aborting\"", ")", "block", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_block", "(", "block_number", ")", "return", "block" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.ops
Yields all operations (excluding virtual operations) starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "head" (the last block) and "irreversible" (the block that is confirmed by 2/3 of all block producers and is thus irreversible) :param bool only_virtual_ops: Only yield virtual operations This call returns a list that only carries one operation and its type!
graphenecommon/blockchain.py
def ops(self, start=None, stop=None, **kwargs): """ Yields all operations (excluding virtual operations) starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "head" (the last block) and "irreversible" (the block that is confirmed by 2/3 of all block producers and is thus irreversible) :param bool only_virtual_ops: Only yield virtual operations This call returns a list that only carries one operation and its type! """ for block in self.blocks(start=start, stop=stop, **kwargs): for tx in block["transactions"]: for op in tx["operations"]: # Replace opid by op name op[0] = self.operationids.getOperationName(op[0]) yield { "block_num": block["block_num"], "op": op, "timestamp": block["timestamp"], }
def ops(self, start=None, stop=None, **kwargs): """ Yields all operations (excluding virtual operations) starting from ``start``. :param int start: Starting block :param int stop: Stop at this block :param str mode: We here have the choice between "head" (the last block) and "irreversible" (the block that is confirmed by 2/3 of all block producers and is thus irreversible) :param bool only_virtual_ops: Only yield virtual operations This call returns a list that only carries one operation and its type! """ for block in self.blocks(start=start, stop=stop, **kwargs): for tx in block["transactions"]: for op in tx["operations"]: # Replace opid by op name op[0] = self.operationids.getOperationName(op[0]) yield { "block_num": block["block_num"], "op": op, "timestamp": block["timestamp"], }
[ "Yields", "all", "operations", "(", "excluding", "virtual", "operations", ")", "starting", "from", "start", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L198-L222
[ "def", "ops", "(", "self", ",", "start", "=", "None", ",", "stop", "=", "None", ",", "*", "*", "kwargs", ")", ":", "for", "block", "in", "self", ".", "blocks", "(", "start", "=", "start", ",", "stop", "=", "stop", ",", "*", "*", "kwargs", ")", ":", "for", "tx", "in", "block", "[", "\"transactions\"", "]", ":", "for", "op", "in", "tx", "[", "\"operations\"", "]", ":", "# Replace opid by op name", "op", "[", "0", "]", "=", "self", ".", "operationids", ".", "getOperationName", "(", "op", "[", "0", "]", ")", "yield", "{", "\"block_num\"", ":", "block", "[", "\"block_num\"", "]", ",", "\"op\"", ":", "op", ",", "\"timestamp\"", ":", "block", "[", "\"timestamp\"", "]", ",", "}" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.stream
Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the choice between * "head": the last block * "irreversible": the block that is confirmed by 2/3 of all block producers and is thus irreversible! The dict output is formated such that ``type`` caries the operation type, timestamp and block_num are taken from the block the operation was stored in and the other key depend on the actualy operation.
graphenecommon/blockchain.py
def stream(self, opNames=[], *args, **kwargs): """ Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the choice between * "head": the last block * "irreversible": the block that is confirmed by 2/3 of all block producers and is thus irreversible! The dict output is formated such that ``type`` caries the operation type, timestamp and block_num are taken from the block the operation was stored in and the other key depend on the actualy operation. """ for op in self.ops(**kwargs): if not opNames or op["op"][0] in opNames: r = { "type": op["op"][0], "timestamp": op.get("timestamp"), "block_num": op.get("block_num"), } r.update(op["op"][1]) yield r
def stream(self, opNames=[], *args, **kwargs): """ Yield specific operations (e.g. comments) only :param array opNames: List of operations to filter for :param int start: Start at this block :param int stop: Stop at this block :param str mode: We here have the choice between * "head": the last block * "irreversible": the block that is confirmed by 2/3 of all block producers and is thus irreversible! The dict output is formated such that ``type`` caries the operation type, timestamp and block_num are taken from the block the operation was stored in and the other key depend on the actualy operation. """ for op in self.ops(**kwargs): if not opNames or op["op"][0] in opNames: r = { "type": op["op"][0], "timestamp": op.get("timestamp"), "block_num": op.get("block_num"), } r.update(op["op"][1]) yield r
[ "Yield", "specific", "operations", "(", "e", ".", "g", ".", "comments", ")", "only" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L224-L248
[ "def", "stream", "(", "self", ",", "opNames", "=", "[", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "op", "in", "self", ".", "ops", "(", "*", "*", "kwargs", ")", ":", "if", "not", "opNames", "or", "op", "[", "\"op\"", "]", "[", "0", "]", "in", "opNames", ":", "r", "=", "{", "\"type\"", ":", "op", "[", "\"op\"", "]", "[", "0", "]", ",", "\"timestamp\"", ":", "op", ".", "get", "(", "\"timestamp\"", ")", ",", "\"block_num\"", ":", "op", ".", "get", "(", "\"block_num\"", ")", ",", "}", "r", ".", "update", "(", "op", "[", "\"op\"", "]", "[", "1", "]", ")", "yield", "r" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.awaitTxConfirmation
Returns the transaction as seen by the blockchain after being included into a block .. note:: If you want instant confirmation, you need to instantiate class:`.blockchain.Blockchain` with ``mode="head"``, otherwise, the call will wait until confirmed in an irreversible block. .. note:: This method returns once the blockchain has included a transaction with the **same signature**. Even though the signature is not usually used to identify a transaction, it still cannot be forfeited and is derived from the transaction contented and thus identifies a transaction uniquely.
graphenecommon/blockchain.py
def awaitTxConfirmation(self, transaction, limit=10): """ Returns the transaction as seen by the blockchain after being included into a block .. note:: If you want instant confirmation, you need to instantiate class:`.blockchain.Blockchain` with ``mode="head"``, otherwise, the call will wait until confirmed in an irreversible block. .. note:: This method returns once the blockchain has included a transaction with the **same signature**. Even though the signature is not usually used to identify a transaction, it still cannot be forfeited and is derived from the transaction contented and thus identifies a transaction uniquely. """ counter = 10 for block in self.blocks(): counter += 1 for tx in block["transactions"]: if sorted(tx["signatures"]) == sorted(transaction["signatures"]): return tx if counter > limit: raise Exception("The operation has not been added after 10 blocks!")
def awaitTxConfirmation(self, transaction, limit=10): """ Returns the transaction as seen by the blockchain after being included into a block .. note:: If you want instant confirmation, you need to instantiate class:`.blockchain.Blockchain` with ``mode="head"``, otherwise, the call will wait until confirmed in an irreversible block. .. note:: This method returns once the blockchain has included a transaction with the **same signature**. Even though the signature is not usually used to identify a transaction, it still cannot be forfeited and is derived from the transaction contented and thus identifies a transaction uniquely. """ counter = 10 for block in self.blocks(): counter += 1 for tx in block["transactions"]: if sorted(tx["signatures"]) == sorted(transaction["signatures"]): return tx if counter > limit: raise Exception("The operation has not been added after 10 blocks!")
[ "Returns", "the", "transaction", "as", "seen", "by", "the", "blockchain", "after", "being", "included", "into", "a", "block" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L250-L273
[ "def", "awaitTxConfirmation", "(", "self", ",", "transaction", ",", "limit", "=", "10", ")", ":", "counter", "=", "10", "for", "block", "in", "self", ".", "blocks", "(", ")", ":", "counter", "+=", "1", "for", "tx", "in", "block", "[", "\"transactions\"", "]", ":", "if", "sorted", "(", "tx", "[", "\"signatures\"", "]", ")", "==", "sorted", "(", "transaction", "[", "\"signatures\"", "]", ")", ":", "return", "tx", "if", "counter", ">", "limit", ":", "raise", "Exception", "(", "\"The operation has not been added after 10 blocks!\"", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Blockchain.get_all_accounts
Yields account names between start and stop. :param str start: Start at this account name :param str stop: Stop at this account name :param int steps: Obtain ``steps`` ret with a single call from RPC
graphenecommon/blockchain.py
def get_all_accounts(self, start="", stop="", steps=1e3, **kwargs): """ Yields account names between start and stop. :param str start: Start at this account name :param str stop: Stop at this account name :param int steps: Obtain ``steps`` ret with a single call from RPC """ lastname = start while True: ret = self.blockchain.rpc.lookup_accounts(lastname, steps) for account in ret: yield account[0] if account[0] == stop: raise StopIteration if lastname == ret[-1][0]: raise StopIteration lastname = ret[-1][0] if len(ret) < steps: raise StopIteration
def get_all_accounts(self, start="", stop="", steps=1e3, **kwargs): """ Yields account names between start and stop. :param str start: Start at this account name :param str stop: Stop at this account name :param int steps: Obtain ``steps`` ret with a single call from RPC """ lastname = start while True: ret = self.blockchain.rpc.lookup_accounts(lastname, steps) for account in ret: yield account[0] if account[0] == stop: raise StopIteration if lastname == ret[-1][0]: raise StopIteration lastname = ret[-1][0] if len(ret) < steps: raise StopIteration
[ "Yields", "account", "names", "between", "start", "and", "stop", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/blockchain.py#L275-L293
[ "def", "get_all_accounts", "(", "self", ",", "start", "=", "\"\"", ",", "stop", "=", "\"\"", ",", "steps", "=", "1e3", ",", "*", "*", "kwargs", ")", ":", "lastname", "=", "start", "while", "True", ":", "ret", "=", "self", ".", "blockchain", ".", "rpc", ".", "lookup_accounts", "(", "lastname", ",", "steps", ")", "for", "account", "in", "ret", ":", "yield", "account", "[", "0", "]", "if", "account", "[", "0", "]", "==", "stop", ":", "raise", "StopIteration", "if", "lastname", "==", "ret", "[", "-", "1", "]", "[", "0", "]", ":", "raise", "StopIteration", "lastname", "=", "ret", "[", "-", "1", "]", "[", "0", "]", "if", "len", "(", "ret", ")", "<", "steps", ":", "raise", "StopIteration" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Asset.refresh
Refresh the data from the API server
graphenecommon/asset.py
def refresh(self): """ Refresh the data from the API server """ asset = self.blockchain.rpc.get_asset(self.identifier) if not asset: raise AssetDoesNotExistsException(self.identifier) super(Asset, self).__init__(asset, blockchain_instance=self.blockchain) if self.full: if "bitasset_data_id" in asset: self["bitasset_data"] = self.blockchain.rpc.get_object( asset["bitasset_data_id"] ) self["dynamic_asset_data"] = self.blockchain.rpc.get_object( asset["dynamic_asset_data_id"] )
def refresh(self): """ Refresh the data from the API server """ asset = self.blockchain.rpc.get_asset(self.identifier) if not asset: raise AssetDoesNotExistsException(self.identifier) super(Asset, self).__init__(asset, blockchain_instance=self.blockchain) if self.full: if "bitasset_data_id" in asset: self["bitasset_data"] = self.blockchain.rpc.get_object( asset["bitasset_data_id"] ) self["dynamic_asset_data"] = self.blockchain.rpc.get_object( asset["dynamic_asset_data_id"] )
[ "Refresh", "the", "data", "from", "the", "API", "server" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/asset.py#L29-L43
[ "def", "refresh", "(", "self", ")", ":", "asset", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_asset", "(", "self", ".", "identifier", ")", "if", "not", "asset", ":", "raise", "AssetDoesNotExistsException", "(", "self", ".", "identifier", ")", "super", "(", "Asset", ",", "self", ")", ".", "__init__", "(", "asset", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "if", "self", ".", "full", ":", "if", "\"bitasset_data_id\"", "in", "asset", ":", "self", "[", "\"bitasset_data\"", "]", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_object", "(", "asset", "[", "\"bitasset_data_id\"", "]", ")", "self", "[", "\"dynamic_asset_data\"", "]", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_object", "(", "asset", "[", "\"dynamic_asset_data_id\"", "]", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Asset.update_cer
Update the Core Exchange Rate (CER) of an asset
graphenecommon/asset.py
def update_cer(self, cer, account=None, **kwargs): """ Update the Core Exchange Rate (CER) of an asset """ assert callable(self.blockchain.update_cer) return self.blockchain.update_cer( self["symbol"], cer, account=account, **kwargs )
def update_cer(self, cer, account=None, **kwargs): """ Update the Core Exchange Rate (CER) of an asset """ assert callable(self.blockchain.update_cer) return self.blockchain.update_cer( self["symbol"], cer, account=account, **kwargs )
[ "Update", "the", "Core", "Exchange", "Rate", "(", "CER", ")", "of", "an", "asset" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/asset.py#L82-L88
[ "def", "update_cer", "(", "self", ",", "cer", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "callable", "(", "self", ".", "blockchain", ".", "update_cer", ")", "return", "self", ".", "blockchain", ".", "update_cer", "(", "self", "[", "\"symbol\"", "]", ",", "cer", ",", "account", "=", "account", ",", "*", "*", "kwargs", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
GrapheneAPI.rpcexec
Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises UnauthorizedError: if the user is not authorized raise ValueError: if the API returns a non-JSON formated answer It is not recommended to use this method directly, unless you know what you are doing. All calls available to the API will be wrapped to methods directly:: info -> grapheneapi.info()
grapheneapi/grapheneapi.py
def rpcexec(self, payload): """ Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises UnauthorizedError: if the user is not authorized raise ValueError: if the API returns a non-JSON formated answer It is not recommended to use this method directly, unless you know what you are doing. All calls available to the API will be wrapped to methods directly:: info -> grapheneapi.info() """ try: response = requests.post( "http://{}:{}/rpc".format(self.host, self.port), data=json.dumps(payload, ensure_ascii=False).encode("utf8"), headers=self.headers, auth=(self.username, self.password), ) if response.status_code == 401: raise UnauthorizedError ret = json.loads(response.text) if "error" in ret: if "detail" in ret["error"]: raise RPCError(ret["error"]["detail"]) else: raise RPCError(ret["error"]["message"]) except requests.exceptions.RequestException: raise RPCConnection("Error connecting to Client!") except UnauthorizedError: raise UnauthorizedError("Invalid login credentials!") except ValueError: raise ValueError("Client returned invalid format. Expected JSON!") except RPCError as err: raise err else: return ret["result"]
def rpcexec(self, payload): """ Manual execute a command on API (internally used) param str payload: The payload containing the request return: Servers answer to the query rtype: json raises RPCConnection: if no connction can be made raises UnauthorizedError: if the user is not authorized raise ValueError: if the API returns a non-JSON formated answer It is not recommended to use this method directly, unless you know what you are doing. All calls available to the API will be wrapped to methods directly:: info -> grapheneapi.info() """ try: response = requests.post( "http://{}:{}/rpc".format(self.host, self.port), data=json.dumps(payload, ensure_ascii=False).encode("utf8"), headers=self.headers, auth=(self.username, self.password), ) if response.status_code == 401: raise UnauthorizedError ret = json.loads(response.text) if "error" in ret: if "detail" in ret["error"]: raise RPCError(ret["error"]["detail"]) else: raise RPCError(ret["error"]["message"]) except requests.exceptions.RequestException: raise RPCConnection("Error connecting to Client!") except UnauthorizedError: raise UnauthorizedError("Invalid login credentials!") except ValueError: raise ValueError("Client returned invalid format. Expected JSON!") except RPCError as err: raise err else: return ret["result"]
[ "Manual", "execute", "a", "command", "on", "API", "(", "internally", "used", ")" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/grapheneapi/grapheneapi.py#L68-L108
[ "def", "rpcexec", "(", "self", ",", "payload", ")", ":", "try", ":", "response", "=", "requests", ".", "post", "(", "\"http://{}:{}/rpc\"", ".", "format", "(", "self", ".", "host", ",", "self", ".", "port", ")", ",", "data", "=", "json", ".", "dumps", "(", "payload", ",", "ensure_ascii", "=", "False", ")", ".", "encode", "(", "\"utf8\"", ")", ",", "headers", "=", "self", ".", "headers", ",", "auth", "=", "(", "self", ".", "username", ",", "self", ".", "password", ")", ",", ")", "if", "response", ".", "status_code", "==", "401", ":", "raise", "UnauthorizedError", "ret", "=", "json", ".", "loads", "(", "response", ".", "text", ")", "if", "\"error\"", "in", "ret", ":", "if", "\"detail\"", "in", "ret", "[", "\"error\"", "]", ":", "raise", "RPCError", "(", "ret", "[", "\"error\"", "]", "[", "\"detail\"", "]", ")", "else", ":", "raise", "RPCError", "(", "ret", "[", "\"error\"", "]", "[", "\"message\"", "]", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "raise", "RPCConnection", "(", "\"Error connecting to Client!\"", ")", "except", "UnauthorizedError", ":", "raise", "UnauthorizedError", "(", "\"Invalid login credentials!\"", ")", "except", "ValueError", ":", "raise", "ValueError", "(", "\"Client returned invalid format. Expected JSON!\"", ")", "except", "RPCError", "as", "err", ":", "raise", "err", "else", ":", "return", "ret", "[", "\"result\"", "]" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
formatTime
Properly Format Time for permlinks
graphenecommon/utils.py
def formatTime(t): """ Properly Format Time for permlinks """ if isinstance(t, float): return datetime.utcfromtimestamp(t).strftime(timeFormat) if isinstance(t, datetime): return t.strftime(timeFormat)
def formatTime(t): """ Properly Format Time for permlinks """ if isinstance(t, float): return datetime.utcfromtimestamp(t).strftime(timeFormat) if isinstance(t, datetime): return t.strftime(timeFormat)
[ "Properly", "Format", "Time", "for", "permlinks" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/utils.py#L9-L15
[ "def", "formatTime", "(", "t", ")", ":", "if", "isinstance", "(", "t", ",", "float", ")", ":", "return", "datetime", ".", "utcfromtimestamp", "(", "t", ")", ".", "strftime", "(", "timeFormat", ")", "if", "isinstance", "(", "t", ",", "datetime", ")", ":", "return", "t", ".", "strftime", "(", "timeFormat", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
formatTimeFromNow
Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str
graphenecommon/utils.py
def formatTimeFromNow(secs=None): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs or 0)).strftime(timeFormat)
def formatTimeFromNow(secs=None): """ Properly Format Time that is `x` seconds in the future :param int secs: Seconds to go in the future (`x>0`) or the past (`x<0`) :return: Properly formated time for Graphene (`%Y-%m-%dT%H:%M:%S`) :rtype: str """ return datetime.utcfromtimestamp(time.time() + int(secs or 0)).strftime(timeFormat)
[ "Properly", "Format", "Time", "that", "is", "x", "seconds", "in", "the", "future" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/utils.py#L24-L33
[ "def", "formatTimeFromNow", "(", "secs", "=", "None", ")", ":", "return", "datetime", ".", "utcfromtimestamp", "(", "time", ".", "time", "(", ")", "+", "int", "(", "secs", "or", "0", ")", ")", ".", "strftime", "(", "timeFormat", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
parse_time
Take a string representation of time from the blockchain, and parse it into datetime object.
graphenecommon/utils.py
def parse_time(block_time): """Take a string representation of time from the blockchain, and parse it into datetime object. """ return datetime.strptime(block_time, timeFormat).replace(tzinfo=timezone.utc)
def parse_time(block_time): """Take a string representation of time from the blockchain, and parse it into datetime object. """ return datetime.strptime(block_time, timeFormat).replace(tzinfo=timezone.utc)
[ "Take", "a", "string", "representation", "of", "time", "from", "the", "blockchain", "and", "parse", "it", "into", "datetime", "object", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/utils.py#L36-L40
[ "def", "parse_time", "(", "block_time", ")", ":", "return", "datetime", ".", "strptime", "(", "block_time", ",", "timeFormat", ")", ".", "replace", "(", "tzinfo", "=", "timezone", ".", "utc", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
getOperationNameForId
Convert an operation id into the corresponding string
graphenebase/operationids.py
def getOperationNameForId(i: int): """ Convert an operation id into the corresponding string """ assert isinstance(i, (int)), "This method expects an integer argument" for key in operations: if int(operations[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" % i)
def getOperationNameForId(i: int): """ Convert an operation id into the corresponding string """ assert isinstance(i, (int)), "This method expects an integer argument" for key in operations: if int(operations[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" % i)
[ "Convert", "an", "operation", "id", "into", "the", "corresponding", "string" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/operationids.py#L14-L21
[ "def", "getOperationNameForId", "(", "i", ":", "int", ")", ":", "assert", "isinstance", "(", "i", ",", "(", "int", ")", ")", ",", "\"This method expects an integer argument\"", "for", "key", "in", "operations", ":", "if", "int", "(", "operations", "[", "key", "]", ")", "is", "int", "(", "i", ")", ":", "return", "key", "raise", "ValueError", "(", "\"Unknown Operation ID %d\"", "%", "i", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword.unlocked
Is the store unlocked so that I can decrypt the content?
graphenestorage/masterpassword.py
def unlocked(self): """ Is the store unlocked so that I can decrypt the content? """ if self.password is not None: return bool(self.password) else: if ( "UNLOCK" in os.environ and os.environ["UNLOCK"] and self.config_key in self.config and self.config[self.config_key] ): log.debug("Trying to use environmental " "variable to unlock wallet") self.unlock(os.environ.get("UNLOCK")) return bool(self.password) return False
def unlocked(self): """ Is the store unlocked so that I can decrypt the content? """ if self.password is not None: return bool(self.password) else: if ( "UNLOCK" in os.environ and os.environ["UNLOCK"] and self.config_key in self.config and self.config[self.config_key] ): log.debug("Trying to use environmental " "variable to unlock wallet") self.unlock(os.environ.get("UNLOCK")) return bool(self.password) return False
[ "Is", "the", "store", "unlocked", "so", "that", "I", "can", "decrypt", "the", "content?" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L55-L70
[ "def", "unlocked", "(", "self", ")", ":", "if", "self", ".", "password", "is", "not", "None", ":", "return", "bool", "(", "self", ".", "password", ")", "else", ":", "if", "(", "\"UNLOCK\"", "in", "os", ".", "environ", "and", "os", ".", "environ", "[", "\"UNLOCK\"", "]", "and", "self", ".", "config_key", "in", "self", ".", "config", "and", "self", ".", "config", "[", "self", ".", "config_key", "]", ")", ":", "log", ".", "debug", "(", "\"Trying to use environmental \"", "\"variable to unlock wallet\"", ")", "self", ".", "unlock", "(", "os", ".", "environ", ".", "get", "(", "\"UNLOCK\"", ")", ")", "return", "bool", "(", "self", ".", "password", ")", "return", "False" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword.unlock
The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database, one must use BIP38, decrypt the masterpassword from the configuration store with the user password, and use the decrypted masterpassword to decrypt the BIP38 encrypted private keys from the keys storage! :param str password: Password to use for en-/de-cryption
graphenestorage/masterpassword.py
def unlock(self, password): """ The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database, one must use BIP38, decrypt the masterpassword from the configuration store with the user password, and use the decrypted masterpassword to decrypt the BIP38 encrypted private keys from the keys storage! :param str password: Password to use for en-/de-cryption """ self.password = password if self.config_key in self.config and self.config[self.config_key]: self._decrypt_masterpassword() else: self._new_masterpassword(password) self._save_encrypted_masterpassword()
def unlock(self, password): """ The password is used to encrypt this masterpassword. To decrypt the keys stored in the keys database, one must use BIP38, decrypt the masterpassword from the configuration store with the user password, and use the decrypted masterpassword to decrypt the BIP38 encrypted private keys from the keys storage! :param str password: Password to use for en-/de-cryption """ self.password = password if self.config_key in self.config and self.config[self.config_key]: self._decrypt_masterpassword() else: self._new_masterpassword(password) self._save_encrypted_masterpassword()
[ "The", "password", "is", "used", "to", "encrypt", "this", "masterpassword", ".", "To", "decrypt", "the", "keys", "stored", "in", "the", "keys", "database", "one", "must", "use", "BIP38", "decrypt", "the", "masterpassword", "from", "the", "configuration", "store", "with", "the", "user", "password", "and", "use", "the", "decrypted", "masterpassword", "to", "decrypt", "the", "BIP38", "encrypted", "private", "keys", "from", "the", "keys", "storage!" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L79-L94
[ "def", "unlock", "(", "self", ",", "password", ")", ":", "self", ".", "password", "=", "password", "if", "self", ".", "config_key", "in", "self", ".", "config", "and", "self", ".", "config", "[", "self", ".", "config_key", "]", ":", "self", ".", "_decrypt_masterpassword", "(", ")", "else", ":", "self", ".", "_new_masterpassword", "(", "password", ")", "self", ".", "_save_encrypted_masterpassword", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword._decrypt_masterpassword
Decrypt the encrypted masterkey
graphenestorage/masterpassword.py
def _decrypt_masterpassword(self): """ Decrypt the encrypted masterkey """ aes = AESCipher(self.password) checksum, encrypted_master = self.config[self.config_key].split("$") try: decrypted_master = aes.decrypt(encrypted_master) except Exception: self._raise_wrongmasterpassexception() if checksum != self._derive_checksum(decrypted_master): self._raise_wrongmasterpassexception() self.decrypted_master = decrypted_master
def _decrypt_masterpassword(self): """ Decrypt the encrypted masterkey """ aes = AESCipher(self.password) checksum, encrypted_master = self.config[self.config_key].split("$") try: decrypted_master = aes.decrypt(encrypted_master) except Exception: self._raise_wrongmasterpassexception() if checksum != self._derive_checksum(decrypted_master): self._raise_wrongmasterpassexception() self.decrypted_master = decrypted_master
[ "Decrypt", "the", "encrypted", "masterkey" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L96-L107
[ "def", "_decrypt_masterpassword", "(", "self", ")", ":", "aes", "=", "AESCipher", "(", "self", ".", "password", ")", "checksum", ",", "encrypted_master", "=", "self", ".", "config", "[", "self", ".", "config_key", "]", ".", "split", "(", "\"$\"", ")", "try", ":", "decrypted_master", "=", "aes", ".", "decrypt", "(", "encrypted_master", ")", "except", "Exception", ":", "self", ".", "_raise_wrongmasterpassexception", "(", ")", "if", "checksum", "!=", "self", ".", "_derive_checksum", "(", "decrypted_master", ")", ":", "self", ".", "_raise_wrongmasterpassexception", "(", ")", "self", ".", "decrypted_master", "=", "decrypted_master" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword._new_masterpassword
Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption
graphenestorage/masterpassword.py
def _new_masterpassword(self, password): """ Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption """ # make sure to not overwrite an existing key if self.config_key in self.config and self.config[self.config_key]: raise Exception("Storage already has a masterpassword!") self.decrypted_master = hexlify(os.urandom(32)).decode("ascii") # Encrypt and save master self.password = password self._save_encrypted_masterpassword() return self.masterkey
def _new_masterpassword(self, password): """ Generate a new random masterkey, encrypt it with the password and store it in the store. :param str password: Password to use for en-/de-cryption """ # make sure to not overwrite an existing key if self.config_key in self.config and self.config[self.config_key]: raise Exception("Storage already has a masterpassword!") self.decrypted_master = hexlify(os.urandom(32)).decode("ascii") # Encrypt and save master self.password = password self._save_encrypted_masterpassword() return self.masterkey
[ "Generate", "a", "new", "random", "masterkey", "encrypt", "it", "with", "the", "password", "and", "store", "it", "in", "the", "store", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L116-L131
[ "def", "_new_masterpassword", "(", "self", ",", "password", ")", ":", "# make sure to not overwrite an existing key", "if", "self", ".", "config_key", "in", "self", ".", "config", "and", "self", ".", "config", "[", "self", ".", "config_key", "]", ":", "raise", "Exception", "(", "\"Storage already has a masterpassword!\"", ")", "self", ".", "decrypted_master", "=", "hexlify", "(", "os", ".", "urandom", "(", "32", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "# Encrypt and save master", "self", ".", "password", "=", "password", "self", ".", "_save_encrypted_masterpassword", "(", ")", "return", "self", ".", "masterkey" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword._derive_checksum
Derive the checksum :param str s: Random string for which to derive the checksum
graphenestorage/masterpassword.py
def _derive_checksum(self, s): """ Derive the checksum :param str s: Random string for which to derive the checksum """ checksum = hashlib.sha256(bytes(s, "ascii")).hexdigest() return checksum[:4]
def _derive_checksum(self, s): """ Derive the checksum :param str s: Random string for which to derive the checksum """ checksum = hashlib.sha256(bytes(s, "ascii")).hexdigest() return checksum[:4]
[ "Derive", "the", "checksum" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L133-L139
[ "def", "_derive_checksum", "(", "self", ",", "s", ")", ":", "checksum", "=", "hashlib", ".", "sha256", "(", "bytes", "(", "s", ",", "\"ascii\"", ")", ")", ".", "hexdigest", "(", ")", "return", "checksum", "[", ":", "4", "]" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword._get_encrypted_masterpassword
Obtain the encrypted masterkey .. note:: The encrypted masterkey is checksummed, so that we can figure out that a provided password is correct or not. The checksum is only 4 bytes long!
graphenestorage/masterpassword.py
def _get_encrypted_masterpassword(self): """ Obtain the encrypted masterkey .. note:: The encrypted masterkey is checksummed, so that we can figure out that a provided password is correct or not. The checksum is only 4 bytes long! """ if not self.unlocked(): raise WalletLocked aes = AESCipher(self.password) return "{}${}".format( self._derive_checksum(self.masterkey), aes.encrypt(self.masterkey) )
def _get_encrypted_masterpassword(self): """ Obtain the encrypted masterkey .. note:: The encrypted masterkey is checksummed, so that we can figure out that a provided password is correct or not. The checksum is only 4 bytes long! """ if not self.unlocked(): raise WalletLocked aes = AESCipher(self.password) return "{}${}".format( self._derive_checksum(self.masterkey), aes.encrypt(self.masterkey) )
[ "Obtain", "the", "encrypted", "masterkey" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L141-L153
[ "def", "_get_encrypted_masterpassword", "(", "self", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "aes", "=", "AESCipher", "(", "self", ".", "password", ")", "return", "\"{}${}\"", ".", "format", "(", "self", ".", "_derive_checksum", "(", "self", ".", "masterkey", ")", ",", "aes", ".", "encrypt", "(", "self", ".", "masterkey", ")", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword.change_password
Change the password that allows to decrypt the master key
graphenestorage/masterpassword.py
def change_password(self, newpassword): """ Change the password that allows to decrypt the master key """ if not self.unlocked(): raise WalletLocked self.password = newpassword self._save_encrypted_masterpassword()
def change_password(self, newpassword): """ Change the password that allows to decrypt the master key """ if not self.unlocked(): raise WalletLocked self.password = newpassword self._save_encrypted_masterpassword()
[ "Change", "the", "password", "that", "allows", "to", "decrypt", "the", "master", "key" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L155-L161
[ "def", "change_password", "(", "self", ",", "newpassword", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "self", ".", "password", "=", "newpassword", "self", ".", "_save_encrypted_masterpassword", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword.decrypt
Decrypt the content according to BIP38 :param str wif: Encrypted key
graphenestorage/masterpassword.py
def decrypt(self, wif): """ Decrypt the content according to BIP38 :param str wif: Encrypted key """ if not self.unlocked(): raise WalletLocked return format(bip38.decrypt(wif, self.masterkey), "wif")
def decrypt(self, wif): """ Decrypt the content according to BIP38 :param str wif: Encrypted key """ if not self.unlocked(): raise WalletLocked return format(bip38.decrypt(wif, self.masterkey), "wif")
[ "Decrypt", "the", "content", "according", "to", "BIP38" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L163-L170
[ "def", "decrypt", "(", "self", ",", "wif", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "return", "format", "(", "bip38", ".", "decrypt", "(", "wif", ",", "self", ".", "masterkey", ")", ",", "\"wif\"", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
MasterPassword.encrypt
Encrypt the content according to BIP38 :param str wif: Unencrypted key
graphenestorage/masterpassword.py
def encrypt(self, wif): """ Encrypt the content according to BIP38 :param str wif: Unencrypted key """ if not self.unlocked(): raise WalletLocked return format(bip38.encrypt(str(wif), self.masterkey), "encwif")
def encrypt(self, wif): """ Encrypt the content according to BIP38 :param str wif: Unencrypted key """ if not self.unlocked(): raise WalletLocked return format(bip38.encrypt(str(wif), self.masterkey), "encwif")
[ "Encrypt", "the", "content", "according", "to", "BIP38" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/masterpassword.py#L172-L179
[ "def", "encrypt", "(", "self", ",", "wif", ")", ":", "if", "not", "self", ".", "unlocked", "(", ")", ":", "raise", "WalletLocked", "return", "format", "(", "bip38", ".", "encrypt", "(", "str", "(", "wif", ")", ",", "self", ".", "masterkey", ")", ",", "\"encwif\"", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
BrainKey.get_private
Derive private key from the brain key and the current sequence number
graphenebase/account.py
def get_private(self): """ Derive private key from the brain key and the current sequence number """ encoded = "%s %d" % (self.brainkey, self.sequence) a = _bytes(encoded) s = hashlib.sha256(hashlib.sha512(a).digest()).digest() return PrivateKey(hexlify(s).decode("ascii"), prefix=self.prefix)
def get_private(self): """ Derive private key from the brain key and the current sequence number """ encoded = "%s %d" % (self.brainkey, self.sequence) a = _bytes(encoded) s = hashlib.sha256(hashlib.sha512(a).digest()).digest() return PrivateKey(hexlify(s).decode("ascii"), prefix=self.prefix)
[ "Derive", "private", "key", "from", "the", "brain", "key", "and", "the", "current", "sequence", "number" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L97-L104
[ "def", "get_private", "(", "self", ")", ":", "encoded", "=", "\"%s %d\"", "%", "(", "self", ".", "brainkey", ",", "self", ".", "sequence", ")", "a", "=", "_bytes", "(", "encoded", ")", "s", "=", "hashlib", ".", "sha256", "(", "hashlib", ".", "sha512", "(", "a", ")", ".", "digest", "(", ")", ")", ".", "digest", "(", ")", "return", "PrivateKey", "(", "hexlify", "(", "s", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "prefix", "=", "self", ".", "prefix", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
BrainKey.get_blind_private
Derive private key from the brain key (and no sequence number)
graphenebase/account.py
def get_blind_private(self): """ Derive private key from the brain key (and no sequence number) """ a = _bytes(self.brainkey) return PrivateKey(hashlib.sha256(a).hexdigest(), prefix=self.prefix)
def get_blind_private(self): """ Derive private key from the brain key (and no sequence number) """ a = _bytes(self.brainkey) return PrivateKey(hashlib.sha256(a).hexdigest(), prefix=self.prefix)
[ "Derive", "private", "key", "from", "the", "brain", "key", "(", "and", "no", "sequence", "number", ")" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L106-L110
[ "def", "get_blind_private", "(", "self", ")", ":", "a", "=", "_bytes", "(", "self", ".", "brainkey", ")", "return", "PrivateKey", "(", "hashlib", ".", "sha256", "(", "a", ")", ".", "hexdigest", "(", ")", ",", "prefix", "=", "self", ".", "prefix", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
BrainKey.suggest
Suggest a new random brain key. Randomness is provided by the operating system using ``os.urandom()``.
graphenebase/account.py
def suggest(): """ Suggest a new random brain key. Randomness is provided by the operating system using ``os.urandom()``. """ word_count = 16 brainkey = [None] * word_count dict_lines = BrainKeyDictionary.split(",") assert len(dict_lines) == 49744 for j in range(0, word_count): num = int.from_bytes(os.urandom(2), byteorder="little") rndMult = num / 2 ** 16 # returns float between 0..1 (inclusive) wIdx = round(len(dict_lines) * rndMult) brainkey[j] = dict_lines[wIdx] return " ".join(brainkey).upper()
def suggest(): """ Suggest a new random brain key. Randomness is provided by the operating system using ``os.urandom()``. """ word_count = 16 brainkey = [None] * word_count dict_lines = BrainKeyDictionary.split(",") assert len(dict_lines) == 49744 for j in range(0, word_count): num = int.from_bytes(os.urandom(2), byteorder="little") rndMult = num / 2 ** 16 # returns float between 0..1 (inclusive) wIdx = round(len(dict_lines) * rndMult) brainkey[j] = dict_lines[wIdx] return " ".join(brainkey).upper()
[ "Suggest", "a", "new", "random", "brain", "key", ".", "Randomness", "is", "provided", "by", "the", "operating", "system", "using", "os", ".", "urandom", "()", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L122-L135
[ "def", "suggest", "(", ")", ":", "word_count", "=", "16", "brainkey", "=", "[", "None", "]", "*", "word_count", "dict_lines", "=", "BrainKeyDictionary", ".", "split", "(", "\",\"", ")", "assert", "len", "(", "dict_lines", ")", "==", "49744", "for", "j", "in", "range", "(", "0", ",", "word_count", ")", ":", "num", "=", "int", ".", "from_bytes", "(", "os", ".", "urandom", "(", "2", ")", ",", "byteorder", "=", "\"little\"", ")", "rndMult", "=", "num", "/", "2", "**", "16", "# returns float between 0..1 (inclusive)", "wIdx", "=", "round", "(", "len", "(", "dict_lines", ")", "*", "rndMult", ")", "brainkey", "[", "j", "]", "=", "dict_lines", "[", "wIdx", "]", "return", "\" \"", ".", "join", "(", "brainkey", ")", ".", "upper", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Address.from_pubkey
Load an address provided the public key. Version: 56 => PTS
graphenebase/account.py
def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None): """ Load an address provided the public key. Version: 56 => PTS """ # Ensure this is a public key pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix) if compressed: pubkey_plain = pubkey.compressed() else: pubkey_plain = pubkey.uncompressed() sha = hashlib.sha256(unhexlify(pubkey_plain)).hexdigest() rep = hexlify(ripemd160(sha)).decode("ascii") s = ("%.2x" % version) + rep result = s + hexlify(doublesha256(s)[:4]).decode("ascii") result = hexlify(ripemd160(result)).decode("ascii") return cls(result, prefix=pubkey.prefix)
def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None): """ Load an address provided the public key. Version: 56 => PTS """ # Ensure this is a public key pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix) if compressed: pubkey_plain = pubkey.compressed() else: pubkey_plain = pubkey.uncompressed() sha = hashlib.sha256(unhexlify(pubkey_plain)).hexdigest() rep = hexlify(ripemd160(sha)).decode("ascii") s = ("%.2x" % version) + rep result = s + hexlify(doublesha256(s)[:4]).decode("ascii") result = hexlify(ripemd160(result)).decode("ascii") return cls(result, prefix=pubkey.prefix)
[ "Load", "an", "address", "provided", "the", "public", "key", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L158-L174
[ "def", "from_pubkey", "(", "cls", ",", "pubkey", ",", "compressed", "=", "True", ",", "version", "=", "56", ",", "prefix", "=", "None", ")", ":", "# Ensure this is a public key", "pubkey", "=", "PublicKey", "(", "pubkey", ",", "prefix", "=", "prefix", "or", "Prefix", ".", "prefix", ")", "if", "compressed", ":", "pubkey_plain", "=", "pubkey", ".", "compressed", "(", ")", "else", ":", "pubkey_plain", "=", "pubkey", ".", "uncompressed", "(", ")", "sha", "=", "hashlib", ".", "sha256", "(", "unhexlify", "(", "pubkey_plain", ")", ")", ".", "hexdigest", "(", ")", "rep", "=", "hexlify", "(", "ripemd160", "(", "sha", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "s", "=", "(", "\"%.2x\"", "%", "version", ")", "+", "rep", "result", "=", "s", "+", "hexlify", "(", "doublesha256", "(", "s", ")", "[", ":", "4", "]", ")", ".", "decode", "(", "\"ascii\"", ")", "result", "=", "hexlify", "(", "ripemd160", "(", "result", ")", ")", ".", "decode", "(", "\"ascii\"", ")", "return", "cls", "(", "result", ",", "prefix", "=", "pubkey", ".", "prefix", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
GrapheneAddress.from_pubkey
Derive address using ``RIPEMD160(SHA512(x))``
graphenebase/account.py
def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix) if compressed: pubkey_plain = pubkey.compressed() else: pubkey_plain = pubkey.uncompressed() """ Derive address using ``RIPEMD160(SHA512(x))`` """ addressbin = ripemd160(hashlib.sha512(unhexlify(pubkey_plain)).hexdigest()) result = Base58(hexlify(addressbin).decode("ascii")) return cls(result, prefix=pubkey.prefix)
def from_pubkey(cls, pubkey, compressed=True, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey, prefix=prefix or Prefix.prefix) if compressed: pubkey_plain = pubkey.compressed() else: pubkey_plain = pubkey.uncompressed() """ Derive address using ``RIPEMD160(SHA512(x))`` """ addressbin = ripemd160(hashlib.sha512(unhexlify(pubkey_plain)).hexdigest()) result = Base58(hexlify(addressbin).decode("ascii")) return cls(result, prefix=pubkey.prefix)
[ "Derive", "address", "using", "RIPEMD160", "(", "SHA512", "(", "x", "))" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L204-L215
[ "def", "from_pubkey", "(", "cls", ",", "pubkey", ",", "compressed", "=", "True", ",", "version", "=", "56", ",", "prefix", "=", "None", ")", ":", "# Ensure this is a public key", "pubkey", "=", "PublicKey", "(", "pubkey", ",", "prefix", "=", "prefix", "or", "Prefix", ".", "prefix", ")", "if", "compressed", ":", "pubkey_plain", "=", "pubkey", ".", "compressed", "(", ")", "else", ":", "pubkey_plain", "=", "pubkey", ".", "uncompressed", "(", ")", "addressbin", "=", "ripemd160", "(", "hashlib", ".", "sha512", "(", "unhexlify", "(", "pubkey_plain", ")", ")", ".", "hexdigest", "(", ")", ")", "result", "=", "Base58", "(", "hexlify", "(", "addressbin", ")", ".", "decode", "(", "\"ascii\"", ")", ")", "return", "cls", "(", "result", ",", "prefix", "=", "pubkey", ".", "prefix", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
PublicKey._derive_y_from_x
Derive y point from x point
graphenebase/account.py
def _derive_y_from_x(self, x, is_even): """ Derive y point from x point """ curve = ecdsa.SECP256k1.curve # The curve equation over F_p is: # y^2 = x^3 + ax + b a, b, p = curve.a(), curve.b(), curve.p() alpha = (pow(x, 3, p) + a * x + b) % p beta = ecdsa.numbertheory.square_root_mod_prime(alpha, p) if (beta % 2) == is_even: beta = p - beta return beta
def _derive_y_from_x(self, x, is_even): """ Derive y point from x point """ curve = ecdsa.SECP256k1.curve # The curve equation over F_p is: # y^2 = x^3 + ax + b a, b, p = curve.a(), curve.b(), curve.p() alpha = (pow(x, 3, p) + a * x + b) % p beta = ecdsa.numbertheory.square_root_mod_prime(alpha, p) if (beta % 2) == is_even: beta = p - beta return beta
[ "Derive", "y", "point", "from", "x", "point" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L261-L271
[ "def", "_derive_y_from_x", "(", "self", ",", "x", ",", "is_even", ")", ":", "curve", "=", "ecdsa", ".", "SECP256k1", ".", "curve", "# The curve equation over F_p is:", "# y^2 = x^3 + ax + b", "a", ",", "b", ",", "p", "=", "curve", ".", "a", "(", ")", ",", "curve", ".", "b", "(", ")", ",", "curve", ".", "p", "(", ")", "alpha", "=", "(", "pow", "(", "x", ",", "3", ",", "p", ")", "+", "a", "*", "x", "+", "b", ")", "%", "p", "beta", "=", "ecdsa", ".", "numbertheory", ".", "square_root_mod_prime", "(", "alpha", ",", "p", ")", "if", "(", "beta", "%", "2", ")", "==", "is_even", ":", "beta", "=", "p", "-", "beta", "return", "beta" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
PublicKey.point
Return the point for the public key
graphenebase/account.py
def point(self): """ Return the point for the public key """ string = unhexlify(self.unCompressed()) return ecdsa.VerifyingKey.from_string( string[1:], curve=ecdsa.SECP256k1 ).pubkey.point
def point(self): """ Return the point for the public key """ string = unhexlify(self.unCompressed()) return ecdsa.VerifyingKey.from_string( string[1:], curve=ecdsa.SECP256k1 ).pubkey.point
[ "Return", "the", "point", "for", "the", "public", "key" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L287-L292
[ "def", "point", "(", "self", ")", ":", "string", "=", "unhexlify", "(", "self", ".", "unCompressed", "(", ")", ")", "return", "ecdsa", ".", "VerifyingKey", ".", "from_string", "(", "string", "[", "1", ":", "]", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "pubkey", ".", "point" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
PublicKey.child
Derive new public key from this key and a sha256 "offset"
graphenebase/account.py
def child(self, offset256): """ Derive new public key from this key and a sha256 "offset" """ a = bytes(self) + offset256 s = hashlib.sha256(a).digest() return self.add(s)
def child(self, offset256): """ Derive new public key from this key and a sha256 "offset" """ a = bytes(self) + offset256 s = hashlib.sha256(a).digest() return self.add(s)
[ "Derive", "new", "public", "key", "from", "this", "key", "and", "a", "sha256", "offset" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L294-L298
[ "def", "child", "(", "self", ",", "offset256", ")", ":", "a", "=", "bytes", "(", "self", ")", "+", "offset256", "s", "=", "hashlib", ".", "sha256", "(", "a", ")", ".", "digest", "(", ")", "return", "self", ".", "add", "(", "s", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
PublicKey.from_privkey
Derive uncompressed public key
graphenebase/account.py
def from_privkey(cls, privkey, prefix=None): """ Derive uncompressed public key """ privkey = PrivateKey(privkey, prefix=prefix or Prefix.prefix) secret = unhexlify(repr(privkey)) order = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1 ).curve.generator.order() p = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1 ).verifying_key.pubkey.point x_str = ecdsa.util.number_to_string(p.x(), order) # y_str = ecdsa.util.number_to_string(p.y(), order) compressed = hexlify(chr(2 + (p.y() & 1)).encode("ascii") + x_str).decode( "ascii" ) # uncompressed = hexlify( # chr(4).encode('ascii') + x_str + y_str).decode('ascii') return cls(compressed, prefix=prefix or Prefix.prefix)
def from_privkey(cls, privkey, prefix=None): """ Derive uncompressed public key """ privkey = PrivateKey(privkey, prefix=prefix or Prefix.prefix) secret = unhexlify(repr(privkey)) order = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1 ).curve.generator.order() p = ecdsa.SigningKey.from_string( secret, curve=ecdsa.SECP256k1 ).verifying_key.pubkey.point x_str = ecdsa.util.number_to_string(p.x(), order) # y_str = ecdsa.util.number_to_string(p.y(), order) compressed = hexlify(chr(2 + (p.y() & 1)).encode("ascii") + x_str).decode( "ascii" ) # uncompressed = hexlify( # chr(4).encode('ascii') + x_str + y_str).decode('ascii') return cls(compressed, prefix=prefix or Prefix.prefix)
[ "Derive", "uncompressed", "public", "key" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L307-L324
[ "def", "from_privkey", "(", "cls", ",", "privkey", ",", "prefix", "=", "None", ")", ":", "privkey", "=", "PrivateKey", "(", "privkey", ",", "prefix", "=", "prefix", "or", "Prefix", ".", "prefix", ")", "secret", "=", "unhexlify", "(", "repr", "(", "privkey", ")", ")", "order", "=", "ecdsa", ".", "SigningKey", ".", "from_string", "(", "secret", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "curve", ".", "generator", ".", "order", "(", ")", "p", "=", "ecdsa", ".", "SigningKey", ".", "from_string", "(", "secret", ",", "curve", "=", "ecdsa", ".", "SECP256k1", ")", ".", "verifying_key", ".", "pubkey", ".", "point", "x_str", "=", "ecdsa", ".", "util", ".", "number_to_string", "(", "p", ".", "x", "(", ")", ",", "order", ")", "# y_str = ecdsa.util.number_to_string(p.y(), order)", "compressed", "=", "hexlify", "(", "chr", "(", "2", "+", "(", "p", ".", "y", "(", ")", "&", "1", ")", ")", ".", "encode", "(", "\"ascii\"", ")", "+", "x_str", ")", ".", "decode", "(", "\"ascii\"", ")", "# uncompressed = hexlify(", "# chr(4).encode('ascii') + x_str + y_str).decode('ascii')", "return", "cls", "(", "compressed", ",", "prefix", "=", "prefix", "or", "Prefix", ".", "prefix", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
PrivateKey.derive_private_key
Derive new private key from this private key and an arbitrary sequence number
graphenebase/account.py
def derive_private_key(self, sequence): """ Derive new private key from this private key and an arbitrary sequence number """ encoded = "%s %d" % (str(self), sequence) a = bytes(encoded, "ascii") s = hashlib.sha256(hashlib.sha512(a).digest()).digest() return PrivateKey(hexlify(s).decode("ascii"), prefix=self.pubkey.prefix)
def derive_private_key(self, sequence): """ Derive new private key from this private key and an arbitrary sequence number """ encoded = "%s %d" % (str(self), sequence) a = bytes(encoded, "ascii") s = hashlib.sha256(hashlib.sha512(a).digest()).digest() return PrivateKey(hexlify(s).decode("ascii"), prefix=self.pubkey.prefix)
[ "Derive", "new", "private", "key", "from", "this", "private", "key", "and", "an", "arbitrary", "sequence", "number" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L429-L436
[ "def", "derive_private_key", "(", "self", ",", "sequence", ")", ":", "encoded", "=", "\"%s %d\"", "%", "(", "str", "(", "self", ")", ",", "sequence", ")", "a", "=", "bytes", "(", "encoded", ",", "\"ascii\"", ")", "s", "=", "hashlib", ".", "sha256", "(", "hashlib", ".", "sha512", "(", "a", ")", ".", "digest", "(", ")", ")", ".", "digest", "(", ")", "return", "PrivateKey", "(", "hexlify", "(", "s", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "prefix", "=", "self", ".", "pubkey", ".", "prefix", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
PrivateKey.child
Derive new private key from this key and a sha256 "offset"
graphenebase/account.py
def child(self, offset256): """ Derive new private key from this key and a sha256 "offset" """ a = bytes(self.pubkey) + offset256 s = hashlib.sha256(a).digest() return self.derive_from_seed(s)
def child(self, offset256): """ Derive new private key from this key and a sha256 "offset" """ a = bytes(self.pubkey) + offset256 s = hashlib.sha256(a).digest() return self.derive_from_seed(s)
[ "Derive", "new", "private", "key", "from", "this", "key", "and", "a", "sha256", "offset" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L438-L443
[ "def", "child", "(", "self", ",", "offset256", ")", ":", "a", "=", "bytes", "(", "self", ".", "pubkey", ")", "+", "offset256", "s", "=", "hashlib", ".", "sha256", "(", "a", ")", ".", "digest", "(", ")", "return", "self", ".", "derive_from_seed", "(", "s", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
PrivateKey.derive_from_seed
Derive private key using "generate_from_seed" method. Here, the key itself serves as a `seed`, and `offset` is expected to be a sha256 digest.
graphenebase/account.py
def derive_from_seed(self, offset): """ Derive private key using "generate_from_seed" method. Here, the key itself serves as a `seed`, and `offset` is expected to be a sha256 digest. """ seed = int(hexlify(bytes(self)).decode("ascii"), 16) z = int(hexlify(offset).decode("ascii"), 16) order = ecdsa.SECP256k1.order secexp = (seed + z) % order secret = "%0x" % secexp if len(secret) < 64: # left-pad with zeroes secret = ("0" * (64-len(secret))) + secret return PrivateKey(secret, prefix=self.pubkey.prefix)
def derive_from_seed(self, offset): """ Derive private key using "generate_from_seed" method. Here, the key itself serves as a `seed`, and `offset` is expected to be a sha256 digest. """ seed = int(hexlify(bytes(self)).decode("ascii"), 16) z = int(hexlify(offset).decode("ascii"), 16) order = ecdsa.SECP256k1.order secexp = (seed + z) % order secret = "%0x" % secexp if len(secret) < 64: # left-pad with zeroes secret = ("0" * (64-len(secret))) + secret return PrivateKey(secret, prefix=self.pubkey.prefix)
[ "Derive", "private", "key", "using", "generate_from_seed", "method", ".", "Here", "the", "key", "itself", "serves", "as", "a", "seed", "and", "offset", "is", "expected", "to", "be", "a", "sha256", "digest", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L445-L457
[ "def", "derive_from_seed", "(", "self", ",", "offset", ")", ":", "seed", "=", "int", "(", "hexlify", "(", "bytes", "(", "self", ")", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "16", ")", "z", "=", "int", "(", "hexlify", "(", "offset", ")", ".", "decode", "(", "\"ascii\"", ")", ",", "16", ")", "order", "=", "ecdsa", ".", "SECP256k1", ".", "order", "secexp", "=", "(", "seed", "+", "z", ")", "%", "order", "secret", "=", "\"%0x\"", "%", "secexp", "if", "len", "(", "secret", ")", "<", "64", ":", "# left-pad with zeroes", "secret", "=", "(", "\"0\"", "*", "(", "64", "-", "len", "(", "secret", ")", ")", ")", "+", "secret", "return", "PrivateKey", "(", "secret", ",", "prefix", "=", "self", ".", "pubkey", ".", "prefix", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
BitcoinAddress.from_pubkey
Derive address using ``RIPEMD160(SHA256(x))``
graphenebase/account.py
def from_pubkey(cls, pubkey, compressed=False, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey) if compressed: pubkey = pubkey.compressed() else: pubkey = pubkey.uncompressed() """ Derive address using ``RIPEMD160(SHA256(x))`` """ addressbin = ripemd160(hexlify(hashlib.sha256(unhexlify(pubkey)).digest())) return cls(hexlify(addressbin).decode("ascii"))
def from_pubkey(cls, pubkey, compressed=False, version=56, prefix=None): # Ensure this is a public key pubkey = PublicKey(pubkey) if compressed: pubkey = pubkey.compressed() else: pubkey = pubkey.uncompressed() """ Derive address using ``RIPEMD160(SHA256(x))`` """ addressbin = ripemd160(hexlify(hashlib.sha256(unhexlify(pubkey)).digest())) return cls(hexlify(addressbin).decode("ascii"))
[ "Derive", "address", "using", "RIPEMD160", "(", "SHA256", "(", "x", "))" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/account.py#L482-L492
[ "def", "from_pubkey", "(", "cls", ",", "pubkey", ",", "compressed", "=", "False", ",", "version", "=", "56", ",", "prefix", "=", "None", ")", ":", "# Ensure this is a public key", "pubkey", "=", "PublicKey", "(", "pubkey", ")", "if", "compressed", ":", "pubkey", "=", "pubkey", ".", "compressed", "(", ")", "else", ":", "pubkey", "=", "pubkey", ".", "uncompressed", "(", ")", "addressbin", "=", "ripemd160", "(", "hexlify", "(", "hashlib", ".", "sha256", "(", "unhexlify", "(", "pubkey", ")", ")", ".", "digest", "(", ")", ")", ")", "return", "cls", "(", "hexlify", "(", "addressbin", ")", ".", "decode", "(", "\"ascii\"", ")", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Http.rpcexec
Execute a call by sending the payload :param json payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises HttpInvalidStatusCode: if the server returns a status code that is not 200
grapheneapi/http.py
def rpcexec(self, payload): """ Execute a call by sending the payload :param json payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises HttpInvalidStatusCode: if the server returns a status code that is not 200 """ log.debug(json.dumps(payload)) query = requests.post(self.url, json=payload, proxies=self.proxies()) if query.status_code != 200: # pragma: no cover raise HttpInvalidStatusCode( "Status code returned: {}".format(query.status_code) ) return query.text
def rpcexec(self, payload): """ Execute a call by sending the payload :param json payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises HttpInvalidStatusCode: if the server returns a status code that is not 200 """ log.debug(json.dumps(payload)) query = requests.post(self.url, json=payload, proxies=self.proxies()) if query.status_code != 200: # pragma: no cover raise HttpInvalidStatusCode( "Status code returned: {}".format(query.status_code) ) return query.text
[ "Execute", "a", "call", "by", "sending", "the", "payload" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/grapheneapi/http.py#L22-L38
[ "def", "rpcexec", "(", "self", ",", "payload", ")", ":", "log", ".", "debug", "(", "json", ".", "dumps", "(", "payload", ")", ")", "query", "=", "requests", ".", "post", "(", "self", ".", "url", ",", "json", "=", "payload", ",", "proxies", "=", "self", ".", "proxies", "(", ")", ")", "if", "query", ".", "status_code", "!=", "200", ":", "# pragma: no cover", "raise", "HttpInvalidStatusCode", "(", "\"Status code returned: {}\"", ".", "format", "(", "query", ".", "status_code", ")", ")", "return", "query", ".", "text" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
varint
Varint encoding
graphenebase/types.py
def varint(n): """ Varint encoding """ data = b"" while n >= 0x80: data += bytes([(n & 0x7F) | 0x80]) n >>= 7 data += bytes([n]) return data
def varint(n): """ Varint encoding """ data = b"" while n >= 0x80: data += bytes([(n & 0x7F) | 0x80]) n >>= 7 data += bytes([n]) return data
[ "Varint", "encoding" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/types.py#L13-L21
[ "def", "varint", "(", "n", ")", ":", "data", "=", "b\"\"", "while", "n", ">=", "0x80", ":", "data", "+=", "bytes", "(", "[", "(", "n", "&", "0x7F", ")", "|", "0x80", "]", ")", "n", ">>=", "7", "data", "+=", "bytes", "(", "[", "n", "]", ")", "return", "data" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
varintdecode
Varint decoding
graphenebase/types.py
def varintdecode(data): # pragma: no cover """ Varint decoding """ shift = 0 result = 0 for b in bytes(data): result |= (b & 0x7F) << shift if not (b & 0x80): break shift += 7 return result
def varintdecode(data): # pragma: no cover """ Varint decoding """ shift = 0 result = 0 for b in bytes(data): result |= (b & 0x7F) << shift if not (b & 0x80): break shift += 7 return result
[ "Varint", "decoding" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/types.py#L24-L34
[ "def", "varintdecode", "(", "data", ")", ":", "# pragma: no cover", "shift", "=", "0", "result", "=", "0", "for", "b", "in", "bytes", "(", "data", ")", ":", "result", "|=", "(", "b", "&", "0x7F", ")", "<<", "shift", "if", "not", "(", "b", "&", "0x80", ")", ":", "break", "shift", "+=", "7", "return", "result" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
GenesisBalance.claim
Claim a balance from the genesis block :param str balance_id: The identifier that identifies the balance to claim (1.15.x) :param str account: (optional) the account that owns the bet (defaults to ``default_account``)
graphenecommon/genesisbalance.py
def claim(self, account=None, **kwargs): """ Claim a balance from the genesis block :param str balance_id: The identifier that identifies the balance to claim (1.15.x) :param str account: (optional) the account that owns the bet (defaults to ``default_account``) """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = self.account_class(account, blockchain_instance=self.blockchain) pubkeys = self.blockchain.wallet.getPublicKeys() addresses = dict() for p in pubkeys: if p[: len(self.blockchain.prefix)] != self.blockchain.prefix: continue pubkey = self.publickey_class(p, prefix=self.blockchain.prefix) addresses[ str( self.address_class.from_pubkey( pubkey, compressed=False, version=0, prefix=self.blockchain.prefix, ) ) ] = pubkey addresses[ str( self.address_class.from_pubkey( pubkey, compressed=True, version=0, prefix=self.blockchain.prefix, ) ) ] = pubkey addresses[ str( self.address_class.from_pubkey( pubkey, compressed=False, version=56, prefix=self.blockchain.prefix, ) ) ] = pubkey addresses[ str( self.address_class.from_pubkey( pubkey, compressed=True, version=56, prefix=self.blockchain.prefix, ) ) ] = pubkey if self["owner"] not in addresses.keys(): raise MissingKeyError("Need key for address {}".format(self["owner"])) op = self.operations.Balance_claim( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "deposit_to_account": account["id"], "balance_to_claim": self["id"], "balance_owner_key": addresses[self["owner"]], "total_claimed": self["balance"], "prefix": self.blockchain.prefix, } ) signers = [ account["name"], # The fee payer and receiver account addresses.get(self["owner"]), # The genesis balance! ] return self.blockchain.finalizeOp(op, signers, "active", **kwargs)
def claim(self, account=None, **kwargs): """ Claim a balance from the genesis block :param str balance_id: The identifier that identifies the balance to claim (1.15.x) :param str account: (optional) the account that owns the bet (defaults to ``default_account``) """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = self.account_class(account, blockchain_instance=self.blockchain) pubkeys = self.blockchain.wallet.getPublicKeys() addresses = dict() for p in pubkeys: if p[: len(self.blockchain.prefix)] != self.blockchain.prefix: continue pubkey = self.publickey_class(p, prefix=self.blockchain.prefix) addresses[ str( self.address_class.from_pubkey( pubkey, compressed=False, version=0, prefix=self.blockchain.prefix, ) ) ] = pubkey addresses[ str( self.address_class.from_pubkey( pubkey, compressed=True, version=0, prefix=self.blockchain.prefix, ) ) ] = pubkey addresses[ str( self.address_class.from_pubkey( pubkey, compressed=False, version=56, prefix=self.blockchain.prefix, ) ) ] = pubkey addresses[ str( self.address_class.from_pubkey( pubkey, compressed=True, version=56, prefix=self.blockchain.prefix, ) ) ] = pubkey if self["owner"] not in addresses.keys(): raise MissingKeyError("Need key for address {}".format(self["owner"])) op = self.operations.Balance_claim( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "deposit_to_account": account["id"], "balance_to_claim": self["id"], "balance_owner_key": addresses[self["owner"]], "total_claimed": self["balance"], "prefix": self.blockchain.prefix, } ) signers = [ account["name"], # The fee payer and receiver account addresses.get(self["owner"]), # The genesis balance! ] return self.blockchain.finalizeOp(op, signers, "active", **kwargs)
[ "Claim", "a", "balance", "from", "the", "genesis", "block" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/genesisbalance.py#L41-L119
[ "def", "claim", "(", "self", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "blockchain", ".", "config", ":", "account", "=", "self", ".", "blockchain", ".", "config", "[", "\"default_account\"", "]", "if", "not", "account", ":", "raise", "ValueError", "(", "\"You need to provide an account\"", ")", "account", "=", "self", ".", "account_class", "(", "account", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "pubkeys", "=", "self", ".", "blockchain", ".", "wallet", ".", "getPublicKeys", "(", ")", "addresses", "=", "dict", "(", ")", "for", "p", "in", "pubkeys", ":", "if", "p", "[", ":", "len", "(", "self", ".", "blockchain", ".", "prefix", ")", "]", "!=", "self", ".", "blockchain", ".", "prefix", ":", "continue", "pubkey", "=", "self", ".", "publickey_class", "(", "p", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ")", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "False", ",", "version", "=", "0", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "True", ",", "version", "=", "0", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "False", ",", "version", "=", "56", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "addresses", "[", "str", "(", "self", ".", "address_class", ".", "from_pubkey", "(", "pubkey", ",", "compressed", "=", "True", ",", "version", "=", "56", ",", "prefix", "=", "self", ".", "blockchain", ".", "prefix", ",", ")", ")", "]", "=", "pubkey", "if", "self", "[", "\"owner\"", "]", "not", "in", "addresses", ".", "keys", "(", ")", ":", "raise", "MissingKeyError", "(", "\"Need key for address {}\"", ".", "format", "(", "self", "[", "\"owner\"", "]", ")", ")", "op", "=", "self", ".", "operations", ".", "Balance_claim", "(", "*", "*", "{", "\"fee\"", ":", "{", "\"amount\"", ":", "0", ",", "\"asset_id\"", ":", "\"1.3.0\"", "}", ",", "\"deposit_to_account\"", ":", "account", "[", "\"id\"", "]", ",", "\"balance_to_claim\"", ":", "self", "[", "\"id\"", "]", ",", "\"balance_owner_key\"", ":", "addresses", "[", "self", "[", "\"owner\"", "]", "]", ",", "\"total_claimed\"", ":", "self", "[", "\"balance\"", "]", ",", "\"prefix\"", ":", "self", ".", "blockchain", ".", "prefix", ",", "}", ")", "signers", "=", "[", "account", "[", "\"name\"", "]", ",", "# The fee payer and receiver account", "addresses", ".", "get", "(", "self", "[", "\"owner\"", "]", ")", ",", "# The genesis balance!", "]", "return", "self", ".", "blockchain", ".", "finalizeOp", "(", "op", ",", "signers", ",", "\"active\"", ",", "*", "*", "kwargs", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
get_default_key_store
This method returns the default **key** store that uses an SQLite database internally. :params str appname: The appname that is used internally to distinguish different SQLite files
graphenestorage/__init__.py
def get_default_key_store(*args, config, **kwargs): """ This method returns the default **key** store that uses an SQLite database internally. :params str appname: The appname that is used internally to distinguish different SQLite files """ kwargs["appname"] = kwargs.get("appname", "graphene") return SqliteEncryptedKeyStore(config=config, **kwargs)
def get_default_key_store(*args, config, **kwargs): """ This method returns the default **key** store that uses an SQLite database internally. :params str appname: The appname that is used internally to distinguish different SQLite files """ kwargs["appname"] = kwargs.get("appname", "graphene") return SqliteEncryptedKeyStore(config=config, **kwargs)
[ "This", "method", "returns", "the", "default", "**", "key", "**", "store", "that", "uses", "an", "SQLite", "database", "internally", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/__init__.py#L27-L35
[ "def", "get_default_key_store", "(", "*", "args", ",", "config", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"appname\"", "]", "=", "kwargs", ".", "get", "(", "\"appname\"", ",", "\"graphene\"", ")", "return", "SqliteEncryptedKeyStore", "(", "config", "=", "config", ",", "*", "*", "kwargs", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Operation.getOperationNameForId
Convert an operation id into the corresponding string
graphenebase/objects.py
def getOperationNameForId(self, i): """ Convert an operation id into the corresponding string """ for key in self.ops: if int(self.ops[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" % i)
def getOperationNameForId(self, i): """ Convert an operation id into the corresponding string """ for key in self.ops: if int(self.ops[key]) is int(i): return key raise ValueError("Unknown Operation ID %d" % i)
[ "Convert", "an", "operation", "id", "into", "the", "corresponding", "string" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenebase/objects.py#L147-L153
[ "def", "getOperationNameForId", "(", "self", ",", "i", ")", ":", "for", "key", "in", "self", ".", "ops", ":", "if", "int", "(", "self", ".", "ops", "[", "key", "]", ")", "is", "int", "(", "i", ")", ":", "return", "key", "raise", "ValueError", "(", "\"Unknown Operation ID %d\"", "%", "i", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
AbstractBlockchainInstanceProvider.shared_blockchain_instance
This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default instance that can be reused by multiple classes.
graphenecommon/instance.py
def shared_blockchain_instance(self): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default instance that can be reused by multiple classes. """ if not self._sharedInstance.instance: klass = self.get_instance_class() self._sharedInstance.instance = klass(**self._sharedInstance.config) return self._sharedInstance.instance
def shared_blockchain_instance(self): """ This method will initialize ``SharedInstance.instance`` and return it. The purpose of this method is to have offer single default instance that can be reused by multiple classes. """ if not self._sharedInstance.instance: klass = self.get_instance_class() self._sharedInstance.instance = klass(**self._sharedInstance.config) return self._sharedInstance.instance
[ "This", "method", "will", "initialize", "SharedInstance", ".", "instance", "and", "return", "it", ".", "The", "purpose", "of", "this", "method", "is", "to", "have", "offer", "single", "default", "instance", "that", "can", "be", "reused", "by", "multiple", "classes", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/instance.py#L68-L76
[ "def", "shared_blockchain_instance", "(", "self", ")", ":", "if", "not", "self", ".", "_sharedInstance", ".", "instance", ":", "klass", "=", "self", ".", "get_instance_class", "(", ")", "self", ".", "_sharedInstance", ".", "instance", "=", "klass", "(", "*", "*", "self", ".", "_sharedInstance", ".", "config", ")", "return", "self", ".", "_sharedInstance", ".", "instance" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
AbstractBlockchainInstanceProvider.set_shared_config
This allows to set a config that will be used when calling ``shared_blockchain_instance`` and allows to define the configuration without requiring to actually create an instance
graphenecommon/instance.py
def set_shared_config(cls, config): """ This allows to set a config that will be used when calling ``shared_blockchain_instance`` and allows to define the configuration without requiring to actually create an instance """ assert isinstance(config, dict) cls._sharedInstance.config.update(config) # if one is already set, delete if cls._sharedInstance.instance: cls._sharedInstance.instance = None
def set_shared_config(cls, config): """ This allows to set a config that will be used when calling ``shared_blockchain_instance`` and allows to define the configuration without requiring to actually create an instance """ assert isinstance(config, dict) cls._sharedInstance.config.update(config) # if one is already set, delete if cls._sharedInstance.instance: cls._sharedInstance.instance = None
[ "This", "allows", "to", "set", "a", "config", "that", "will", "be", "used", "when", "calling", "shared_blockchain_instance", "and", "allows", "to", "define", "the", "configuration", "without", "requiring", "to", "actually", "create", "an", "instance" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/instance.py#L96-L105
[ "def", "set_shared_config", "(", "cls", ",", "config", ")", ":", "assert", "isinstance", "(", "config", ",", "dict", ")", "cls", ".", "_sharedInstance", ".", "config", ".", "update", "(", "config", ")", "# if one is already set, delete", "if", "cls", ".", "_sharedInstance", ".", "instance", ":", "cls", ".", "_sharedInstance", ".", "instance", "=", "None" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Api.find_next
Find the next url in the list
grapheneapi/api.py
def find_next(self): """ Find the next url in the list """ if int(self.num_retries) < 0: # pragma: no cover self._cnt_retries += 1 sleeptime = (self._cnt_retries - 1) * 2 if self._cnt_retries < 10 else 10 if sleeptime: log.warning( "Lost connection to node during rpcexec(): %s (%d/%d) " % (self.url, self._cnt_retries, self.num_retries) + "Retrying in %d seconds" % sleeptime ) sleep(sleeptime) return next(self.urls) urls = [ k for k, v in self._url_counter.items() if ( # Only provide URLS if num_retries is bigger equal 0, # i.e. we want to do reconnects at all int(self.num_retries) >= 0 # the counter for this host/endpoint should be smaller than # num_retries and v <= self.num_retries # let's not retry with the same URL *if* we have others # available and (k != self.url or len(self._url_counter) == 1) ) ] if not len(urls): raise NumRetriesReached url = urls[0] return url
def find_next(self): """ Find the next url in the list """ if int(self.num_retries) < 0: # pragma: no cover self._cnt_retries += 1 sleeptime = (self._cnt_retries - 1) * 2 if self._cnt_retries < 10 else 10 if sleeptime: log.warning( "Lost connection to node during rpcexec(): %s (%d/%d) " % (self.url, self._cnt_retries, self.num_retries) + "Retrying in %d seconds" % sleeptime ) sleep(sleeptime) return next(self.urls) urls = [ k for k, v in self._url_counter.items() if ( # Only provide URLS if num_retries is bigger equal 0, # i.e. we want to do reconnects at all int(self.num_retries) >= 0 # the counter for this host/endpoint should be smaller than # num_retries and v <= self.num_retries # let's not retry with the same URL *if* we have others # available and (k != self.url or len(self._url_counter) == 1) ) ] if not len(urls): raise NumRetriesReached url = urls[0] return url
[ "Find", "the", "next", "url", "in", "the", "list" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/grapheneapi/api.py#L81-L114
[ "def", "find_next", "(", "self", ")", ":", "if", "int", "(", "self", ".", "num_retries", ")", "<", "0", ":", "# pragma: no cover", "self", ".", "_cnt_retries", "+=", "1", "sleeptime", "=", "(", "self", ".", "_cnt_retries", "-", "1", ")", "*", "2", "if", "self", ".", "_cnt_retries", "<", "10", "else", "10", "if", "sleeptime", ":", "log", ".", "warning", "(", "\"Lost connection to node during rpcexec(): %s (%d/%d) \"", "%", "(", "self", ".", "url", ",", "self", ".", "_cnt_retries", ",", "self", ".", "num_retries", ")", "+", "\"Retrying in %d seconds\"", "%", "sleeptime", ")", "sleep", "(", "sleeptime", ")", "return", "next", "(", "self", ".", "urls", ")", "urls", "=", "[", "k", "for", "k", ",", "v", "in", "self", ".", "_url_counter", ".", "items", "(", ")", "if", "(", "# Only provide URLS if num_retries is bigger equal 0,", "# i.e. we want to do reconnects at all", "int", "(", "self", ".", "num_retries", ")", ">=", "0", "# the counter for this host/endpoint should be smaller than", "# num_retries", "and", "v", "<=", "self", ".", "num_retries", "# let's not retry with the same URL *if* we have others", "# available", "and", "(", "k", "!=", "self", ".", "url", "or", "len", "(", "self", ".", "_url_counter", ")", "==", "1", ")", ")", "]", "if", "not", "len", "(", "urls", ")", ":", "raise", "NumRetriesReached", "url", "=", "urls", "[", "0", "]", "return", "url" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Api.reset_counter
reset the failed connection counters
grapheneapi/api.py
def reset_counter(self): """ reset the failed connection counters """ self._cnt_retries = 0 for i in self._url_counter: self._url_counter[i] = 0
def reset_counter(self): """ reset the failed connection counters """ self._cnt_retries = 0 for i in self._url_counter: self._url_counter[i] = 0
[ "reset", "the", "failed", "connection", "counters" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/grapheneapi/api.py#L116-L121
[ "def", "reset_counter", "(", "self", ")", ":", "self", ".", "_cnt_retries", "=", "0", "for", "i", "in", "self", ".", "_url_counter", ":", "self", ".", "_url_counter", "[", "i", "]", "=", "0" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
Block.refresh
Even though blocks never change, you freshly obtain its contents from an API with this method
graphenecommon/block.py
def refresh(self): """ Even though blocks never change, you freshly obtain its contents from an API with this method """ block = self.blockchain.rpc.get_block(self.identifier) if not block: raise BlockDoesNotExistsException super(Block, self).__init__( block, blockchain_instance=self.blockchain, use_cache=self._use_cache )
def refresh(self): """ Even though blocks never change, you freshly obtain its contents from an API with this method """ block = self.blockchain.rpc.get_block(self.identifier) if not block: raise BlockDoesNotExistsException super(Block, self).__init__( block, blockchain_instance=self.blockchain, use_cache=self._use_cache )
[ "Even", "though", "blocks", "never", "change", "you", "freshly", "obtain", "its", "contents", "from", "an", "API", "with", "this", "method" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/block.py#L40-L49
[ "def", "refresh", "(", "self", ")", ":", "block", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_block", "(", "self", ".", "identifier", ")", "if", "not", "block", ":", "raise", "BlockDoesNotExistsException", "super", "(", "Block", ",", "self", ")", ".", "__init__", "(", "block", ",", "blockchain_instance", "=", "self", ".", "blockchain", ",", "use_cache", "=", "self", ".", "_use_cache", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
BlockHeader.refresh
Even though blocks never change, you freshly obtain its contents from an API with this method
graphenecommon/block.py
def refresh(self): """ Even though blocks never change, you freshly obtain its contents from an API with this method """ block = self.blockchain.rpc.get_block_header(self.identifier) if not block: raise BlockDoesNotExistsException super(BlockHeader, self).__init__( block, blockchain_instance=self.blockchain, use_cache=self._use_cache )
def refresh(self): """ Even though blocks never change, you freshly obtain its contents from an API with this method """ block = self.blockchain.rpc.get_block_header(self.identifier) if not block: raise BlockDoesNotExistsException super(BlockHeader, self).__init__( block, blockchain_instance=self.blockchain, use_cache=self._use_cache )
[ "Even", "though", "blocks", "never", "change", "you", "freshly", "obtain", "its", "contents", "from", "an", "API", "with", "this", "method" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/block.py#L67-L76
[ "def", "refresh", "(", "self", ")", ":", "block", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_block_header", "(", "self", ".", "identifier", ")", "if", "not", "block", ":", "raise", "BlockDoesNotExistsException", "super", "(", "BlockHeader", ",", "self", ")", ".", "__init__", "(", "block", ",", "blockchain_instance", "=", "self", ".", "blockchain", ",", "use_cache", "=", "self", ".", "_use_cache", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
SQLiteStore._haveKey
Is the key `key` available?
graphenestorage/sqlite.py
def _haveKey(self, key): """ Is the key `key` available? """ query = ( "SELECT {} FROM {} WHERE {}=?".format( self.__value__, self.__tablename__, self.__key__ ), (key,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(*query) return True if cursor.fetchone() else False
def _haveKey(self, key): """ Is the key `key` available? """ query = ( "SELECT {} FROM {} WHERE {}=?".format( self.__value__, self.__tablename__, self.__key__ ), (key,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(*query) return True if cursor.fetchone() else False
[ "Is", "the", "key", "key", "available?" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L91-L103
[ "def", "_haveKey", "(", "self", ",", "key", ")", ":", "query", "=", "(", "\"SELECT {} FROM {} WHERE {}=?\"", ".", "format", "(", "self", ".", "__value__", ",", "self", ".", "__tablename__", ",", "self", ".", "__key__", ")", ",", "(", "key", ",", ")", ",", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "*", "query", ")", "return", "True", "if", "cursor", ".", "fetchone", "(", ")", "else", "False" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
SQLiteStore.items
returns all items off the store as tuples
graphenestorage/sqlite.py
def items(self): """ returns all items off the store as tuples """ query = "SELECT {}, {} from {}".format( self.__key__, self.__value__, self.__tablename__ ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(query) r = [] for key, value in cursor.fetchall(): r.append((key, value)) return r
def items(self): """ returns all items off the store as tuples """ query = "SELECT {}, {} from {}".format( self.__key__, self.__value__, self.__tablename__ ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(query) r = [] for key, value in cursor.fetchall(): r.append((key, value)) return r
[ "returns", "all", "items", "off", "the", "store", "as", "tuples" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L186-L198
[ "def", "items", "(", "self", ")", ":", "query", "=", "\"SELECT {}, {} from {}\"", ".", "format", "(", "self", ".", "__key__", ",", "self", ".", "__value__", ",", "self", ".", "__tablename__", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "query", ")", "r", "=", "[", "]", "for", "key", ",", "value", "in", "cursor", ".", "fetchall", "(", ")", ":", "r", ".", "append", "(", "(", "key", ",", "value", ")", ")", "return", "r" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
SQLiteStore.get
Return the key if exists or a default value :param str value: Value :param str default: Default value if key not present
graphenestorage/sqlite.py
def get(self, key, default=None): """ Return the key if exists or a default value :param str value: Value :param str default: Default value if key not present """ if key in self: return self.__getitem__(key) else: return default
def get(self, key, default=None): """ Return the key if exists or a default value :param str value: Value :param str default: Default value if key not present """ if key in self: return self.__getitem__(key) else: return default
[ "Return", "the", "key", "if", "exists", "or", "a", "default", "value" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L200-L209
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "if", "key", "in", "self", ":", "return", "self", ".", "__getitem__", "(", "key", ")", "else", ":", "return", "default" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
SQLiteStore.delete
Delete a key from the store :param str value: Value
graphenestorage/sqlite.py
def delete(self, key): """ Delete a key from the store :param str value: Value """ query = ( "DELETE FROM {} WHERE {}=?".format(self.__tablename__, self.__key__), (key,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(*query) connection.commit()
def delete(self, key): """ Delete a key from the store :param str value: Value """ query = ( "DELETE FROM {} WHERE {}=?".format(self.__tablename__, self.__key__), (key,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(*query) connection.commit()
[ "Delete", "a", "key", "from", "the", "store" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L212-L224
[ "def", "delete", "(", "self", ",", "key", ")", ":", "query", "=", "(", "\"DELETE FROM {} WHERE {}=?\"", ".", "format", "(", "self", ".", "__tablename__", ",", "self", ".", "__key__", ")", ",", "(", "key", ",", ")", ",", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "*", "query", ")", "connection", ".", "commit", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
SQLiteStore.wipe
Wipe the store
graphenestorage/sqlite.py
def wipe(self): """ Wipe the store """ query = "DELETE FROM {}".format(self.__tablename__) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(query) connection.commit()
def wipe(self): """ Wipe the store """ query = "DELETE FROM {}".format(self.__tablename__) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(query) connection.commit()
[ "Wipe", "the", "store" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L226-L233
[ "def", "wipe", "(", "self", ")", ":", "query", "=", "\"DELETE FROM {}\"", ".", "format", "(", "self", ".", "__tablename__", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "query", ")", "connection", ".", "commit", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
SQLiteStore.exists
Check if the database table exists
graphenestorage/sqlite.py
def exists(self): """ Check if the database table exists """ query = ( "SELECT name FROM sqlite_master " + "WHERE type='table' AND name=?", (self.__tablename__,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(*query) return True if cursor.fetchone() else False
def exists(self): """ Check if the database table exists """ query = ( "SELECT name FROM sqlite_master " + "WHERE type='table' AND name=?", (self.__tablename__,), ) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(*query) return True if cursor.fetchone() else False
[ "Check", "if", "the", "database", "table", "exists" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L235-L245
[ "def", "exists", "(", "self", ")", ":", "query", "=", "(", "\"SELECT name FROM sqlite_master \"", "+", "\"WHERE type='table' AND name=?\"", ",", "(", "self", ".", "__tablename__", ",", ")", ",", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "*", "query", ")", "return", "True", "if", "cursor", ".", "fetchone", "(", ")", "else", "False" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
SQLiteStore.create
Create the new table in the SQLite database
graphenestorage/sqlite.py
def create(self): # pragma: no cover """ Create the new table in the SQLite database """ query = ( """ CREATE TABLE {} ( id INTEGER PRIMARY KEY AUTOINCREMENT, {} STRING(256), {} STRING(256) )""" ).format(self.__tablename__, self.__key__, self.__value__) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(query) connection.commit()
def create(self): # pragma: no cover """ Create the new table in the SQLite database """ query = ( """ CREATE TABLE {} ( id INTEGER PRIMARY KEY AUTOINCREMENT, {} STRING(256), {} STRING(256) )""" ).format(self.__tablename__, self.__key__, self.__value__) connection = sqlite3.connect(self.sqlite_file) cursor = connection.cursor() cursor.execute(query) connection.commit()
[ "Create", "the", "new", "table", "in", "the", "SQLite", "database" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenestorage/sqlite.py#L247-L261
[ "def", "create", "(", "self", ")", ":", "# pragma: no cover", "query", "=", "(", "\"\"\"\n CREATE TABLE {} (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n {} STRING(256),\n {} STRING(256)\n )\"\"\"", ")", ".", "format", "(", "self", ".", "__tablename__", ",", "self", ".", "__key__", ",", "self", ".", "__value__", ")", "connection", "=", "sqlite3", ".", "connect", "(", "self", ".", "sqlite_file", ")", "cursor", "=", "connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "query", ")", "connection", ".", "commit", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
ProposalBuilder.appendOps
Append op(s) to the transaction builder :param list ops: One or a list of operations
graphenecommon/transactionbuilder.py
def appendOps(self, ops, append_to=None): """ Append op(s) to the transaction builder :param list ops: One or a list of operations """ if isinstance(ops, list): self.ops.extend(ops) else: self.ops.append(ops) parent = self.parent if parent: parent._set_require_reconstruction()
def appendOps(self, ops, append_to=None): """ Append op(s) to the transaction builder :param list ops: One or a list of operations """ if isinstance(ops, list): self.ops.extend(ops) else: self.ops.append(ops) parent = self.parent if parent: parent._set_require_reconstruction()
[ "Append", "op", "(", "s", ")", "to", "the", "transaction", "builder" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L68-L79
[ "def", "appendOps", "(", "self", ",", "ops", ",", "append_to", "=", "None", ")", ":", "if", "isinstance", "(", "ops", ",", "list", ")", ":", "self", ".", "ops", ".", "extend", "(", "ops", ")", "else", ":", "self", ".", "ops", ".", "append", "(", "ops", ")", "parent", "=", "self", ".", "parent", "if", "parent", ":", "parent", ".", "_set_require_reconstruction", "(", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
ProposalBuilder.get_raw
Returns an instance of base "Operations" for further processing
graphenecommon/transactionbuilder.py
def get_raw(self): """ Returns an instance of base "Operations" for further processing """ if not self.ops: return ops = [self.operations.Op_wrapper(op=o) for o in list(self.ops)] proposer = self.account_class( self.proposer, blockchain_instance=self.blockchain ) data = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "fee_paying_account": proposer["id"], "expiration_time": formatTimeFromNow(self.proposal_expiration), "proposed_ops": [o.json() for o in ops], "extensions": [], } if self.proposal_review: data.update({"review_period_seconds": self.proposal_review}) ops = self.operations.Proposal_create(**data) return self.operation_class(ops)
def get_raw(self): """ Returns an instance of base "Operations" for further processing """ if not self.ops: return ops = [self.operations.Op_wrapper(op=o) for o in list(self.ops)] proposer = self.account_class( self.proposer, blockchain_instance=self.blockchain ) data = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "fee_paying_account": proposer["id"], "expiration_time": formatTimeFromNow(self.proposal_expiration), "proposed_ops": [o.json() for o in ops], "extensions": [], } if self.proposal_review: data.update({"review_period_seconds": self.proposal_review}) ops = self.operations.Proposal_create(**data) return self.operation_class(ops)
[ "Returns", "an", "instance", "of", "base", "Operations", "for", "further", "processing" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L110-L129
[ "def", "get_raw", "(", "self", ")", ":", "if", "not", "self", ".", "ops", ":", "return", "ops", "=", "[", "self", ".", "operations", ".", "Op_wrapper", "(", "op", "=", "o", ")", "for", "o", "in", "list", "(", "self", ".", "ops", ")", "]", "proposer", "=", "self", ".", "account_class", "(", "self", ".", "proposer", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "data", "=", "{", "\"fee\"", ":", "{", "\"amount\"", ":", "0", ",", "\"asset_id\"", ":", "\"1.3.0\"", "}", ",", "\"fee_paying_account\"", ":", "proposer", "[", "\"id\"", "]", ",", "\"expiration_time\"", ":", "formatTimeFromNow", "(", "self", ".", "proposal_expiration", ")", ",", "\"proposed_ops\"", ":", "[", "o", ".", "json", "(", ")", "for", "o", "in", "ops", "]", ",", "\"extensions\"", ":", "[", "]", ",", "}", "if", "self", ".", "proposal_review", ":", "data", ".", "update", "(", "{", "\"review_period_seconds\"", ":", "self", ".", "proposal_review", "}", ")", "ops", "=", "self", ".", "operations", ".", "Proposal_create", "(", "*", "*", "data", ")", "return", "self", ".", "operation_class", "(", "ops", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
TransactionBuilder.json
Show the transaction as plain json
graphenecommon/transactionbuilder.py
def json(self): """ Show the transaction as plain json """ if not self._is_constructed() or self._is_require_reconstruction(): self.constructTx() return dict(self)
def json(self): """ Show the transaction as plain json """ if not self._is_constructed() or self._is_require_reconstruction(): self.constructTx() return dict(self)
[ "Show", "the", "transaction", "as", "plain", "json" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L213-L218
[ "def", "json", "(", "self", ")", ":", "if", "not", "self", ".", "_is_constructed", "(", ")", "or", "self", ".", "_is_require_reconstruction", "(", ")", ":", "self", ".", "constructTx", "(", ")", "return", "dict", "(", "self", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
TransactionBuilder.appendSigner
Try to obtain the wif key from the wallet by telling which account and permission is supposed to sign the transaction
graphenecommon/transactionbuilder.py
def appendSigner(self, accounts, permission): """ Try to obtain the wif key from the wallet by telling which account and permission is supposed to sign the transaction """ assert permission in self.permission_types, "Invalid permission" if self.blockchain.wallet.locked(): raise WalletLocked() if not isinstance(accounts, (list, tuple, set)): accounts = [accounts] for account in accounts: # Now let's actually deal with the accounts if account not in self.signing_accounts: # is the account an instance of public key? if isinstance(account, self.publickey_class): self.appendWif( self.blockchain.wallet.getPrivateKeyForPublicKey(str(account)) ) # ... or should we rather obtain the keys from an account name else: accountObj = self.account_class( account, blockchain_instance=self.blockchain ) required_treshold = accountObj[permission]["weight_threshold"] keys = self._fetchkeys( accountObj, permission, required_treshold=required_treshold ) # If we couldn't find an active key, let's try overwrite it # with an owner key if not keys and permission != "owner": keys.extend( self._fetchkeys( accountObj, "owner", required_treshold=required_treshold ) ) for x in keys: self.appendWif(x[0]) self.signing_accounts.append(account)
def appendSigner(self, accounts, permission): """ Try to obtain the wif key from the wallet by telling which account and permission is supposed to sign the transaction """ assert permission in self.permission_types, "Invalid permission" if self.blockchain.wallet.locked(): raise WalletLocked() if not isinstance(accounts, (list, tuple, set)): accounts = [accounts] for account in accounts: # Now let's actually deal with the accounts if account not in self.signing_accounts: # is the account an instance of public key? if isinstance(account, self.publickey_class): self.appendWif( self.blockchain.wallet.getPrivateKeyForPublicKey(str(account)) ) # ... or should we rather obtain the keys from an account name else: accountObj = self.account_class( account, blockchain_instance=self.blockchain ) required_treshold = accountObj[permission]["weight_threshold"] keys = self._fetchkeys( accountObj, permission, required_treshold=required_treshold ) # If we couldn't find an active key, let's try overwrite it # with an owner key if not keys and permission != "owner": keys.extend( self._fetchkeys( accountObj, "owner", required_treshold=required_treshold ) ) for x in keys: self.appendWif(x[0]) self.signing_accounts.append(account)
[ "Try", "to", "obtain", "the", "wif", "key", "from", "the", "wallet", "by", "telling", "which", "account", "and", "permission", "is", "supposed", "to", "sign", "the", "transaction" ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L278-L317
[ "def", "appendSigner", "(", "self", ",", "accounts", ",", "permission", ")", ":", "assert", "permission", "in", "self", ".", "permission_types", ",", "\"Invalid permission\"", "if", "self", ".", "blockchain", ".", "wallet", ".", "locked", "(", ")", ":", "raise", "WalletLocked", "(", ")", "if", "not", "isinstance", "(", "accounts", ",", "(", "list", ",", "tuple", ",", "set", ")", ")", ":", "accounts", "=", "[", "accounts", "]", "for", "account", "in", "accounts", ":", "# Now let's actually deal with the accounts", "if", "account", "not", "in", "self", ".", "signing_accounts", ":", "# is the account an instance of public key?", "if", "isinstance", "(", "account", ",", "self", ".", "publickey_class", ")", ":", "self", ".", "appendWif", "(", "self", ".", "blockchain", ".", "wallet", ".", "getPrivateKeyForPublicKey", "(", "str", "(", "account", ")", ")", ")", "# ... or should we rather obtain the keys from an account name", "else", ":", "accountObj", "=", "self", ".", "account_class", "(", "account", ",", "blockchain_instance", "=", "self", ".", "blockchain", ")", "required_treshold", "=", "accountObj", "[", "permission", "]", "[", "\"weight_threshold\"", "]", "keys", "=", "self", ".", "_fetchkeys", "(", "accountObj", ",", "permission", ",", "required_treshold", "=", "required_treshold", ")", "# If we couldn't find an active key, let's try overwrite it", "# with an owner key", "if", "not", "keys", "and", "permission", "!=", "\"owner\"", ":", "keys", ".", "extend", "(", "self", ".", "_fetchkeys", "(", "accountObj", ",", "\"owner\"", ",", "required_treshold", "=", "required_treshold", ")", ")", "for", "x", "in", "keys", ":", "self", ".", "appendWif", "(", "x", "[", "0", "]", ")", "self", ".", "signing_accounts", ".", "append", "(", "account", ")" ]
8bb5396bc79998ee424cf3813af478304173f3a6
valid
TransactionBuilder.appendWif
Add a wif that should be used for signing of the transaction.
graphenecommon/transactionbuilder.py
def appendWif(self, wif): """ Add a wif that should be used for signing of the transaction. """ if wif: try: self.privatekey_class(wif) self.wifs.add(wif) except Exception: raise InvalidWifError
def appendWif(self, wif): """ Add a wif that should be used for signing of the transaction. """ if wif: try: self.privatekey_class(wif) self.wifs.add(wif) except Exception: raise InvalidWifError
[ "Add", "a", "wif", "that", "should", "be", "used", "for", "signing", "of", "the", "transaction", "." ]
xeroc/python-graphenelib
python
https://github.com/xeroc/python-graphenelib/blob/8bb5396bc79998ee424cf3813af478304173f3a6/graphenecommon/transactionbuilder.py#L319-L327
[ "def", "appendWif", "(", "self", ",", "wif", ")", ":", "if", "wif", ":", "try", ":", "self", ".", "privatekey_class", "(", "wif", ")", "self", ".", "wifs", ".", "add", "(", "wif", ")", "except", "Exception", ":", "raise", "InvalidWifError" ]
8bb5396bc79998ee424cf3813af478304173f3a6