repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
BrianHicks/emit | emit/router/core.py | Router.regenerate_routes | python | def regenerate_routes(self):
'regenerate the routes after a new route is added'
for destination, origins in self.regexes.items():
# we want only the names that match the destination regexes.
resolved = [
name for name in self.names
if name is not d... | regenerate the routes after a new route is added | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L290-L317 | null | class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages pas... |
BrianHicks/emit | emit/router/core.py | Router.route | python | def route(self, origin, message):
'''\
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass... | \
Using the routing dictionary, dispatch a message to all subscribers
:param origin: name of the origin node
:type origin: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L327-L348 | [
"def resolve_node_modules(self):\n 'import the modules specified in init'\n if not self.resolved_node_modules:\n try:\n self.resolved_node_modules = [\n importlib.import_module(mod, self.node_package)\n for mod in self.node_modules\n ]\n except... | class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages pas... |
BrianHicks/emit | emit/router/core.py | Router.dispatch | python | def dispatch(self, origin, destination, message):
'''\
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass... | \
dispatch a message to a named function
:param destination: destination to dispatch to
:type destination: :py:class:`str`
:param message: message to dispatch
:type message: :py:class:`emit.message.Message` or subclass | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L350-L361 | null | class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages pas... |
BrianHicks/emit | emit/router/core.py | Router.wrap_result | python | def wrap_result(self, name, result):
'''
Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:e... | Wrap a result from a function with it's stated fields
:param name: fields to look up
:type name: :py:class:`str`
:param result: return value from function. Will be converted to tuple.
:type result: anything
:raises: :py:exc:`ValueError` if name has no associated fields
... | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L363-L384 | null | class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages pas... |
BrianHicks/emit | emit/router/core.py | Router.get_name | python | def get_name(self, func):
'''
Get the name to reference a function by
:param func: function to get the name of
:type func: callable
'''
if hasattr(func, 'name'):
return func.name
return '%s.%s' % (
func.__module__,
func.__name... | Get the name to reference a function by
:param func: function to get the name of
:type func: callable | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/core.py#L386-L399 | null | class Router(object):
'A router object. Holds routes and references to functions for dispatch'
def __init__(self, message_class=None, node_modules=None, node_package=None):
'''\
Create a new router object. All parameters are optional.
:param message_class: wrapper class for messages pas... |
BrianHicks/emit | emit/router/celery.py | CeleryRouter.wrap_node | python | def wrap_node(self, node, options):
'''\
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute.
'''
if 'celery_task' in options:
return options['cele... | \
celery registers tasks by decorating them, and so do we, so the user
can pass a celery task and we'll wrap our code with theirs in a nice
package celery can execute. | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/celery.py#L33-L42 | null | class CeleryRouter(Router):
'Router specifically for Celery routing'
def __init__(self, celery_task, *args, **kwargs):
'''\
Specifically route when celery is needed
:param celery_task: celery task to apply to all nodes (can be
overridden in :py:meth:`Router.n... |
BrianHicks/emit | emit/router/rq.py | RQRouter.wrap_node | python | def wrap_node(self, node, options):
'''
we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects.
'''
job_kwargs = {
'queue': options.get('queue', 'default'),
'connection': options.... | we have the option to construct nodes here, so we can use different
queues for nodes without having to have different queue objects. | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/router/rq.py#L28-L40 | null | class RQRouter(Router):
'Router specifically for RQ routing'
def __init__(self, redis_connection, *args, **kwargs):
'''\
Specific routing when using RQ
:param redis_connection: a redis connection to send to all the tasks
(can be overridden in :py:meth:`R... |
BrianHicks/emit | emit/multilang.py | ShellNode.deserialize | python | def deserialize(self, msg):
'deserialize output to a Python object'
self.logger.debug('deserializing %s', msg)
return json.loads(msg) | deserialize output to a Python object | train | https://github.com/BrianHicks/emit/blob/19a86c2392b136c9e857000798ccaa525aa0ed84/emit/multilang.py#L65-L68 | null | class ShellNode(object):
'''\
callable object to wrap communication to a node in another language
to use this, subclass ``ShellNode``, providing "command". Decorate it
however you feel like.
Messages will be passed in on lines in msgpack format. This class expects
similar output: msgpack messa... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/commands.py | commandstr | python | def commandstr(command):
if command == CMD_MESSAGE_ERROR:
msg = "CMD_MESSAGE_ERROR"
elif command == CMD_MESSAGE_LIST:
msg = "CMD_MESSAGE_LIST"
elif command == CMD_MESSAGE_PASSWORD:
msg = "CMD_MESSAGE_PASSWORD"
elif command == CMD_MESSAGE_MP3:
msg = "CMD_MESSAGE_MP3"
e... | Convert command into string. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/commands.py#L13-L33 | null | # coding: utf-8
"""Commands used to communicate between client and server."""
CMD_MESSAGE_ERROR = 0
CMD_MESSAGE_LIST = 1
CMD_MESSAGE_PASSWORD = 2
CMD_MESSAGE_MP3 = 3
CMD_MESSAGE_DELETE = 4
CMD_MESSAGE_VERSION = 5
CMD_MESSAGE_CDR = 6
CMD_MESSAGE_CDR_AVAILABLE = 7
|
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | _build_request | python | def _build_request(request):
msg = bytes([request['cmd']])
if 'dest' in request:
msg += bytes([request['dest']])
else:
msg += b'\0'
if 'sha' in request:
msg += request['sha']
else:
for dummy in range(64):
msg += b'0'
logging.debug("Request (%d): %s", l... | Build message to transfer over the socket from a request. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L28-L41 | null | """asterisk_mbox_client: Client API for Asterisk Mailboxes."""
import sys
import socket
import select
import json
import configparser
import logging
import zlib
import queue
import threading
from distutils.version import StrictVersion
from asterisk_mbox.utils import (PollableQueue, recv_blocking,
... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | main | python | def main():
__async__ = True
logging.basicConfig(format="%(levelname)-10s %(message)s",
level=logging.DEBUG)
if len(sys.argv) != 2:
logging.error("Must specify configuration file")
sys.exit()
config = configparser.ConfigParser()
config.read(sys.argv[1])
... | Show example using the API. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L242-L267 | null | """asterisk_mbox_client: Client API for Asterisk Mailboxes."""
import sys
import socket
import select
import json
import configparser
import logging
import zlib
import queue
import threading
from distutils.version import StrictVersion
from asterisk_mbox.utils import (PollableQueue, recv_blocking,
... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client.start | python | def start(self):
if not self._thread:
logging.info("Starting asterisk mbox thread")
# Ensure signal queue is empty
try:
while True:
self.signal.get(False)
except queue.Empty:
pass
self._thread = threa... | Start thread. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L73-L85 | [
"def get(self, block=True, timeout=None):\n \"\"\"get.\"\"\"\n try:\n item = super().get(block, timeout)\n self._getsocket.recv(1)\n return item\n except queue.Empty:\n raise queue.Empty\n"
] | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client.stop | python | def stop(self):
if self._thread:
self.signal.put("Stop")
self._thread.join()
if self._soc:
self._soc.shutdown()
self._soc.close()
self._thread = None | Stop thread. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L87-L95 | null | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client._connect | python | def _connect(self):
self._soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._soc.connect((self._ipaddr, self._port))
self._soc.send(_build_request({'cmd': cmd.CMD_MESSAGE_PASSWORD,
'sha': self._password})) | Connect to server. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L97-L102 | null | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client._recv_msg | python | def _recv_msg(self):
command = ord(recv_blocking(self._soc, 1))
msglen = recv_blocking(self._soc, 4)
msglen = ((msglen[0] << 24) + (msglen[1] << 16) +
(msglen[2] << 8) + msglen[3])
msg = recv_blocking(self._soc, msglen)
return command, msg | Read a message from the server. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L104-L111 | null | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client._loop | python | def _loop(self):
request = {}
connected = False
while True:
timeout = None
sockets = [self.request_queue, self.signal]
if not connected:
try:
self._clear_request(request)
self._connect()
... | Handle data. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L146-L196 | null | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client.mp3 | python | def mp3(self, sha, **kwargs):
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_MP3,
'sha': _get_bytes(sha)}, **kwargs) | Get raw MP3 of a message. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L216-L219 | [
"def _get_bytes(data):\n \"\"\"Ensure data is type 'bytes'.\"\"\"\n if isinstance(data, str):\n return data.encode('utf-8')\n return data\n",
"def _queue_msg(self, item, **kwargs):\n if not self._thread:\n raise ServerError(\"Client not running\")\n if not self._callback or kwargs.get... | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client.delete | python | def delete(self, sha, **kwargs):
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_DELETE,
'sha': _get_bytes(sha)}, **kwargs) | Delete a message. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L221-L224 | [
"def _get_bytes(data):\n \"\"\"Ensure data is type 'bytes'.\"\"\"\n if isinstance(data, str):\n return data.encode('utf-8')\n return data\n",
"def _queue_msg(self, item, **kwargs):\n if not self._thread:\n raise ServerError(\"Client not running\")\n if not self._callback or kwargs.get... | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/__init__.py | Client.get_cdr | python | def get_cdr(self, start=0, count=-1, **kwargs):
sha = encode_to_sha("{:d},{:d}".format(start, count))
return self._queue_msg({'cmd': cmd.CMD_MESSAGE_CDR,
'sha': sha}, **kwargs) | Request range of CDR messages | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/__init__.py#L231-L235 | [
"def encode_to_sha(msg):\n \"\"\"coerce numeric list inst sha-looking bytearray\"\"\"\n if isinstance(msg, str):\n msg = msg.encode('utf-8')\n return (codecs.encode(msg, \"hex_codec\") + (b'00' * 32))[:64]\n",
"def _queue_msg(self, item, **kwargs):\n if not self._thread:\n raise ServerEr... | class Client:
"""asterisk_mbox client."""
def __init__(self, ipaddr, port, password, callback=None, **kwargs):
"""constructor."""
self._ipaddr = ipaddr
self._port = port
self._password = encode_password(password).encode('utf-8')
self._callback = callback
self._so... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | recv_blocking | python | def recv_blocking(conn, msglen):
msg = b''
while len(msg) < msglen:
maxlen = msglen-len(msg)
if maxlen > 4096:
maxlen = 4096
tmpmsg = conn.recv(maxlen)
if not tmpmsg:
raise RuntimeError("socket connection broken")
msg += tmpmsg
logging.debu... | Recieve data until msglen bytes have been received. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L52-L65 | null | """Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | compare_password | python | def compare_password(expected, actual):
if expected == actual:
return True, "OK"
msg = []
ver_exp = expected[-8:].rstrip()
ver_act = actual[-8:].rstrip()
if expected[:-8] != actual[:-8]:
msg.append("Password mismatch")
if ver_exp != ver_act:
msg.append("asterisk_mbox ver... | Compare two 64byte encoded passwords. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L74-L87 | null | """Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | encode_to_sha | python | def encode_to_sha(msg):
if isinstance(msg, str):
msg = msg.encode('utf-8')
return (codecs.encode(msg, "hex_codec") + (b'00' * 32))[:64] | coerce numeric list inst sha-looking bytearray | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L90-L94 | null | """Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | decode_from_sha | python | def decode_from_sha(sha):
if isinstance(sha, str):
sha = sha.encode('utf-8')
return codecs.decode(re.sub(rb'(00)*$', b'', sha), "hex_codec") | convert coerced sha back into numeric list | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L97-L101 | null | """Utility classes for use in the asterisk_mbox."""
import queue
import os
import socket
import logging
import hashlib
import re
import codecs
__version__ = "0.5.0"
class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | PollableQueue.put | python | def put(self, item, block=True, timeout=None):
super().put(item, block, timeout)
self._putsocket.send(b'x') | put. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L37-L40 | null | class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
... |
PhracturedBlue/asterisk_mbox | asterisk_mbox/utils.py | PollableQueue.get | python | def get(self, block=True, timeout=None):
try:
item = super().get(block, timeout)
self._getsocket.recv(1)
return item
except queue.Empty:
raise queue.Empty | get. | train | https://github.com/PhracturedBlue/asterisk_mbox/blob/275de1e71ed05c6acff1a5fa87f754f4d385a372/asterisk_mbox/utils.py#L42-L49 | null | class PollableQueue(queue.Queue):
"""Queue which allows using select."""
def __init__(self):
"""Constructor."""
super().__init__()
# Create a pair of connected sockets
if os.name == 'posix':
self._putsocket, self._getsocket = socket.socketpair()
else:
... |
mjirik/sed3 | sed3/sed3.py | show_slices | python | def show_slices(data3d, contour=None, seeds=None, axis=0, slice_step=None,
shape=None, show=True,
flipH=False, flipV=False,
first_slice_offset=0,
first_slice_offset_to_see_seed_with_label=None,
slice_number=None
):
... | Show slices as tiled image
:param data3d: Input data
:param contour: Data for contouring
:param seeds: Seed data
:param axis: Axis for sliceing
:param slice_step: Show each "slice_step"-th slice, can be float
:param shape: tuple(vertical_tiles_number, horisontal_tiles_number), set shape ... | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L607-L700 | [
"def _import_data(data, axis, slice_step, first_slice_offset=0):\n \"\"\"\n import ndarray or SimpleITK data\n \"\"\"\n try:\n import SimpleITK as sitk\n if type(data) is sitk.SimpleITK.Image:\n data = sitk.GetArrayFromImage(data)\n except:\n pass\n\n data = __selec... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | __get_slice | python | def __get_slice(data, slice_number, axis=0, flipH=False, flipV=False):
"""
:param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return:
"""
if axis == 0:
data2d = data[slice_number, :, :]
elif axis == 1:
... | :param data:
:param slice_number:
:param axis:
:param flipV: vertical flip
:param flipH: horizontal flip
:return: | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L708-L735 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | __put_slice_in_slim | python | def __put_slice_in_slim(slim, dataim, sh, i):
"""
put one small slice as a tile in a big image
"""
a, b = np.unravel_index(int(i), sh)
st0 = int(dataim.shape[0] * a)
st1 = int(dataim.shape[1] * b)
sp0 = int(st0 + dataim.shape[0])
sp1 = int(st1 + dataim.shape[1])
slim[
... | put one small slice as a tile in a big image | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L738-L754 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | show_slice | python | def show_slice(data2d, contour2d=None, seeds2d=None):
"""
:param data2d:
:param contour2d:
:param seeds2d:
:return:
"""
import copy as cp
# Show results
colormap = cp.copy(plt.cm.get_cmap('brg'))
colormap._init()
colormap._lut[:1:, 3] = 0
plt.imshow(da... | :param data2d:
:param contour2d:
:param seeds2d:
:return: | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L768-L821 | [
"def sigmoid(x, x0, k):\n y = 1 / (1 + np.exp(-k*(x-x0)))\n return y\n"
] | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | _import_data | python | def _import_data(data, axis, slice_step, first_slice_offset=0):
"""
import ndarray or SimpleITK data
"""
try:
import SimpleITK as sitk
if type(data) is sitk.SimpleITK.Image:
data = sitk.GetArrayFromImage(data)
except:
pass
data = __select_slices(da... | import ndarray or SimpleITK data | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L845-L857 | [
"def __select_slices(data, axis, slice_step, first_slice_offset=0):\n if data is None:\n return None\n\n inds = np.floor(np.arange(first_slice_offset, data.shape[axis], slice_step)).astype(np.int)\n # import ipdb\n # ipdb.set_trace()\n # logger.warning(\"select slices\")\n\n if axis == 0:\n... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | generate_data | python | def generate_data(shp=[16, 20, 24]):
""" Generating data """
x = np.ones(shp)
# inserting box
x[4:-4, 6:-2, 1:-6] = -1
x_noisy = x + np.random.normal(0, 0.6, size=x.shape)
return x_noisy | Generating data | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1020-L1027 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | index_to_coords | python | def index_to_coords(index, shape):
'''convert index to coordinates given the shape'''
coords = []
for i in xrange(1, len(shape)):
divisor = int(np.product(shape[i:]))
value = index // divisor
coords.append(value)
index -= value * divisor
coords.append(index)
... | convert index to coordinates given the shape | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1115-L1124 | null | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | slices | python | def slices(img, shape=[3, 4]):
"""
create tiled image with multiple slices
:param img:
:param shape:
:return:
"""
sh = np.asarray(shape)
i_max = np.prod(sh)
allimg = np.zeros(img.shape[-2:] * sh)
for i in range(0, i_max):
# i = 0
islice = round((img.... | create tiled image with multiple slices
:param img:
:param shape:
:return: | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1130-L1154 | [
"def index_to_coords(index, shape):\n '''convert index to coordinates given the shape'''\n coords = []\n for i in xrange(1, len(shape)):\n divisor = int(np.product(shape[i:]))\n value = index // divisor\n coords.append(value)\n index -= value * divisor\n coords.append(index)\... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | sed2 | python | def sed2(img, contour=None, shape=[3, 4]):
"""
plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return:
"""
"""
:param img:
:param contour:
:param shape:
:return:
"""
plt.imshow(slices(img, shape), cmap='gray')
... | plot tiled image of multiple slices
:param img:
:param contour:
:param shape:
:return: | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L1159-L1177 | [
"def slices(img, shape=[3, 4]):\n \"\"\"\n create tiled image with multiple slices\n :param img:\n :param shape:\n :return:\n \"\"\"\n sh = np.asarray(shape)\n i_max = np.prod(sh)\n allimg = np.zeros(img.shape[-2:] * sh)\n\n for i in range(0, i_max):\n # i = 0\n islice = ... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import sys
import scipy.io
import math
import copy
import argparse
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.widgets import Slider, Button
import traceback
import logging
logger = logging.getLogger(__name__)
#... |
mjirik/sed3 | sed3/sed3.py | sed3.set_window | python | def set_window(self, windowC, windowW):
"""
Sets visualization window
:param windowC: window center
:param windowW: window width
:return:
"""
if not (windowW and windowC):
windowW = np.max(self.img) - np.min(self.img)
windowC = (np... | Sets visualization window
:param windowC: window center
:param windowW: window width
:return: | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L249-L263 | null | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
mjirik/sed3 | sed3/sed3.py | sed3.rotate_to_zaxis | python | def rotate_to_zaxis(self, new_zaxis):
"""
rotate image to selected axis
:param new_zaxis:
:return:
"""
img = self._rotate_end(self.img, self.zaxis)
seeds = self._rotate_end(self.seeds, self.zaxis)
contour = self._rotate_end(self.contour, self.zax... | rotate image to selected axis
:param new_zaxis:
:return: | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L297-L328 | [
"def _rotate_start(self, data, zaxis):\n if data is not None:\n if zaxis == 0:\n tr =(1, 2, 0)\n data = np.transpose(data, tr)\n vs = self.actual_voxelsize\n if self.actual_voxelsize is not None:\n self.actual_voxelsize = [vs[tr[0]], vs[tr[1]], vs... | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
mjirik/sed3 | sed3/sed3.py | sed3.__flip | python | def __flip(self, sliceimg):
"""
Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp
"""
if self.flipH:
sliceimg = sliceimg[:, -1:0:-1]
if self.flipV:
sliceimg = sliceimg [-1:0:-1,:]
... | Flip if asked in self.flipV or self.flipH
:param sliceimg: one image slice
:return: flipp | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L386-L398 | null | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
mjirik/sed3 | sed3/sed3.py | sed3.on_scroll | python | def on_scroll(self, event):
''' mouse wheel is used for setting slider value'''
if event.button == 'up':
self.next_slice()
if event.button == 'down':
self.prev_slice()
self.actual_slice_slider.set_val(self.actual_slice) | mouse wheel is used for setting slider value | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L517-L523 | [
"def next_slice(self):\n self.actual_slice = self.actual_slice + 1\n if self.actual_slice >= self.imgshape[2]:\n self.actual_slice = 0\n",
"def prev_slice(self):\n self.actual_slice = self.actual_slice - 1\n if self.actual_slice < 0:\n self.actual_slice = self.imgshape[2] - 1\n"
] | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
mjirik/sed3 | sed3/sed3.py | sed3.on_press | python | def on_press(self, event):
'on but-ton press we will see if the mouse is over us and store data'
if event.inaxes != self.ax:
return
# contains, attrd = self.rect.contains(event)
# if not contains: return
# print('event contains', self.rect.xy)
# x0, y0 ... | on but-ton press we will see if the mouse is over us and store data | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L529-L537 | null | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
mjirik/sed3 | sed3/sed3.py | sed3.on_motion | python | def on_motion(self, event):
'on motion we will move the rect if the mouse is over us'
if self.press is None:
return
if event.inaxes != self.ax:
return
# print(event.inaxes)
x0, y0, btn = self.press
x0.append(event.xdata)
y0.app... | on motion we will move the rect if the mouse is over us | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L540-L551 | null | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
mjirik/sed3 | sed3/sed3.py | sed3.on_release | python | def on_release(self, event):
'on release we reset the press data'
if self.press is None:
return
# print(self.press)
x0, y0, btn = self.press
if btn == 1:
color = 'r'
elif btn == 2:
color = 'b' # noqa
# plt.axes(self... | on release we reset the press data | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L553-L573 | [
"def update_slice(self):\n # TODO tohle je tu kvuli contour, neumim ji odstranit jinak\n self.ax.cla()\n\n self.draw_slice()\n",
"def set_seeds(self, px, py, pz, value=1, voxelsizemm=[1, 1, 1],\n cursorsizemm=[1, 1, 1]):\n assert len(px) == len(\n py), 'px and py describes a point,... | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
mjirik/sed3 | sed3/sed3.py | sed3.get_seed_sub | python | def get_seed_sub(self, label):
""" Return list of all seeds with specific label
"""
sx, sy, sz = np.nonzero(self.seeds == label)
return sx, sy, sz | Return list of all seeds with specific label | train | https://github.com/mjirik/sed3/blob/270c12836218fd2fa2fe192c6b6fef882322c173/sed3/sed3.py#L595-L600 | null | class sed3:
""" Viewer and seed editor for 2D and 3D data.
sed3(img, ...)
img: 2D or 3D grayscale data
voxelsizemm: size of voxel, default is [1, 1, 1]
initslice: 0
colorbar: True/False, default is True
cmap: colormap
zaxis: axis with slice numbers
show: (True/False) automatic call... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | create_hlk_sw16_connection | python | async def create_hlk_sw16_connection(port=None, host=None,
disconnect_callback=None,
reconnect_callback=None, loop=None,
logger=None, timeout=None,
reconnect_interval=None)... | Create HLK-SW16 Client class. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L292-L305 | [
"async def setup(self):\n \"\"\"Set up the connection with automatic retry.\"\"\"\n while True:\n fut = self.loop.create_connection(\n lambda: SW16Protocol(\n self,\n disconnect_callback=self.handle_disconnect_callback,\n loop=self.loop, logger=se... | """HLK-SW16 Protocol Support."""
import asyncio
from collections import deque
import logging
import codecs
import binascii
class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=No... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._reset_timeout | python | def _reset_timeout(self):
if self._timeout:
self._timeout.cancel()
self._timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | Reset timeout for date keep alive. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L30-L35 | null | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.reset_cmd_timeout | python | def reset_cmd_timeout(self):
if self._cmd_timeout:
self._cmd_timeout.cancel()
self._cmd_timeout = self.loop.call_later(self.client.timeout,
self.transport.close) | Reset timeout for command execution. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L37-L42 | null | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._handle_lines | python | def _handle_lines(self):
while b'\xdd' in self._buffer:
linebuf, self._buffer = self._buffer.rsplit(b'\xdd', 1)
line = linebuf[-19:]
self._buffer += linebuf[:-19]
if self._valid_packet(line):
self._handle_raw_packet(line)
else:
... | Assemble incoming data into per-line packets. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L49-L59 | [
"def _valid_packet(raw_packet):\n \"\"\"Validate incoming packet.\"\"\"\n if raw_packet[0:1] != b'\\xcc':\n return False\n if len(raw_packet) != 19:\n return False\n checksum = 0\n for i in range(1, 17):\n checksum += raw_packet[i]\n if checksum != raw_packet[18]:\n ret... | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._valid_packet | python | def _valid_packet(raw_packet):
if raw_packet[0:1] != b'\xcc':
return False
if len(raw_packet) != 19:
return False
checksum = 0
for i in range(1, 17):
checksum += raw_packet[i]
if checksum != raw_packet[18]:
return False
retu... | Validate incoming packet. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L62-L73 | null | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol._handle_raw_packet | python | def _handle_raw_packet(self, raw_packet):
if raw_packet[1:2] == b'\x1f':
self._reset_timeout()
year = raw_packet[2]
month = raw_packet[3]
day = raw_packet[4]
hour = raw_packet[5]
minute = raw_packet[6]
sec = raw_packet[7]
... | Parse incoming packet. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L75-L125 | null | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.send_packet | python | def send_packet(self):
waiter, packet = self.client.waiters.popleft()
self.logger.debug('sending packet: %s', binascii.hexlify(packet))
self.client.active_transaction = waiter
self.client.in_transaction = True
self.client.active_packet = packet
self.reset_cmd_timeout()
... | Write next packet in send queue. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L127-L135 | [
"def reset_cmd_timeout(self):\n \"\"\"Reset timeout for command execution.\"\"\"\n if self._cmd_timeout:\n self._cmd_timeout.cancel()\n self._cmd_timeout = self.loop.call_later(self.client.timeout,\n self.transport.close)\n"
] | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.format_packet | python | def format_packet(command):
frame_header = b"\xaa"
verify = b"\x0b"
send_delim = b"\xbb"
return frame_header + command.ljust(17, b"\x00") + verify + send_delim | Format packet to be sent. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L138-L143 | null | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Protocol.connection_lost | python | def connection_lost(self, exc):
if exc:
self.logger.error('disconnected due to error')
else:
self.logger.info('disconnected because of close/abort.')
if self.disconnect_callback:
asyncio.ensure_future(self.disconnect_callback(), loop=self.loop) | Log when connection is closed, if needed call callback. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L145-L152 | null | class SW16Protocol(asyncio.Protocol):
"""HLK-SW16 relay control protocol."""
transport = None # type: asyncio.Transport
def __init__(self, client, disconnect_callback=None, loop=None,
logger=None):
"""Initialize the HLK-SW16 protocol."""
self.client = client
self.... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.setup | python | async def setup(self):
while True:
fut = self.loop.create_connection(
lambda: SW16Protocol(
self,
disconnect_callback=self.handle_disconnect_callback,
loop=self.loop, logger=self.logger),
host=self.host,
... | Set up the connection with automatic retry. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L188-L211 | null | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.stop | python | def stop(self):
self.reconnect = False
self.logger.debug("Shutting down.")
if self.transport:
self.transport.close() | Shut down transport. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L213-L218 | null | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.handle_disconnect_callback | python | async def handle_disconnect_callback(self):
self.is_connected = False
if self.disconnect_callback:
self.disconnect_callback()
if self.reconnect:
self.logger.debug("Protocol disconnected...reconnecting")
await self.setup()
self.protocol.reset_cmd_ti... | Reconnect automatically unless stopping. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L220-L233 | [
"async def setup(self):\n \"\"\"Set up the connection with automatic retry.\"\"\"\n while True:\n fut = self.loop.create_connection(\n lambda: SW16Protocol(\n self,\n disconnect_callback=self.handle_disconnect_callback,\n loop=self.loop, logger=se... | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.register_status_callback | python | def register_status_callback(self, callback, switch):
if self.status_callbacks.get(switch, None) is None:
self.status_callbacks[switch] = []
self.status_callbacks[switch].append(callback) | Register a callback which will fire when state changes. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L235-L239 | null | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client._send | python | def _send(self, packet):
fut = self.loop.create_future()
self.waiters.append((fut, packet))
if self.waiters and self.in_transaction is False:
self.protocol.send_packet()
return fut | Add packet to send queue. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L241-L247 | null | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.turn_on | python | async def turn_on(self, switch=None):
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x01")
else:
packet = self.protocol.format_packet(b"\x0a")
states = await self._send(pack... | Turn on relay. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L249-L257 | [
"def _send(self, packet):\n \"\"\"Add packet to send queue.\"\"\"\n fut = self.loop.create_future()\n self.waiters.append((fut, packet))\n if self.waiters and self.in_transaction is False:\n self.protocol.send_packet()\n return fut\n"
] | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.turn_off | python | async def turn_off(self, switch=None):
if switch is not None:
switch = codecs.decode(switch.rjust(2, '0'), 'hex')
packet = self.protocol.format_packet(b"\x10" + switch + b"\x02")
else:
packet = self.protocol.format_packet(b"\x0b")
states = await self._send(pac... | Turn off relay. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L259-L267 | [
"def _send(self, packet):\n \"\"\"Add packet to send queue.\"\"\"\n fut = self.loop.create_future()\n self.waiters.append((fut, packet))\n if self.waiters and self.in_transaction is False:\n self.protocol.send_packet()\n return fut\n"
] | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
jameshilliard/hlk-sw16 | hlk_sw16/protocol.py | SW16Client.status | python | async def status(self, switch=None):
if switch is not None:
if self.waiters or self.in_transaction:
fut = self.loop.create_future()
self.status_waiters.append(fut)
states = await fut
state = states[switch]
else:
... | Get current relay status. | train | https://github.com/jameshilliard/hlk-sw16/blob/4f0c5a7b76b42167f4dc9d2aa6312c7518a8cd56/hlk_sw16/protocol.py#L269-L289 | [
"def _send(self, packet):\n \"\"\"Add packet to send queue.\"\"\"\n fut = self.loop.create_future()\n self.waiters.append((fut, packet))\n if self.waiters and self.in_transaction is False:\n self.protocol.send_packet()\n return fut\n"
] | class SW16Client:
"""HLK-SW16 client wrapper class."""
def __init__(self, host, port=8080,
disconnect_callback=None, reconnect_callback=None,
loop=None, logger=None, timeout=10, reconnect_interval=10):
"""Initialize the HLK-SW16 client wrapper."""
if loop:
... |
bibanon/BASC-py4chan | basc_py4chan/util.py | clean_comment_body | python | def clean_comment_body(body):
body = _parser.unescape(body)
body = re.sub(r'<a [^>]+>(.+?)</a>', r'\1', body)
body = body.replace('<br>', '\n')
body = re.sub(r'<.+?>', '', body)
return body | Returns given comment HTML as plaintext.
Converts all HTML tags and entities within 4chan comments
into human-readable text equivalents. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/util.py#L16-L26 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Utility functions."""
import re
# HTML parser was renamed in python 3.x
try:
from html.parser import HTMLParser
except ImportError:
from HTMLParser import HTMLParser
_parser = HTMLParser()
|
bibanon/BASC-py4chan | basc_py4chan/board.py | get_boards | python | def get_boards(board_name_list, *args, **kwargs):
if isinstance(board_name_list, basestring):
board_name_list = board_name_list.split()
return [Board(name, *args, **kwargs) for name in board_name_list] | Given a list of boards, return :class:`basc_py4chan.Board` objects.
Args:
board_name_list (list): List of board names to get, eg: ['b', 'tg']
Returns:
dict of :class:`basc_py4chan.Board`: Requested boards. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L43-L54 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from . import __version__
from .thread import Thread
from .url import Url
# cached metadata for boards
_metadata = {}
# compatibility layer for Python2's `basestring` variable
# http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/
try:
un... |
bibanon/BASC-py4chan | basc_py4chan/board.py | get_all_boards | python | def get_all_boards(*args, **kwargs):
# Use https based on how the Board class instances are to be instantiated
https = kwargs.get('https', args[1] if len(args) > 1 else False)
# Dummy URL generator, only used to generate the board list which doesn't
# require a valid board name
url_generator = Url(... | Returns every board on 4chan.
Returns:
dict of :class:`basc_py4chan.Board`: All boards. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L57-L70 | [
"def get_boards(board_name_list, *args, **kwargs):\n \"\"\"Given a list of boards, return :class:`basc_py4chan.Board` objects.\n\n Args:\n board_name_list (list): List of board names to get, eg: ['b', 'tg']\n\n Returns:\n dict of :class:`basc_py4chan.Board`: Requested boards.\n \"\"\"\n ... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from . import __version__
from .thread import Thread
from .url import Url
# cached metadata for boards
_metadata = {}
# compatibility layer for Python2's `basestring` variable
# http://www.rfk.id.au/blog/entry/preparing-pyenchant-for-python-3/
try:
un... |
bibanon/BASC-py4chan | basc_py4chan/board.py | Board.get_thread | python | def get_thread(self, thread_id, update_if_cached=True, raise_404=False):
# see if already cached
cached_thread = self._thread_cache.get(thread_id)
if cached_thread:
if update_if_cached:
cached_thread.update()
return cached_thread
res = self._reque... | Get a thread from 4chan via 4chan API.
Args:
thread_id (int): Thread ID
update_if_cached (bool): Whether the thread should be updated if it's already in our cache
raise_404 (bool): Raise an Exception if thread has 404'd
Returns:
:class:`basc_py4chan.Thre... | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L110-L143 | [
"def _from_request(cls, board, res, id):\n if res.status_code == 404:\n return None\n\n res.raise_for_status()\n\n return cls._from_json(res.json(), board, id, res.headers['Last-Modified'])\n",
"def thread_api_url(self, thread_id):\n return self.URL['api']['thread'].format(\n board=self.... | class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is works... |
bibanon/BASC-py4chan | basc_py4chan/board.py | Board.thread_exists | python | def thread_exists(self, thread_id):
return self._requests_session.head(
self._url.thread_api_url(
thread_id=thread_id
)
).ok | Check if a thread exists or has 404'd.
Args:
thread_id (int): Thread ID
Returns:
bool: Whether the given thread exists on this board. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L145-L158 | null | class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is works... |
bibanon/BASC-py4chan | basc_py4chan/board.py | Board.get_threads | python | def get_threads(self, page=1):
url = self._url.page_url(page)
return self._request_threads(url) | Returns all threads on a certain page.
Gets a list of Thread objects for every thread on the given page. If a thread is
already in our cache, the cached version is returned and thread.want_update is
set to True on the specific thread object.
Pages on 4chan are indexed from 1 onwards.
... | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L192-L208 | [
"def _request_threads(self, url):\n json = self._get_json(url)\n\n if url == self._url.catalog():\n thread_list = self._catalog_to_threads(json)\n else:\n thread_list = json['threads']\n\n threads = []\n for thread_json in thread_list:\n id = thread_json['posts'][0]['no']\n ... | class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is works... |
bibanon/BASC-py4chan | basc_py4chan/board.py | Board.get_all_thread_ids | python | def get_all_thread_ids(self):
json = self._get_json(self._url.thread_list())
return [thread['no'] for page in json for thread in page['threads']] | Return the ID of every thread on this board.
Returns:
list of ints: List of IDs of every thread on this board. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L210-L217 | [
"def _get_json(self, url):\n res = self._requests_session.get(url)\n res.raise_for_status()\n return res.json()\n",
"def thread_list(self):\n return self.URL['listing']['thread_list'].format(\n board=self._board_name\n )\n"
] | class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is works... |
bibanon/BASC-py4chan | basc_py4chan/board.py | Board.get_all_threads | python | def get_all_threads(self, expand=False):
if not expand:
return self._request_threads(self._url.catalog())
thread_ids = self.get_all_thread_ids()
threads = [self.get_thread(id, raise_404=False) for id in thread_ids]
return filter(None, threads) | Return every thread on this board.
If not expanded, result is same as get_threads run across all board pages,
with last 3-5 replies included.
Uses the catalog when not expanding, and uses the flat thread ID listing
at /{board}/threads.json when expanding for more efficient resource usa... | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L219-L243 | [
"def _request_threads(self, url):\n json = self._get_json(url)\n\n if url == self._url.catalog():\n thread_list = self._catalog_to_threads(json)\n else:\n thread_list = json['threads']\n\n threads = []\n for thread_json in thread_list:\n id = thread_json['posts'][0]['no']\n ... | class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is works... |
bibanon/BASC-py4chan | basc_py4chan/board.py | Board.refresh_cache | python | def refresh_cache(self, if_want_update=False):
for thread in tuple(self._thread_cache.values()):
if if_want_update:
if not thread.want_update:
continue
thread.update() | Update all threads currently stored in our cache. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/board.py#L245-L251 | null | class Board(object):
"""Represents a 4chan board.
Attributes:
name (str): Name of this board, such as ``tg`` or ``k``.
name (string): Name of the board, such as "tg" or "etc".
title (string): Board title, such as "Animu and Mango".
is_worksafe (bool): Whether this board is works... |
bibanon/BASC-py4chan | examples/example6-download-thread.py | download_file | python | def download_file(local_filename, url, clobber=False):
dir_name = os.path.dirname(local_filename)
mkdirs(dir_name)
if clobber or not os.path.exists(local_filename):
i = requests.get(url)
# if not exists
if i.status_code == 404:
print('Failed to download file:', local_fi... | Download the given file. Clobber overwrites file if exists. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/examples/example6-download-thread.py#L14-L33 | [
"def mkdirs(path):\n \"\"\"Make directory, if it doesn't exist.\"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n"
] | # example6-download-thread.py - download json and all full-size images from a thread
from __future__ import print_function
import basc_py4chan
import sys
import os
import requests
import json
def mkdirs(path):
"""Make directory, if it doesn't exist."""
if not os.path.exists(path):
os.makedirs(path)
d... |
bibanon/BASC-py4chan | examples/example6-download-thread.py | download_json | python | def download_json(local_filename, url, clobber=False):
with open(local_filename, 'w') as json_file:
json_file.write(json.dumps(requests.get(url).json(), sort_keys=True, indent=2, separators=(',', ': '))) | Download the given JSON file, and pretty-print before we output it. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/examples/example6-download-thread.py#L35-L38 | null | # example6-download-thread.py - download json and all full-size images from a thread
from __future__ import print_function
import basc_py4chan
import sys
import os
import requests
import json
def mkdirs(path):
"""Make directory, if it doesn't exist."""
if not os.path.exists(path):
os.makedirs(path)
de... |
bibanon/BASC-py4chan | basc_py4chan/thread.py | Thread.files | python | def files(self):
if self.topic.has_file:
yield self.topic.file.file_url
for reply in self.replies:
if reply.has_file:
yield reply.file.file_url | Returns the URLs of all files attached to posts in the thread. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L105-L111 | null | class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit... |
bibanon/BASC-py4chan | basc_py4chan/thread.py | Thread.thumbs | python | def thumbs(self):
if self.topic.has_file:
yield self.topic.file.thumbnail_url
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_url | Returns the URLs of all thumbnails in the thread. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L113-L119 | null | class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit... |
bibanon/BASC-py4chan | basc_py4chan/thread.py | Thread.filenames | python | def filenames(self):
if self.topic.has_file:
yield self.topic.file.filename
for reply in self.replies:
if reply.has_file:
yield reply.file.filename | Returns the filenames of all files attached to posts in the thread. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L121-L127 | null | class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit... |
bibanon/BASC-py4chan | basc_py4chan/thread.py | Thread.thumbnames | python | def thumbnames(self):
if self.topic.has_file:
yield self.topic.file.thumbnail_fname
for reply in self.replies:
if reply.has_file:
yield reply.file.thumbnail_fname | Returns the filenames of all thumbnails in the thread. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L129-L135 | null | class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit... |
bibanon/BASC-py4chan | basc_py4chan/thread.py | Thread.file_objects | python | def file_objects(self):
if self.topic.has_file:
yield self.topic.file
for reply in self.replies:
if reply.has_file:
yield reply.file | Returns the :class:`basc_py4chan.File` objects of all files attached to posts in the thread. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L137-L143 | null | class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit... |
bibanon/BASC-py4chan | basc_py4chan/thread.py | Thread.update | python | def update(self, force=False):
# The thread has already 404'ed, this function shouldn't do anything anymore.
if self.is_404 and not force:
return 0
if self._last_modified:
headers = {'If-Modified-Since': self._last_modified}
else:
headers = None
... | Fetch new posts from the server.
Arguments:
force (bool): Force a thread update, even if thread has 404'd.
Returns:
int: How many new posts have been fetched. | train | https://github.com/bibanon/BASC-py4chan/blob/88e4866d73853e1025e549fbbe9744e750522359/basc_py4chan/thread.py#L145-L214 | null | class Thread(object):
"""Represents a 4chan thread.
Attributes:
closed (bool): Whether the thread has been closed.
sticky (bool): Whether this thread is a 'sticky'.
archived (bool): Whether the thread has been archived.
bumplimit (bool): Whether the thread has hit the bump limit... |
hfaran/progressive | progressive/examples.py | simple | python | def simple():
MAX_VALUE = 100
# Create our test progress bar
bar = Bar(max_value=MAX_VALUE, fallback=True)
bar.cursor.clear_lines(2)
# Before beginning to draw our bars, we save the position
# of our cursor so we can restore back to this position before writing
# the next time.
ba... | Simple example using just the Bar class
This example is intended to show usage of the Bar class at the lowest
level. | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/examples.py#L16-L37 | [
"def draw(self, value, newline=True, flush=True):\n \"\"\"Draw the progress bar\n\n :type value: int\n :param value: Progress value relative to ``self.max_value``\n :type newline: bool\n :param newline: If this is set, a newline will be written after drawing\n \"\"\"\n # This is essentially w... | # -*- coding: utf-8 -*-
"""Examples
Usage:
`python -c "from progressive.examples import *; tree()"` as an example
"""
import random
from time import sleep
from blessings import Terminal
from progressive.bar import Bar
from progressive.tree import ProgressTree, Value, BarDescriptor
def tree():
"""Example showi... |
hfaran/progressive | progressive/examples.py | tree | python | def tree():
#############
# Test data #
#############
# For this example, we're obviously going to be feeding fictitious data
# to ProgressTree, so here it is
leaf_values = [Value(0) for i in range(6)]
bd_defaults = dict(type=Bar, kwargs=dict(max_value=10))
test_d = {
"Warp ... | Example showing tree progress view | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/examples.py#L40-L111 | [
"def restore(self):\n \"\"\"Restores cursor to the previously saved location\n\n Cursor position will only be restored IF it was previously saved\n by this instance (and not by any external force)\n \"\"\"\n if self._saved:\n self.write(self.term.restore)\n",
"def draw(self, tree, bar_de... | # -*- coding: utf-8 -*-
"""Examples
Usage:
`python -c "from progressive.examples import *; tree()"` as an example
"""
import random
from time import sleep
from blessings import Terminal
from progressive.bar import Bar
from progressive.tree import ProgressTree, Value, BarDescriptor
def simple():
"""Simple examp... |
hfaran/progressive | progressive/tree.py | ProgressTree.draw | python | def draw(self, tree, bar_desc=None, save_cursor=True, flush=True):
if save_cursor:
self.cursor.save()
tree = deepcopy(tree)
# TODO: Automatically collapse hierarchy so something
# will always be displayable (well, unless the top-level)
# contains too many to disp... | Draw ``tree`` to the terminal
:type tree: dict
:param tree: ``tree`` should be a tree representing a hierarchy; each
key should be a string describing that hierarchy level and value
should also be ``dict`` except for leaves which should be
``BarDescriptors``. See ``... | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L73-L109 | [
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n",
"def save(self):\n \"\"\"Saves current cursor position, so that it can be restored later\"\"\"\n self.write(self.te... | class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between... |
hfaran/progressive | progressive/tree.py | ProgressTree.make_room | python | def make_room(self, tree):
lines_req = self.lines_required(tree)
self.cursor.clear_lines(lines_req) | Clear lines in terminal below current cursor position as required
This is important to do before drawing to ensure sufficient
room at the bottom of your terminal.
:type tree: dict
:param tree: tree as described in ``BarDescriptor`` | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L111-L121 | [
"def clear_lines(self, num_lines=0):\n for i in range(num_lines):\n self.write(self.term.clear_eol)\n self.write(self.term.move_down)\n for i in range(num_lines):\n self.write(self.term.move_up)\n",
"def lines_required(self, tree, count=0):\n \"\"\"Calculate number of lines required ... | class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between... |
hfaran/progressive | progressive/tree.py | ProgressTree.lines_required | python | def lines_required(self, tree, count=0):
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
return sum(self.lines_required(v, count=count)
for v in tree.values()) + 2
elif isinstance(tree, BarDescriptor):
if tre... | Calculate number of lines required to draw ``tree`` | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L123-L135 | null | class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between... |
hfaran/progressive | progressive/tree.py | ProgressTree._calculate_values | python | def _calculate_values(self, tree, bar_d):
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
# Calculate value and max_value
max_val = 0
value = 0
for k in tree:
# Get descriptor by recursing
... | Calculate values for drawing bars of non-leafs in ``tree``
Recurses through ``tree``, replaces ``dict``s with
``(BarDescriptor, dict)`` so ``ProgressTree._draw`` can use
the ``BarDescriptor``s to draw the tree | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L141-L177 | [
"def floor(x):\n \"\"\"Returns the floor of ``x``\n :returns: floor of ``x``\n :rtype: int\n \"\"\"\n return int(math.floor(x))\n",
"def merge_dicts(dicts, deepcopy=False):\n \"\"\"Merges dicts\n\n In case of key conflicts, the value kept will be from the latter\n dictionary in the list of... | class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between... |
hfaran/progressive | progressive/tree.py | ProgressTree._draw | python | def _draw(self, tree, indent=0):
if all([
isinstance(tree, dict),
type(tree) != BarDescriptor
]):
for k, v in sorted(tree.items()):
bar_desc, subdict = v[0], v[1]
args = [self.cursor.term] + bar_desc.get("args", [])
kwa... | Recurse through ``tree`` and draw all nodes | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/tree.py#L179-L195 | [
"def draw(self, value, newline=True, flush=True):\n \"\"\"Draw the progress bar\n\n :type value: int\n :param value: Progress value relative to ``self.max_value``\n :type newline: bool\n :param newline: If this is set, a newline will be written after drawing\n \"\"\"\n # This is essentially w... | class ProgressTree(object):
"""Progress display for trees
For drawing a hierarchical progress view from a tree
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
:type indent: int
:param indent: The amount of indentation between... |
hfaran/progressive | progressive/util.py | merge_dicts | python | def merge_dicts(dicts, deepcopy=False):
assert isinstance(dicts, list) and all(isinstance(d, dict) for d in dicts)
return dict(chain(*[copy.deepcopy(d).items() if deepcopy else d.items()
for d in dicts])) | Merges dicts
In case of key conflicts, the value kept will be from the latter
dictionary in the list of dictionaries
:param dicts: [dict, ...]
:param deepcopy: deepcopy items within dicts | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/util.py#L34-L45 | null | import math
import copy
from itertools import chain
def floor(x):
"""Returns the floor of ``x``
:returns: floor of ``x``
:rtype: int
"""
return int(math.floor(x))
def ensure(expr, exc, *args, **kwargs):
"""
:raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``
"""
if n... |
hfaran/progressive | progressive/bar.py | Bar.max_width | python | def max_width(self):
value, unit = float(self._width_str[:-1]), self._width_str[-1]
ensure(unit in ["c", "%"], ValueError,
"Width unit must be either 'c' or '%'")
if unit == "c":
ensure(value <= self.columns, ValueError,
"Terminal only has {} colum... | Get maximum width of progress bar
:rtype: int
:returns: Maximum column width of progress bar | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L144-L166 | [
"def floor(x):\n \"\"\"Returns the floor of ``x``\n :returns: floor of ``x``\n :rtype: int\n \"\"\"\n return int(math.floor(x))\n",
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise... | class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github... |
hfaran/progressive | progressive/bar.py | Bar.full_line_width | python | def full_line_width(self):
bar_str_len = sum([
self._indent,
((len(self.title) + 1) if self._title_pos in ["left", "right"]
else 0), # Title if present
len(self.start_char),
self.max_width, # Progress bar
len(self.end_char),
... | Find actual length of bar_str
e.g., Progress [ | ] 10/10 | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L169-L184 | null | class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github... |
hfaran/progressive | progressive/bar.py | Bar._supports_colors | python | def _supports_colors(term, raise_err, colors):
for color in colors:
try:
if isinstance(color, str):
req_colors = 16 if "bright" in color else 8
ensure(term.number_of_colors >= req_colors,
ColorUnsupportedError,
... | Check if ``term`` supports ``colors``
:raises ColorUnsupportedError: This is raised if ``raise_err``
is ``False`` and a color in ``colors`` is unsupported by ``term``
:type raise_err: bool
:param raise_err: Set to ``False`` to return a ``bool`` indicating
color support r... | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L243-L270 | [
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n"
] | class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github... |
hfaran/progressive | progressive/bar.py | Bar._get_format_callable | python | def _get_format_callable(term, color, back_color):
if isinstance(color, str):
ensure(
any(isinstance(back_color, t) for t in [str, type(None)]),
TypeError,
"back_color must be a str or NoneType"
)
if back_color:
... | Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
:param back_color: Back color for the string
:retur... | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L273-L301 | [
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n"
] | class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github... |
hfaran/progressive | progressive/bar.py | Bar._write | python | def _write(self, s, s_length=None, flush=False, ignore_overflow=False,
err_msg=None):
if not ignore_overflow:
s_length = len(s) if s_length is None else s_length
if err_msg is None:
err_msg = (
"Terminal has {} columns; attempted to writ... | Write ``s``
:type s: str|unicode
:param s: String to write
:param s_length: Custom length of ``s``
:param flush: Set this to flush the terminal stream after writing
:param ignore_overflow: Set this to ignore if s will exceed
the terminal's width
:param err_m... | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L309-L333 | [
"def ensure(expr, exc, *args, **kwargs):\n \"\"\"\n :raises ``exc``: With ``*args`` and ``**kwargs`` if not ``expr``\n \"\"\"\n if not expr:\n raise exc(*args, **kwargs)\n"
] | class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github... |
hfaran/progressive | progressive/bar.py | Bar.draw | python | def draw(self, value, newline=True, flush=True):
# This is essentially winch-handling without having
# to do winch-handling; cleanly redrawing on winch is difficult
# and out of the intended scope of this class; we *can*
# however, adjust the next draw to be proper by re-measuring
... | Draw the progress bar
:type value: int
:param value: Progress value relative to ``self.max_value``
:type newline: bool
:param newline: If this is set, a newline will be written after drawing | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/bar.py#L339-L408 | [
"def u(s):\n \"\"\"Cast ``s`` as unicode string\n\n This is a convenience function to make up for the fact\n that Python3 does not have a unicode() cast (for obvious reasons)\n\n :rtype: unicode\n :returns: Equivalent of unicode(s) (at least I hope so)\n \"\"\"\n return u'{}'.format(s)\n",
... | class Bar(object):
"""Progress Bar with blessings
Several parts of this class are thanks to Erik Rose's implementation
of ``ProgressBar`` in ``nose-progressive``, licensed under
The MIT License.
`MIT <http://opensource.org/licenses/MIT>`_
`nose-progressive/noseprogressive/bar.py <https://github... |
hfaran/progressive | progressive/cursor.py | Cursor.write | python | def write(self, s):
should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != "True"
if should_write_s:
self._stream.write(s) | Writes ``s`` to the terminal output stream
Writes can be disabled by setting the environment variable
`PROGRESSIVE_NOWRITE` to `'True'` | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/cursor.py#L18-L26 | null | class Cursor(object):
"""Common methods for cursor manipulation
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
"""
def __init__(self, term=None):
self.term = Terminal() if term is None else term
self._stream = sel... |
hfaran/progressive | progressive/cursor.py | Cursor.save | python | def save(self):
self.write(self.term.save)
self._saved = True | Saves current cursor position, so that it can be restored later | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/cursor.py#L28-L31 | [
"def write(self, s):\n \"\"\"Writes ``s`` to the terminal output stream\n\n Writes can be disabled by setting the environment variable\n `PROGRESSIVE_NOWRITE` to `'True'`\n \"\"\"\n should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != \"True\"\n if should_write_s:\n self._stream.write(s... | class Cursor(object):
"""Common methods for cursor manipulation
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
"""
def __init__(self, term=None):
self.term = Terminal() if term is None else term
self._stream = sel... |
hfaran/progressive | progressive/cursor.py | Cursor.newline | python | def newline(self):
self.write(self.term.move_down)
self.write(self.term.clear_bol) | Effects a newline by moving the cursor down and clearing | train | https://github.com/hfaran/progressive/blob/e39c7fb17405dbe997c3417a5993b94ef16dab0a/progressive/cursor.py#L46-L49 | [
"def write(self, s):\n \"\"\"Writes ``s`` to the terminal output stream\n\n Writes can be disabled by setting the environment variable\n `PROGRESSIVE_NOWRITE` to `'True'`\n \"\"\"\n should_write_s = os.getenv('PROGRESSIVE_NOWRITE') != \"True\"\n if should_write_s:\n self._stream.write(s... | class Cursor(object):
"""Common methods for cursor manipulation
:type term: NoneType|blessings.Terminal
:param term: Terminal instance; if not given, will be created by the class
"""
def __init__(self, term=None):
self.term = Terminal() if term is None else term
self._stream = sel... |
kalbhor/MusicNow | musicnow/command_line.py | add_config | python | def add_config():
genius_key = input('Enter Genius key : ')
bing_key = input('Enter Bing key : ')
CONFIG['keys']['bing_key'] = bing_key
CONFIG['keys']['genius_key'] = genius_key
with open(config_path, 'w') as configfile:
CONFIG.write(configfile) | Prompts user for API keys, adds them in an .ini file stored in the same
location as that of the script | train | https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L66-L79 | null | #!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
impor... |
kalbhor/MusicNow | musicnow/command_line.py | get_tracks_from_album | python | def get_tracks_from_album(album_name):
'''
Gets tracks from an album using Spotify's API
'''
spotify = spotipy.Spotify()
album = spotify.search(q='album:' + album_name, limit=1)
album_id = album['tracks']['items'][0]['album']['id']
results = spotify.album_tracks(album_id=str(album_id))
... | Gets tracks from an album using Spotify's API | train | https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L82-L96 | null | #!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
impor... |
kalbhor/MusicNow | musicnow/command_line.py | get_url | python | def get_url(song_input, auto):
'''
Provides user with a list of songs to choose from
returns the url of chosen song.
'''
youtube_list = OrderedDict()
num = 0 # List of songs index
html = requests.get("https://www.youtube.com/results",
params={'search_query': song_in... | Provides user with a list of songs to choose from
returns the url of chosen song. | train | https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L99-L135 | [
"def prompt(youtube_list):\n '''\n Prompts for song number from list of songs\n '''\n\n option = int(input('\\nEnter song number > '))\n try:\n song_url = list(youtube_list.values())[option - 1]\n song_title = list(youtube_list.keys())[option - 1]\n except IndexError:\n log.lo... | #!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
impor... |
kalbhor/MusicNow | musicnow/command_line.py | prompt | python | def prompt(youtube_list):
'''
Prompts for song number from list of songs
'''
option = int(input('\nEnter song number > '))
try:
song_url = list(youtube_list.values())[option - 1]
song_title = list(youtube_list.keys())[option - 1]
except IndexError:
log.log_error('Invalid... | Prompts for song number from list of songs | train | https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L138-L164 | [
"def log_error(text='', indented=False):\n msg = '%s%s%s' % (Fore.RED, text, Fore.RESET)\n if indented:\n log_indented(msg)\n else:\n log(msg)\n"
] | #!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
impor... |
kalbhor/MusicNow | musicnow/command_line.py | main | python | def main():
'''
Starts here, handles arguments
'''
system('clear') # Must be system('cls') for windows
setup()
parser = argparse.ArgumentParser(
description='Download songs with album art and metadata!')
parser.add_argument('-c', '--config', action='store_true',
... | Starts here, handles arguments | train | https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/command_line.py#L189-L267 | [
"def setup():\n \"\"\"\n Gathers all configs\n \"\"\"\n\n global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR \n\n LOG_FILENAME = 'musicrepair_log.txt'\n LOG_LINE_SEPERATOR = '........................\\n'\n\n CONFIG = configparser.ConfigParser()\n config_path =... | #!/usr/bin/env python
r"""
__ __ _ _ _
| \/ |_ _ ___(_) ___| \ | | _____ __
| |\/| | | | / __| |/ __| \| |/ _ \ \ /\ / /
| | | | |_| \__ \ | (__| |\ | (_) \ V V /
|_| |_|\__,_|___/_|\___|_| \_|\___/ \_/\_/
"""
import argparse
import configparser
import re
impor... |
kalbhor/MusicNow | musicnow/repair.py | setup | python | def setup():
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR
LOG_FILENAME = 'musicrepair_log.txt'
LOG_LINE_SEPERATOR = '........................\n'
CONFIG = configparser.ConfigParser()
config_path = realpath(__file__).replace(basename(__file__),'')
config_p... | Gathers all configs | train | https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L42-L57 | null | #!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, env... |
kalbhor/MusicNow | musicnow/repair.py | matching_details | python | def matching_details(song_name, song_title, artist):
'''
Provides a score out of 10 that determines the
relevance of the search result
'''
match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio()
match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio(... | Provides a score out of 10 that determines the
relevance of the search result | train | https://github.com/kalbhor/MusicNow/blob/12ff1ed2ea2bb7dbbfd925d7998b3ea1e20de291/musicnow/repair.py#L60-L73 | null | #!/usr/bin/env python
'''
Tries to find the metadata of songs based on the file name
https://github.com/lakshaykalbhor/MusicRepair
'''
try:
from . import albumsearch
from . import improvename
from . import log
except:
import albumsearch
import improvename
import log
from os import rename, env... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.