repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
pystorm/pystorm
pystorm/component.py
Component.read_handshake
def read_handshake(self): """Read and process an initial handshake message from Storm.""" msg = self.read_message() pid_dir, _conf, _context = msg["pidDir"], msg["conf"], msg["context"] # Write a blank PID file out to the pidDir open(join(pid_dir, str(self.pid)), "w").close() ...
python
def read_handshake(self): """Read and process an initial handshake message from Storm.""" msg = self.read_message() pid_dir, _conf, _context = msg["pidDir"], msg["conf"], msg["context"] # Write a blank PID file out to the pidDir open(join(pid_dir, str(self.pid)), "w").close() ...
[ "def", "read_handshake", "(", "self", ")", ":", "msg", "=", "self", ".", "read_message", "(", ")", "pid_dir", ",", "_conf", ",", "_context", "=", "msg", "[", "\"pidDir\"", "]", ",", "msg", "[", "\"conf\"", "]", ",", "msg", "[", "\"context\"", "]", "#...
Read and process an initial handshake message from Storm.
[ "Read", "and", "process", "an", "initial", "handshake", "message", "from", "Storm", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/component.py#L326-L335
pystorm/pystorm
pystorm/component.py
Component.send_message
def send_message(self, message): """Send a message to Storm via stdout.""" if not isinstance(message, dict): logger = self.logger if self.logger else log logger.error( "%s.%d attempted to send a non dict message to Storm: " "%r", self.component_nam...
python
def send_message(self, message): """Send a message to Storm via stdout.""" if not isinstance(message, dict): logger = self.logger if self.logger else log logger.error( "%s.%d attempted to send a non dict message to Storm: " "%r", self.component_nam...
[ "def", "send_message", "(", "self", ",", "message", ")", ":", "if", "not", "isinstance", "(", "message", ",", "dict", ")", ":", "logger", "=", "self", ".", "logger", "if", "self", ".", "logger", "else", "log", "logger", ".", "error", "(", "\"%s.%d atte...
Send a message to Storm via stdout.
[ "Send", "a", "message", "to", "Storm", "via", "stdout", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/component.py#L337-L348
pystorm/pystorm
pystorm/component.py
Component.raise_exception
def raise_exception(self, exception, tup=None): """Report an exception back to Storm via logging. :param exception: a Python exception. :param tup: a :class:`Tuple` object. """ if tup: message = ( "Python {exception_name} raised while processing Tuple...
python
def raise_exception(self, exception, tup=None): """Report an exception back to Storm via logging. :param exception: a Python exception. :param tup: a :class:`Tuple` object. """ if tup: message = ( "Python {exception_name} raised while processing Tuple...
[ "def", "raise_exception", "(", "self", ",", "exception", ",", "tup", "=", "None", ")", ":", "if", "tup", ":", "message", "=", "(", "\"Python {exception_name} raised while processing Tuple \"", "\"{tup!r}\\n{traceback}\"", ")", "else", ":", "message", "=", "\"Python ...
Report an exception back to Storm via logging. :param exception: a Python exception. :param tup: a :class:`Tuple` object.
[ "Report", "an", "exception", "back", "to", "Storm", "via", "logging", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/component.py#L350-L367
pystorm/pystorm
pystorm/component.py
Component.log
def log(self, message, level=None): """Log a message to Storm optionally providing a logging level. :param message: the log message to send to Storm. :type message: str :param level: the logging level that Storm should use when writing the ``message``. Can be one o...
python
def log(self, message, level=None): """Log a message to Storm optionally providing a logging level. :param message: the log message to send to Storm. :type message: str :param level: the logging level that Storm should use when writing the ``message``. Can be one o...
[ "def", "log", "(", "self", ",", "message", ",", "level", "=", "None", ")", ":", "level", "=", "_STORM_LOG_LEVELS", ".", "get", "(", "level", ",", "_STORM_LOG_INFO", ")", "self", ".", "send_message", "(", "{", "\"command\"", ":", "\"log\"", ",", "\"msg\""...
Log a message to Storm optionally providing a logging level. :param message: the log message to send to Storm. :type message: str :param level: the logging level that Storm should use when writing the ``message``. Can be one of: trace, debug, info, warn, or ...
[ "Log", "a", "message", "to", "Storm", "optionally", "providing", "a", "logging", "level", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/component.py#L384-L404
pystorm/pystorm
pystorm/component.py
Component.emit
def emit( self, tup, tup_id=None, stream=None, anchors=None, direct_task=None, need_task_ids=False, ): """Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only JSON-serializable d...
python
def emit( self, tup, tup_id=None, stream=None, anchors=None, direct_task=None, need_task_ids=False, ): """Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only JSON-serializable d...
[ "def", "emit", "(", "self", ",", "tup", ",", "tup_id", "=", "None", ",", "stream", "=", "None", ",", "anchors", "=", "None", ",", "direct_task", "=", "None", ",", "need_task_ids", "=", "False", ",", ")", ":", "if", "not", "isinstance", "(", "tup", ...
Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only JSON-serializable data. :type tup: :class:`list` or :class:`pystorm.component.Tuple` :param tup_id: the ID for the Tuple. If omitted by a :class:`pystorm....
[ "Emit", "a", "new", "Tuple", "to", "a", "stream", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/component.py#L406-L478
pystorm/pystorm
pystorm/component.py
Component.run
def run(self): """Main run loop for all components. Performs initial handshake with Storm and reads Tuples handing them off to subclasses. Any exceptions are caught and logged back to Storm prior to the Python process exiting. .. warning:: Subclasses should **not*...
python
def run(self): """Main run loop for all components. Performs initial handshake with Storm and reads Tuples handing them off to subclasses. Any exceptions are caught and logged back to Storm prior to the Python process exiting. .. warning:: Subclasses should **not*...
[ "def", "run", "(", "self", ")", ":", "storm_conf", ",", "context", "=", "self", ".", "read_handshake", "(", ")", "self", ".", "_setup_component", "(", "storm_conf", ",", "context", ")", "self", ".", "initialize", "(", "storm_conf", ",", "context", ")", "...
Main run loop for all components. Performs initial handshake with Storm and reads Tuples handing them off to subclasses. Any exceptions are caught and logged back to Storm prior to the Python process exiting. .. warning:: Subclasses should **not** override this method.
[ "Main", "run", "loop", "for", "all", "components", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/component.py#L504-L542
pystorm/pystorm
pystorm/component.py
Component._exit
def _exit(self, status_code): """Properly kill Python process including zombie threads.""" # If there are active threads still running infinite loops, sys.exit # won't kill them but os._exit will. os._exit skips calling cleanup # handlers, flushing stdio buffers, etc. exit_func =...
python
def _exit(self, status_code): """Properly kill Python process including zombie threads.""" # If there are active threads still running infinite loops, sys.exit # won't kill them but os._exit will. os._exit skips calling cleanup # handlers, flushing stdio buffers, etc. exit_func =...
[ "def", "_exit", "(", "self", ",", "status_code", ")", ":", "# If there are active threads still running infinite loops, sys.exit", "# won't kill them but os._exit will. os._exit skips calling cleanup", "# handlers, flushing stdio buffers, etc.", "exit_func", "=", "os", ".", "_exit", ...
Properly kill Python process including zombie threads.
[ "Properly", "kill", "Python", "process", "including", "zombie", "threads", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/component.py#L544-L550
pystorm/pystorm
pystorm/serializers/json_serializer.py
JSONSerializer._wrap_stream
def _wrap_stream(stream): """Returns a TextIOWrapper around the given stream that handles UTF-8 encoding/decoding. """ if hasattr(stream, "buffer"): return io.TextIOWrapper(stream.buffer, encoding="utf-8") elif hasattr(stream, "readable"): return io.TextIO...
python
def _wrap_stream(stream): """Returns a TextIOWrapper around the given stream that handles UTF-8 encoding/decoding. """ if hasattr(stream, "buffer"): return io.TextIOWrapper(stream.buffer, encoding="utf-8") elif hasattr(stream, "readable"): return io.TextIO...
[ "def", "_wrap_stream", "(", "stream", ")", ":", "if", "hasattr", "(", "stream", ",", "\"buffer\"", ")", ":", "return", "io", ".", "TextIOWrapper", "(", "stream", ".", "buffer", ",", "encoding", "=", "\"utf-8\"", ")", "elif", "hasattr", "(", "stream", ","...
Returns a TextIOWrapper around the given stream that handles UTF-8 encoding/decoding.
[ "Returns", "a", "TextIOWrapper", "around", "the", "given", "stream", "that", "handles", "UTF", "-", "8", "encoding", "/", "decoding", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/serializers/json_serializer.py#L27-L37
pystorm/pystorm
pystorm/serializers/json_serializer.py
JSONSerializer.read_message
def read_message(self): """The Storm multilang protocol consists of JSON messages followed by a newline and "end\n". All of Storm's messages (for either bolts or spouts) should be of the form:: '<command or task_id form prior emit>\\nend\\n' Command example, an inc...
python
def read_message(self): """The Storm multilang protocol consists of JSON messages followed by a newline and "end\n". All of Storm's messages (for either bolts or spouts) should be of the form:: '<command or task_id form prior emit>\\nend\\n' Command example, an inc...
[ "def", "read_message", "(", "self", ")", ":", "msg", "=", "\"\"", "num_blank_lines", "=", "0", "while", "True", ":", "# readline will return trailing \\n so that output is unambigious, we", "# should only have line == '' if we're at EOF", "with", "self", ".", "_reader_lock", ...
The Storm multilang protocol consists of JSON messages followed by a newline and "end\n". All of Storm's messages (for either bolts or spouts) should be of the form:: '<command or task_id form prior emit>\\nend\\n' Command example, an incoming Tuple to a bolt:: ...
[ "The", "Storm", "multilang", "protocol", "consists", "of", "JSON", "messages", "followed", "by", "a", "newline", "and", "end", "\\", "n", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/serializers/json_serializer.py#L39-L91
pystorm/pystorm
pystorm/serializers/json_serializer.py
JSONSerializer.serialize_dict
def serialize_dict(self, msg_dict): """Serialize to JSON a message dictionary.""" serialized = json.dumps(msg_dict, namedtuple_as_object=False) if PY2: serialized = serialized.decode("utf-8") serialized = "{}\nend\n".format(serialized) return serialized
python
def serialize_dict(self, msg_dict): """Serialize to JSON a message dictionary.""" serialized = json.dumps(msg_dict, namedtuple_as_object=False) if PY2: serialized = serialized.decode("utf-8") serialized = "{}\nend\n".format(serialized) return serialized
[ "def", "serialize_dict", "(", "self", ",", "msg_dict", ")", ":", "serialized", "=", "json", ".", "dumps", "(", "msg_dict", ",", "namedtuple_as_object", "=", "False", ")", "if", "PY2", ":", "serialized", "=", "serialized", ".", "decode", "(", "\"utf-8\"", "...
Serialize to JSON a message dictionary.
[ "Serialize", "to", "JSON", "a", "message", "dictionary", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/serializers/json_serializer.py#L93-L99
pystorm/pystorm
pystorm/bolt.py
Bolt.read_tuple
def read_tuple(self): """Read a tuple from the pipe to Storm.""" cmd = self.read_command() source = cmd["comp"] stream = cmd["stream"] values = cmd["tuple"] val_type = self._source_tuple_types[source].get(stream) return Tuple( cmd["id"], so...
python
def read_tuple(self): """Read a tuple from the pipe to Storm.""" cmd = self.read_command() source = cmd["comp"] stream = cmd["stream"] values = cmd["tuple"] val_type = self._source_tuple_types[source].get(stream) return Tuple( cmd["id"], so...
[ "def", "read_tuple", "(", "self", ")", ":", "cmd", "=", "self", ".", "read_command", "(", ")", "source", "=", "cmd", "[", "\"comp\"", "]", "stream", "=", "cmd", "[", "\"stream\"", "]", "values", "=", "cmd", "[", "\"tuple\"", "]", "val_type", "=", "se...
Read a tuple from the pipe to Storm.
[ "Read", "a", "tuple", "from", "the", "pipe", "to", "Storm", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L90-L103
pystorm/pystorm
pystorm/bolt.py
Bolt.emit
def emit( self, tup, stream=None, anchors=None, direct_task=None, need_task_ids=False ): """Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only JSON-serializable data. :type tup: :class:`list` or :class:`pystorm.compo...
python
def emit( self, tup, stream=None, anchors=None, direct_task=None, need_task_ids=False ): """Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only JSON-serializable data. :type tup: :class:`list` or :class:`pystorm.compo...
[ "def", "emit", "(", "self", ",", "tup", ",", "stream", "=", "None", ",", "anchors", "=", "None", ",", "direct_task", "=", "None", ",", "need_task_ids", "=", "False", ")", ":", "if", "anchors", "is", "None", ":", "anchors", "=", "self", ".", "_current...
Emit a new Tuple to a stream. :param tup: the Tuple payload to send to Storm, should contain only JSON-serializable data. :type tup: :class:`list` or :class:`pystorm.component.Tuple` :param stream: the ID of the stream to emit this Tuple to. Specify ``...
[ "Emit", "a", "new", "Tuple", "to", "a", "stream", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L136-L174
pystorm/pystorm
pystorm/bolt.py
Bolt.ack
def ack(self, tup): """Indicate that processing of a Tuple has succeeded. :param tup: the Tuple to acknowledge. :type tup: :class:`str` or :class:`pystorm.component.Tuple` """ tup_id = tup.id if isinstance(tup, Tuple) else tup self.send_message({"command": "ack", "id": t...
python
def ack(self, tup): """Indicate that processing of a Tuple has succeeded. :param tup: the Tuple to acknowledge. :type tup: :class:`str` or :class:`pystorm.component.Tuple` """ tup_id = tup.id if isinstance(tup, Tuple) else tup self.send_message({"command": "ack", "id": t...
[ "def", "ack", "(", "self", ",", "tup", ")", ":", "tup_id", "=", "tup", ".", "id", "if", "isinstance", "(", "tup", ",", "Tuple", ")", "else", "tup", "self", ".", "send_message", "(", "{", "\"command\"", ":", "\"ack\"", ",", "\"id\"", ":", "tup_id", ...
Indicate that processing of a Tuple has succeeded. :param tup: the Tuple to acknowledge. :type tup: :class:`str` or :class:`pystorm.component.Tuple`
[ "Indicate", "that", "processing", "of", "a", "Tuple", "has", "succeeded", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L176-L183
pystorm/pystorm
pystorm/bolt.py
Bolt.fail
def fail(self, tup): """Indicate that processing of a Tuple has failed. :param tup: the Tuple to fail (its ``id`` if ``str``). :type tup: :class:`str` or :class:`pystorm.component.Tuple` """ tup_id = tup.id if isinstance(tup, Tuple) else tup self.send_message({"command":...
python
def fail(self, tup): """Indicate that processing of a Tuple has failed. :param tup: the Tuple to fail (its ``id`` if ``str``). :type tup: :class:`str` or :class:`pystorm.component.Tuple` """ tup_id = tup.id if isinstance(tup, Tuple) else tup self.send_message({"command":...
[ "def", "fail", "(", "self", ",", "tup", ")", ":", "tup_id", "=", "tup", ".", "id", "if", "isinstance", "(", "tup", ",", "Tuple", ")", "else", "tup", "self", ".", "send_message", "(", "{", "\"command\"", ":", "\"fail\"", ",", "\"id\"", ":", "tup_id", ...
Indicate that processing of a Tuple has failed. :param tup: the Tuple to fail (its ``id`` if ``str``). :type tup: :class:`str` or :class:`pystorm.component.Tuple`
[ "Indicate", "that", "processing", "of", "a", "Tuple", "has", "failed", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L185-L192
pystorm/pystorm
pystorm/bolt.py
Bolt._run
def _run(self): """The inside of ``run``'s infinite loop. Separated out so it can be properly unit tested. """ tup = self.read_tuple() self._current_tups = [tup] if self.is_heartbeat(tup): self.send_message({"command": "sync"}) elif self.is_tick(tup):...
python
def _run(self): """The inside of ``run``'s infinite loop. Separated out so it can be properly unit tested. """ tup = self.read_tuple() self._current_tups = [tup] if self.is_heartbeat(tup): self.send_message({"command": "sync"}) elif self.is_tick(tup):...
[ "def", "_run", "(", "self", ")", ":", "tup", "=", "self", ".", "read_tuple", "(", ")", "self", ".", "_current_tups", "=", "[", "tup", "]", "if", "self", ".", "is_heartbeat", "(", "tup", ")", ":", "self", ".", "send_message", "(", "{", "\"command\"", ...
The inside of ``run``'s infinite loop. Separated out so it can be properly unit tested.
[ "The", "inside", "of", "run", "s", "infinite", "loop", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L194-L215
pystorm/pystorm
pystorm/bolt.py
Bolt._handle_run_exception
def _handle_run_exception(self, exc): """Process an exception encountered while running the ``run()`` loop. Called right before program exits. """ if len(self._current_tups) == 1: tup = self._current_tups[0] self.raise_exception(exc, tup) if self.auto...
python
def _handle_run_exception(self, exc): """Process an exception encountered while running the ``run()`` loop. Called right before program exits. """ if len(self._current_tups) == 1: tup = self._current_tups[0] self.raise_exception(exc, tup) if self.auto...
[ "def", "_handle_run_exception", "(", "self", ",", "exc", ")", ":", "if", "len", "(", "self", ".", "_current_tups", ")", "==", "1", ":", "tup", "=", "self", ".", "_current_tups", "[", "0", "]", "self", ".", "raise_exception", "(", "exc", ",", "tup", "...
Process an exception encountered while running the ``run()`` loop. Called right before program exits.
[ "Process", "an", "exception", "encountered", "while", "running", "the", "run", "()", "loop", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L217-L226
pystorm/pystorm
pystorm/bolt.py
BatchingBolt.emit
def emit(self, tup, **kwargs): """Modified emit that will not return task IDs after emitting. See :class:`pystorm.component.Bolt` for more information. :returns: ``None``. """ kwargs["need_task_ids"] = False return super(BatchingBolt, self).emit(tup, **kwargs)
python
def emit(self, tup, **kwargs): """Modified emit that will not return task IDs after emitting. See :class:`pystorm.component.Bolt` for more information. :returns: ``None``. """ kwargs["need_task_ids"] = False return super(BatchingBolt, self).emit(tup, **kwargs)
[ "def", "emit", "(", "self", ",", "tup", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"need_task_ids\"", "]", "=", "False", "return", "super", "(", "BatchingBolt", ",", "self", ")", ".", "emit", "(", "tup", ",", "*", "*", "kwargs", ")" ]
Modified emit that will not return task IDs after emitting. See :class:`pystorm.component.Bolt` for more information. :returns: ``None``.
[ "Modified", "emit", "that", "will", "not", "return", "task", "IDs", "after", "emitting", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L316-L324
pystorm/pystorm
pystorm/bolt.py
BatchingBolt.process_tick
def process_tick(self, tick_tup): """Increment tick counter, and call ``process_batch`` for all current batches if tick counter exceeds ``ticks_between_batches``. See :class:`pystorm.component.Bolt` for more information. .. warning:: This method should **not** be overriden....
python
def process_tick(self, tick_tup): """Increment tick counter, and call ``process_batch`` for all current batches if tick counter exceeds ``ticks_between_batches``. See :class:`pystorm.component.Bolt` for more information. .. warning:: This method should **not** be overriden....
[ "def", "process_tick", "(", "self", ",", "tick_tup", ")", ":", "self", ".", "_tick_counter", "+=", "1", "# ACK tick Tuple immediately, since it's just responsible for counter", "self", ".", "ack", "(", "tick_tup", ")", "if", "self", ".", "_tick_counter", ">", "self"...
Increment tick counter, and call ``process_batch`` for all current batches if tick counter exceeds ``ticks_between_batches``. See :class:`pystorm.component.Bolt` for more information. .. warning:: This method should **not** be overriden. If you want to tweak how Tuples...
[ "Increment", "tick", "counter", "and", "call", "process_batch", "for", "all", "current", "batches", "if", "tick", "counter", "exceeds", "ticks_between_batches", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L326-L341
pystorm/pystorm
pystorm/bolt.py
BatchingBolt.process_batches
def process_batches(self): """Iterate through all batches, call process_batch on them, and ack. Separated out for the rare instances when we want to subclass BatchingBolt and customize what mechanism causes batches to be processed. """ for key, batch in iteritems(self._b...
python
def process_batches(self): """Iterate through all batches, call process_batch on them, and ack. Separated out for the rare instances when we want to subclass BatchingBolt and customize what mechanism causes batches to be processed. """ for key, batch in iteritems(self._b...
[ "def", "process_batches", "(", "self", ")", ":", "for", "key", ",", "batch", "in", "iteritems", "(", "self", ".", "_batches", ")", ":", "self", ".", "_current_tups", "=", "batch", "self", ".", "_current_key", "=", "key", "self", ".", "process_batch", "("...
Iterate through all batches, call process_batch on them, and ack. Separated out for the rare instances when we want to subclass BatchingBolt and customize what mechanism causes batches to be processed.
[ "Iterate", "through", "all", "batches", "call", "process_batch", "on", "them", "and", "ack", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L343-L361
pystorm/pystorm
pystorm/bolt.py
BatchingBolt.process
def process(self, tup): """Group non-tick Tuples into batches by ``group_key``. .. warning:: This method should **not** be overriden. If you want to tweak how Tuples are grouped into batches, override ``group_key``. """ # Append latest Tuple to batches g...
python
def process(self, tup): """Group non-tick Tuples into batches by ``group_key``. .. warning:: This method should **not** be overriden. If you want to tweak how Tuples are grouped into batches, override ``group_key``. """ # Append latest Tuple to batches g...
[ "def", "process", "(", "self", ",", "tup", ")", ":", "# Append latest Tuple to batches", "group_key", "=", "self", ".", "group_key", "(", "tup", ")", "self", ".", "_batches", "[", "group_key", "]", ".", "append", "(", "tup", ")" ]
Group non-tick Tuples into batches by ``group_key``. .. warning:: This method should **not** be overriden. If you want to tweak how Tuples are grouped into batches, override ``group_key``.
[ "Group", "non", "-", "tick", "Tuples", "into", "batches", "by", "group_key", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L363-L372
pystorm/pystorm
pystorm/bolt.py
BatchingBolt._handle_run_exception
def _handle_run_exception(self, exc): """Process an exception encountered while running the ``run()`` loop. Called right before program exits. """ self.raise_exception(exc, self._current_tups) if self.auto_fail: failed = set() for key, batch in iteritems...
python
def _handle_run_exception(self, exc): """Process an exception encountered while running the ``run()`` loop. Called right before program exits. """ self.raise_exception(exc, self._current_tups) if self.auto_fail: failed = set() for key, batch in iteritems...
[ "def", "_handle_run_exception", "(", "self", ",", "exc", ")", ":", "self", ".", "raise_exception", "(", "exc", ",", "self", ".", "_current_tups", ")", "if", "self", ".", "auto_fail", ":", "failed", "=", "set", "(", ")", "for", "key", ",", "batch", "in"...
Process an exception encountered while running the ``run()`` loop. Called right before program exits.
[ "Process", "an", "exception", "encountered", "while", "running", "the", "run", "()", "loop", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L391-L414
pystorm/pystorm
pystorm/bolt.py
TicklessBatchingBolt._batch_entry_run
def _batch_entry_run(self): """The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested. """ time.sleep(self.secs_between_batches) with self._batch_lock: self.process_batches()
python
def _batch_entry_run(self): """The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested. """ time.sleep(self.secs_between_batches) with self._batch_lock: self.process_batches()
[ "def", "_batch_entry_run", "(", "self", ")", ":", "time", ".", "sleep", "(", "self", ".", "secs_between_batches", ")", "with", "self", ".", "_batch_lock", ":", "self", ".", "process_batches", "(", ")" ]
The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested.
[ "The", "inside", "of", "_batch_entry", "s", "infinite", "loop", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L496-L503
pystorm/pystorm
pystorm/bolt.py
TicklessBatchingBolt._batch_entry
def _batch_entry(self): """Entry point for the batcher thread.""" try: while True: self._batch_entry_run() except: self.exc_info = sys.exc_info() os.kill(self.pid, signal.SIGUSR1)
python
def _batch_entry(self): """Entry point for the batcher thread.""" try: while True: self._batch_entry_run() except: self.exc_info = sys.exc_info() os.kill(self.pid, signal.SIGUSR1)
[ "def", "_batch_entry", "(", "self", ")", ":", "try", ":", "while", "True", ":", "self", ".", "_batch_entry_run", "(", ")", "except", ":", "self", ".", "exc_info", "=", "sys", ".", "exc_info", "(", ")", "os", ".", "kill", "(", "self", ".", "pid", ",...
Entry point for the batcher thread.
[ "Entry", "point", "for", "the", "batcher", "thread", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L505-L512
pystorm/pystorm
pystorm/bolt.py
TicklessBatchingBolt._run
def _run(self): """The inside of ``run``'s infinite loop. Separate from BatchingBolt's implementation because we need to be able to acquire the batch lock after reading the tuple. We can't acquire the lock before reading the tuple because if that hangs (i.e. the topolog...
python
def _run(self): """The inside of ``run``'s infinite loop. Separate from BatchingBolt's implementation because we need to be able to acquire the batch lock after reading the tuple. We can't acquire the lock before reading the tuple because if that hangs (i.e. the topolog...
[ "def", "_run", "(", "self", ")", ":", "tup", "=", "self", ".", "read_tuple", "(", ")", "with", "self", ".", "_batch_lock", ":", "self", ".", "_current_tups", "=", "[", "tup", "]", "if", "self", ".", "is_heartbeat", "(", "tup", ")", ":", "self", "."...
The inside of ``run``'s infinite loop. Separate from BatchingBolt's implementation because we need to be able to acquire the batch lock after reading the tuple. We can't acquire the lock before reading the tuple because if that hangs (i.e. the topology is shutting down) the loc...
[ "The", "inside", "of", "run", "s", "infinite", "loop", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L523-L546
pystorm/pystorm
pystorm/serializers/serializer.py
Serializer.send_message
def send_message(self, msg_dict): """Serialize a message dictionary and write it to the output stream.""" with self._writer_lock: try: self.output_stream.flush() self.output_stream.write(self.serialize_dict(msg_dict)) self.output_stream.flush()...
python
def send_message(self, msg_dict): """Serialize a message dictionary and write it to the output stream.""" with self._writer_lock: try: self.output_stream.flush() self.output_stream.write(self.serialize_dict(msg_dict)) self.output_stream.flush()...
[ "def", "send_message", "(", "self", ",", "msg_dict", ")", ":", "with", "self", ".", "_writer_lock", ":", "try", ":", "self", ".", "output_stream", ".", "flush", "(", ")", "self", ".", "output_stream", ".", "write", "(", "self", ".", "serialize_dict", "("...
Serialize a message dictionary and write it to the output stream.
[ "Serialize", "a", "message", "dictionary", "and", "write", "it", "to", "the", "output", "stream", "." ]
train
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/serializers/serializer.py#L27-L37
urschrei/convertbng
convertbng/util.py
_void_array_to_list
def _void_array_to_list(restuple, _func, _args): """ Convert the FFI result to Python data structures """ shape = (restuple.e.len, 1) array_size = np.prod(shape) mem_size = 8 * array_size array_str_e = string_at(restuple.e.data, mem_size) array_str_n = string_at(restuple.n.data, mem_size) ...
python
def _void_array_to_list(restuple, _func, _args): """ Convert the FFI result to Python data structures """ shape = (restuple.e.len, 1) array_size = np.prod(shape) mem_size = 8 * array_size array_str_e = string_at(restuple.e.data, mem_size) array_str_n = string_at(restuple.n.data, mem_size) ...
[ "def", "_void_array_to_list", "(", "restuple", ",", "_func", ",", "_args", ")", ":", "shape", "=", "(", "restuple", ".", "e", ".", "len", ",", "1", ")", "array_size", "=", "np", ".", "prod", "(", "shape", ")", "mem_size", "=", "8", "*", "array_size",...
Convert the FFI result to Python data structures
[ "Convert", "the", "FFI", "result", "to", "Python", "data", "structures" ]
train
https://github.com/urschrei/convertbng/blob/b0f5ca8b4942a835a834aed4c1fdb4d827c72342/convertbng/util.py#L122-L134
tsroten/dragonmapper
dragonmapper/data/__init__.py
load_data_file
def load_data_file(filename, encoding='utf-8'): """Load a data file and return it as a list of lines. Parameters: filename: The name of the file (no directories included). encoding: The file encoding. Defaults to utf-8. """ data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, f...
python
def load_data_file(filename, encoding='utf-8'): """Load a data file and return it as a list of lines. Parameters: filename: The name of the file (no directories included). encoding: The file encoding. Defaults to utf-8. """ data = pkgutil.get_data(PACKAGE_NAME, os.path.join(DATA_DIR, f...
[ "def", "load_data_file", "(", "filename", ",", "encoding", "=", "'utf-8'", ")", ":", "data", "=", "pkgutil", ".", "get_data", "(", "PACKAGE_NAME", ",", "os", ".", "path", ".", "join", "(", "DATA_DIR", ",", "filename", ")", ")", "return", "data", ".", "...
Load a data file and return it as a list of lines. Parameters: filename: The name of the file (no directories included). encoding: The file encoding. Defaults to utf-8.
[ "Load", "a", "data", "file", "and", "return", "it", "as", "a", "list", "of", "lines", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/data/__init__.py#L13-L22
tsroten/dragonmapper
dragonmapper/hanzi.py
_load_data
def _load_data(): """Load the word and character mapping data into a dictionary. In the data files, each line is formatted like this: HANZI PINYIN_READING/PINYIN_READING So, lines need to be split by '\t' and then the Pinyin readings need to be split by '/'. """ data = {} for na...
python
def _load_data(): """Load the word and character mapping data into a dictionary. In the data files, each line is formatted like this: HANZI PINYIN_READING/PINYIN_READING So, lines need to be split by '\t' and then the Pinyin readings need to be split by '/'. """ data = {} for na...
[ "def", "_load_data", "(", ")", ":", "data", "=", "{", "}", "for", "name", ",", "file_name", "in", "(", "(", "'words'", ",", "'hanzi_pinyin_words.tsv'", ")", ",", "(", "'characters'", ",", "'hanzi_pinyin_characters.tsv'", ")", ")", ":", "# Split the lines by ta...
Load the word and character mapping data into a dictionary. In the data files, each line is formatted like this: HANZI PINYIN_READING/PINYIN_READING So, lines need to be split by '\t' and then the Pinyin readings need to be split by '/'.
[ "Load", "the", "word", "and", "character", "mapping", "data", "into", "a", "dictionary", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L36-L54
tsroten/dragonmapper
dragonmapper/hanzi.py
_hanzi_to_pinyin
def _hanzi_to_pinyin(hanzi): """Return the Pinyin reading for a Chinese word. If the given string *hanzi* matches a CC-CEDICT word, the return value is formatted like this: [WORD_READING1, WORD_READING2, ...] If the given string *hanzi* doesn't match a CC-CEDICT word, the return value is formatted...
python
def _hanzi_to_pinyin(hanzi): """Return the Pinyin reading for a Chinese word. If the given string *hanzi* matches a CC-CEDICT word, the return value is formatted like this: [WORD_READING1, WORD_READING2, ...] If the given string *hanzi* doesn't match a CC-CEDICT word, the return value is formatted...
[ "def", "_hanzi_to_pinyin", "(", "hanzi", ")", ":", "try", ":", "return", "_HANZI_PINYIN_MAP", "[", "'words'", "]", "[", "hanzi", "]", "except", "KeyError", ":", "return", "[", "_CHARACTERS", ".", "get", "(", "character", ",", "character", ")", "for", "char...
Return the Pinyin reading for a Chinese word. If the given string *hanzi* matches a CC-CEDICT word, the return value is formatted like this: [WORD_READING1, WORD_READING2, ...] If the given string *hanzi* doesn't match a CC-CEDICT word, the return value is formatted like this: [[CHAR_READING1, CHAR_RE...
[ "Return", "the", "Pinyin", "reading", "for", "a", "Chinese", "word", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L61-L77
tsroten/dragonmapper
dragonmapper/hanzi.py
_enclose_readings
def _enclose_readings(container, readings): """Enclose a reading within a container, e.g. '[]'.""" container_start, container_end = tuple(container) enclosed_readings = '%(container_start)s%(readings)s%(container_end)s' % { 'container_start': container_start, 'container_end': container_end, ...
python
def _enclose_readings(container, readings): """Enclose a reading within a container, e.g. '[]'.""" container_start, container_end = tuple(container) enclosed_readings = '%(container_start)s%(readings)s%(container_end)s' % { 'container_start': container_start, 'container_end': container_end, ...
[ "def", "_enclose_readings", "(", "container", ",", "readings", ")", ":", "container_start", ",", "container_end", "=", "tuple", "(", "container", ")", "enclosed_readings", "=", "'%(container_start)s%(readings)s%(container_end)s'", "%", "{", "'container_start'", ":", "co...
Enclose a reading within a container, e.g. '[]'.
[ "Enclose", "a", "reading", "within", "a", "container", "e", ".", "g", ".", "[]", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L80-L86
tsroten/dragonmapper
dragonmapper/hanzi.py
to_pinyin
def to_pinyin(s, delimiter=' ', all_readings=False, container='[]', accented=True): """Convert a string's Chinese characters to Pinyin readings. *s* is a string containing Chinese characters. *accented* is a boolean value indicating whether to return accented or numbered Pinyin readings. ...
python
def to_pinyin(s, delimiter=' ', all_readings=False, container='[]', accented=True): """Convert a string's Chinese characters to Pinyin readings. *s* is a string containing Chinese characters. *accented* is a boolean value indicating whether to return accented or numbered Pinyin readings. ...
[ "def", "to_pinyin", "(", "s", ",", "delimiter", "=", "' '", ",", "all_readings", "=", "False", ",", "container", "=", "'[]'", ",", "accented", "=", "True", ")", ":", "hanzi", "=", "s", "pinyin", "=", "''", "# Process the given string.", "while", "hanzi", ...
Convert a string's Chinese characters to Pinyin readings. *s* is a string containing Chinese characters. *accented* is a boolean value indicating whether to return accented or numbered Pinyin readings. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differenti...
[ "Convert", "a", "string", "s", "Chinese", "characters", "to", "Pinyin", "readings", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L89-L168
tsroten/dragonmapper
dragonmapper/hanzi.py
to_zhuyin
def to_zhuyin(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to Zhuyin readings. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and charact...
python
def to_zhuyin(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to Zhuyin readings. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and charact...
[ "def", "to_zhuyin", "(", "s", ",", "delimiter", "=", "' '", ",", "all_readings", "=", "False", ",", "container", "=", "'[]'", ")", ":", "numbered_pinyin", "=", "to_pinyin", "(", "s", ",", "delimiter", ",", "all_readings", ",", "container", ",", "False", ...
Convert a string's Chinese characters to Zhuyin readings. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and characters so that a more accurate reading can be returned. *all_readings*...
[ "Convert", "a", "string", "s", "Chinese", "characters", "to", "Zhuyin", "readings", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L171-L191
tsroten/dragonmapper
dragonmapper/hanzi.py
to_ipa
def to_ipa(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to IPA. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and characters so that a m...
python
def to_ipa(s, delimiter=' ', all_readings=False, container='[]'): """Convert a string's Chinese characters to IPA. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and characters so that a m...
[ "def", "to_ipa", "(", "s", ",", "delimiter", "=", "' '", ",", "all_readings", "=", "False", ",", "container", "=", "'[]'", ")", ":", "numbered_pinyin", "=", "to_pinyin", "(", "s", ",", "delimiter", ",", "all_readings", ",", "container", ",", "False", ")"...
Convert a string's Chinese characters to IPA. *s* is a string containing Chinese characters. *delimiter* is the character used to indicate word boundaries in *s*. This is used to differentiate between words and characters so that a more accurate reading can be returned. *all_readings* is a boolea...
[ "Convert", "a", "string", "s", "Chinese", "characters", "to", "IPA", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L194-L214
tsroten/dragonmapper
dragonmapper/transcriptions.py
_load_data
def _load_data(): """Load the transcription mapping data into a dictionary.""" lines = dragonmapper.data.load_data_file('transcriptions.csv') pinyin_map, zhuyin_map, ipa_map = {}, {}, {} for line in lines: p, z, i = line.split(',') pinyin_map[p] = {'Zhuyin': z, 'IPA': i} zhuyin_m...
python
def _load_data(): """Load the transcription mapping data into a dictionary.""" lines = dragonmapper.data.load_data_file('transcriptions.csv') pinyin_map, zhuyin_map, ipa_map = {}, {}, {} for line in lines: p, z, i = line.split(',') pinyin_map[p] = {'Zhuyin': z, 'IPA': i} zhuyin_m...
[ "def", "_load_data", "(", ")", ":", "lines", "=", "dragonmapper", ".", "data", ".", "load_data_file", "(", "'transcriptions.csv'", ")", "pinyin_map", ",", "zhuyin_map", ",", "ipa_map", "=", "{", "}", ",", "{", "}", ",", "{", "}", "for", "line", "in", "...
Load the transcription mapping data into a dictionary.
[ "Load", "the", "transcription", "mapping", "data", "into", "a", "dictionary", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L46-L55
tsroten/dragonmapper
dragonmapper/transcriptions.py
_numbered_vowel_to_accented
def _numbered_vowel_to_accented(vowel, tone): """Convert a numbered Pinyin vowel to an accented Pinyin vowel.""" if isinstance(tone, int): tone = str(tone) return _PINYIN_TONES[vowel + tone]
python
def _numbered_vowel_to_accented(vowel, tone): """Convert a numbered Pinyin vowel to an accented Pinyin vowel.""" if isinstance(tone, int): tone = str(tone) return _PINYIN_TONES[vowel + tone]
[ "def", "_numbered_vowel_to_accented", "(", "vowel", ",", "tone", ")", ":", "if", "isinstance", "(", "tone", ",", "int", ")", ":", "tone", "=", "str", "(", "tone", ")", "return", "_PINYIN_TONES", "[", "vowel", "+", "tone", "]" ]
Convert a numbered Pinyin vowel to an accented Pinyin vowel.
[ "Convert", "a", "numbered", "Pinyin", "vowel", "to", "an", "accented", "Pinyin", "vowel", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L69-L73
tsroten/dragonmapper
dragonmapper/transcriptions.py
_accented_vowel_to_numbered
def _accented_vowel_to_numbered(vowel): """Convert an accented Pinyin vowel to a numbered Pinyin vowel.""" for numbered_vowel, accented_vowel in _PINYIN_TONES.items(): if vowel == accented_vowel: return tuple(numbered_vowel)
python
def _accented_vowel_to_numbered(vowel): """Convert an accented Pinyin vowel to a numbered Pinyin vowel.""" for numbered_vowel, accented_vowel in _PINYIN_TONES.items(): if vowel == accented_vowel: return tuple(numbered_vowel)
[ "def", "_accented_vowel_to_numbered", "(", "vowel", ")", ":", "for", "numbered_vowel", ",", "accented_vowel", "in", "_PINYIN_TONES", ".", "items", "(", ")", ":", "if", "vowel", "==", "accented_vowel", ":", "return", "tuple", "(", "numbered_vowel", ")" ]
Convert an accented Pinyin vowel to a numbered Pinyin vowel.
[ "Convert", "an", "accented", "Pinyin", "vowel", "to", "a", "numbered", "Pinyin", "vowel", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L76-L80
tsroten/dragonmapper
dragonmapper/transcriptions.py
_parse_numbered_syllable
def _parse_numbered_syllable(unparsed_syllable): """Return the syllable and tone of a numbered Pinyin syllable.""" tone_number = unparsed_syllable[-1] if not tone_number.isdigit(): syllable, tone = unparsed_syllable, '5' elif tone_number == '0': syllable, tone = unparsed_syllable[:-1], '...
python
def _parse_numbered_syllable(unparsed_syllable): """Return the syllable and tone of a numbered Pinyin syllable.""" tone_number = unparsed_syllable[-1] if not tone_number.isdigit(): syllable, tone = unparsed_syllable, '5' elif tone_number == '0': syllable, tone = unparsed_syllable[:-1], '...
[ "def", "_parse_numbered_syllable", "(", "unparsed_syllable", ")", ":", "tone_number", "=", "unparsed_syllable", "[", "-", "1", "]", "if", "not", "tone_number", ".", "isdigit", "(", ")", ":", "syllable", ",", "tone", "=", "unparsed_syllable", ",", "'5'", "elif"...
Return the syllable and tone of a numbered Pinyin syllable.
[ "Return", "the", "syllable", "and", "tone", "of", "a", "numbered", "Pinyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L83-L94
tsroten/dragonmapper
dragonmapper/transcriptions.py
_parse_accented_syllable
def _parse_accented_syllable(unparsed_syllable): """Return the syllable and tone of an accented Pinyin syllable. Any accented vowels are returned without their accents. Implements the following algorithm: 1. If the syllable has an accent mark, convert that vowel to a regular vowel and add the...
python
def _parse_accented_syllable(unparsed_syllable): """Return the syllable and tone of an accented Pinyin syllable. Any accented vowels are returned without their accents. Implements the following algorithm: 1. If the syllable has an accent mark, convert that vowel to a regular vowel and add the...
[ "def", "_parse_accented_syllable", "(", "unparsed_syllable", ")", ":", "if", "unparsed_syllable", "[", "0", "]", "==", "'\\u00B7'", ":", "# Special case for middle dot tone mark.", "return", "unparsed_syllable", "[", "1", ":", "]", ",", "'5'", "for", "character", "i...
Return the syllable and tone of an accented Pinyin syllable. Any accented vowels are returned without their accents. Implements the following algorithm: 1. If the syllable has an accent mark, convert that vowel to a regular vowel and add the tone to the end of the syllable. 2. Otherwise, assu...
[ "Return", "the", "syllable", "and", "tone", "of", "an", "accented", "Pinyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L97-L116
tsroten/dragonmapper
dragonmapper/transcriptions.py
_parse_zhuyin_syllable
def _parse_zhuyin_syllable(unparsed_syllable): """Return the syllable and tone of a Zhuyin syllable.""" zhuyin_tone = unparsed_syllable[-1] if zhuyin_tone in zhon.zhuyin.characters: syllable, tone = unparsed_syllable, '1' elif zhuyin_tone in zhon.zhuyin.marks: for tone_number, tone_mark ...
python
def _parse_zhuyin_syllable(unparsed_syllable): """Return the syllable and tone of a Zhuyin syllable.""" zhuyin_tone = unparsed_syllable[-1] if zhuyin_tone in zhon.zhuyin.characters: syllable, tone = unparsed_syllable, '1' elif zhuyin_tone in zhon.zhuyin.marks: for tone_number, tone_mark ...
[ "def", "_parse_zhuyin_syllable", "(", "unparsed_syllable", ")", ":", "zhuyin_tone", "=", "unparsed_syllable", "[", "-", "1", "]", "if", "zhuyin_tone", "in", "zhon", ".", "zhuyin", ".", "characters", ":", "syllable", ",", "tone", "=", "unparsed_syllable", ",", ...
Return the syllable and tone of a Zhuyin syllable.
[ "Return", "the", "syllable", "and", "tone", "of", "a", "Zhuyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L132-L144
tsroten/dragonmapper
dragonmapper/transcriptions.py
_parse_ipa_syllable
def _parse_ipa_syllable(unparsed_syllable): """Return the syllable and tone of an IPA syllable.""" ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS}, unparsed_syllable) if not ipa_tone: syllable, tone = unparsed_syllable, '5' else: for tone_number, tone...
python
def _parse_ipa_syllable(unparsed_syllable): """Return the syllable and tone of an IPA syllable.""" ipa_tone = re.search('[%(marks)s]+' % {'marks': _IPA_MARKS}, unparsed_syllable) if not ipa_tone: syllable, tone = unparsed_syllable, '5' else: for tone_number, tone...
[ "def", "_parse_ipa_syllable", "(", "unparsed_syllable", ")", ":", "ipa_tone", "=", "re", ".", "search", "(", "'[%(marks)s]+'", "%", "{", "'marks'", ":", "_IPA_MARKS", "}", ",", "unparsed_syllable", ")", "if", "not", "ipa_tone", ":", "syllable", ",", "tone", ...
Return the syllable and tone of an IPA syllable.
[ "Return", "the", "syllable", "and", "tone", "of", "an", "IPA", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L147-L159
tsroten/dragonmapper
dragonmapper/transcriptions.py
_restore_case
def _restore_case(s, memory): """Restore a lowercase string's characters to their original case.""" cased_s = [] for i, c in enumerate(s): if i + 1 > len(memory): break cased_s.append(c if memory[i] else c.upper()) return ''.join(cased_s)
python
def _restore_case(s, memory): """Restore a lowercase string's characters to their original case.""" cased_s = [] for i, c in enumerate(s): if i + 1 > len(memory): break cased_s.append(c if memory[i] else c.upper()) return ''.join(cased_s)
[ "def", "_restore_case", "(", "s", ",", "memory", ")", ":", "cased_s", "=", "[", "]", "for", "i", ",", "c", "in", "enumerate", "(", "s", ")", ":", "if", "i", "+", "1", ">", "len", "(", "memory", ")", ":", "break", "cased_s", ".", "append", "(", ...
Restore a lowercase string's characters to their original case.
[ "Restore", "a", "lowercase", "string", "s", "characters", "to", "their", "original", "case", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L167-L174
tsroten/dragonmapper
dragonmapper/transcriptions.py
numbered_syllable_to_accented
def numbered_syllable_to_accented(s): """Convert numbered Pinyin syllable *s* to an accented Pinyin syllable. It implements the following algorithm to determine where to place tone marks: 1. If the syllable has an 'a', 'e', or 'o' (in that order), put the tone mark over that vowel. 2. Othe...
python
def numbered_syllable_to_accented(s): """Convert numbered Pinyin syllable *s* to an accented Pinyin syllable. It implements the following algorithm to determine where to place tone marks: 1. If the syllable has an 'a', 'e', or 'o' (in that order), put the tone mark over that vowel. 2. Othe...
[ "def", "numbered_syllable_to_accented", "(", "s", ")", ":", "if", "s", "==", "'r5'", ":", "return", "'r'", "# Special case for 'r' suffix.", "lowercase_syllable", ",", "case_memory", "=", "_lower_case", "(", "s", ")", "syllable", ",", "tone", "=", "_parse_numbered...
Convert numbered Pinyin syllable *s* to an accented Pinyin syllable. It implements the following algorithm to determine where to place tone marks: 1. If the syllable has an 'a', 'e', or 'o' (in that order), put the tone mark over that vowel. 2. Otherwise, put the tone mark on the last vowel.
[ "Convert", "numbered", "Pinyin", "syllable", "*", "s", "*", "to", "an", "accented", "Pinyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L177-L209
tsroten/dragonmapper
dragonmapper/transcriptions.py
accented_syllable_to_numbered
def accented_syllable_to_numbered(s): """Convert accented Pinyin syllable *s* to a numbered Pinyin syllable.""" if s[0] == '\u00B7': lowercase_syllable, case_memory = _lower_case(s[1:]) lowercase_syllable = '\u00B7' + lowercase_syllable else: lowercase_syllable, case_memory = _lower_...
python
def accented_syllable_to_numbered(s): """Convert accented Pinyin syllable *s* to a numbered Pinyin syllable.""" if s[0] == '\u00B7': lowercase_syllable, case_memory = _lower_case(s[1:]) lowercase_syllable = '\u00B7' + lowercase_syllable else: lowercase_syllable, case_memory = _lower_...
[ "def", "accented_syllable_to_numbered", "(", "s", ")", ":", "if", "s", "[", "0", "]", "==", "'\\u00B7'", ":", "lowercase_syllable", ",", "case_memory", "=", "_lower_case", "(", "s", "[", "1", ":", "]", ")", "lowercase_syllable", "=", "'\\u00B7'", "+", "low...
Convert accented Pinyin syllable *s* to a numbered Pinyin syllable.
[ "Convert", "accented", "Pinyin", "syllable", "*", "s", "*", "to", "a", "numbered", "Pinyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L212-L220
tsroten/dragonmapper
dragonmapper/transcriptions.py
pinyin_syllable_to_zhuyin
def pinyin_syllable_to_zhuyin(s): """Convert Pinyin syllable *s* to a Zhuyin syllable.""" pinyin_syllable, tone = _parse_pinyin_syllable(s) try: zhuyin_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['Zhuyin'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) return z...
python
def pinyin_syllable_to_zhuyin(s): """Convert Pinyin syllable *s* to a Zhuyin syllable.""" pinyin_syllable, tone = _parse_pinyin_syllable(s) try: zhuyin_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['Zhuyin'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) return z...
[ "def", "pinyin_syllable_to_zhuyin", "(", "s", ")", ":", "pinyin_syllable", ",", "tone", "=", "_parse_pinyin_syllable", "(", "s", ")", "try", ":", "zhuyin_syllable", "=", "_PINYIN_MAP", "[", "pinyin_syllable", ".", "lower", "(", ")", "]", "[", "'Zhuyin'", "]", ...
Convert Pinyin syllable *s* to a Zhuyin syllable.
[ "Convert", "Pinyin", "syllable", "*", "s", "*", "to", "a", "Zhuyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L223-L230
tsroten/dragonmapper
dragonmapper/transcriptions.py
pinyin_syllable_to_ipa
def pinyin_syllable_to_ipa(s): """Convert Pinyin syllable *s* to an IPA syllable.""" pinyin_syllable, tone = _parse_pinyin_syllable(s) try: ipa_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['IPA'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) return ipa_syllable...
python
def pinyin_syllable_to_ipa(s): """Convert Pinyin syllable *s* to an IPA syllable.""" pinyin_syllable, tone = _parse_pinyin_syllable(s) try: ipa_syllable = _PINYIN_MAP[pinyin_syllable.lower()]['IPA'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) return ipa_syllable...
[ "def", "pinyin_syllable_to_ipa", "(", "s", ")", ":", "pinyin_syllable", ",", "tone", "=", "_parse_pinyin_syllable", "(", "s", ")", "try", ":", "ipa_syllable", "=", "_PINYIN_MAP", "[", "pinyin_syllable", ".", "lower", "(", ")", "]", "[", "'IPA'", "]", "except...
Convert Pinyin syllable *s* to an IPA syllable.
[ "Convert", "Pinyin", "syllable", "*", "s", "*", "to", "an", "IPA", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L233-L240
tsroten/dragonmapper
dragonmapper/transcriptions.py
_zhuyin_syllable_to_numbered
def _zhuyin_syllable_to_numbered(s): """Convert Zhuyin syllable *s* to a numbered Pinyin syllable.""" zhuyin_syllable, tone = _parse_zhuyin_syllable(s) try: pinyin_syllable = _ZHUYIN_MAP[zhuyin_syllable]['Pinyin'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) retu...
python
def _zhuyin_syllable_to_numbered(s): """Convert Zhuyin syllable *s* to a numbered Pinyin syllable.""" zhuyin_syllable, tone = _parse_zhuyin_syllable(s) try: pinyin_syllable = _ZHUYIN_MAP[zhuyin_syllable]['Pinyin'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) retu...
[ "def", "_zhuyin_syllable_to_numbered", "(", "s", ")", ":", "zhuyin_syllable", ",", "tone", "=", "_parse_zhuyin_syllable", "(", "s", ")", "try", ":", "pinyin_syllable", "=", "_ZHUYIN_MAP", "[", "zhuyin_syllable", "]", "[", "'Pinyin'", "]", "except", "KeyError", "...
Convert Zhuyin syllable *s* to a numbered Pinyin syllable.
[ "Convert", "Zhuyin", "syllable", "*", "s", "*", "to", "a", "numbered", "Pinyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L243-L250
tsroten/dragonmapper
dragonmapper/transcriptions.py
_ipa_syllable_to_numbered
def _ipa_syllable_to_numbered(s): """Convert IPA syllable *s* to a numbered Pinyin syllable.""" ipa_syllable, tone = _parse_ipa_syllable(s) try: pinyin_syllable = _IPA_MAP[ipa_syllable]['Pinyin'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) return pinyin_syllable...
python
def _ipa_syllable_to_numbered(s): """Convert IPA syllable *s* to a numbered Pinyin syllable.""" ipa_syllable, tone = _parse_ipa_syllable(s) try: pinyin_syllable = _IPA_MAP[ipa_syllable]['Pinyin'] except KeyError: raise ValueError('Not a valid syllable: %s' % s) return pinyin_syllable...
[ "def", "_ipa_syllable_to_numbered", "(", "s", ")", ":", "ipa_syllable", ",", "tone", "=", "_parse_ipa_syllable", "(", "s", ")", "try", ":", "pinyin_syllable", "=", "_IPA_MAP", "[", "ipa_syllable", "]", "[", "'Pinyin'", "]", "except", "KeyError", ":", "raise", ...
Convert IPA syllable *s* to a numbered Pinyin syllable.
[ "Convert", "IPA", "syllable", "*", "s", "*", "to", "a", "numbered", "Pinyin", "syllable", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L278-L285
tsroten/dragonmapper
dragonmapper/transcriptions.py
_convert
def _convert(s, re_pattern, syllable_function, add_apostrophes=False, remove_apostrophes=False, separate_syllables=False): """Convert a string's syllables to a different transcription system.""" original = s new = '' while original: match = re.search(re_pattern, original, re.IGNOREC...
python
def _convert(s, re_pattern, syllable_function, add_apostrophes=False, remove_apostrophes=False, separate_syllables=False): """Convert a string's syllables to a different transcription system.""" original = s new = '' while original: match = re.search(re_pattern, original, re.IGNOREC...
[ "def", "_convert", "(", "s", ",", "re_pattern", ",", "syllable_function", ",", "add_apostrophes", "=", "False", ",", "remove_apostrophes", "=", "False", ",", "separate_syllables", "=", "False", ")", ":", "original", "=", "s", "new", "=", "''", "while", "orig...
Convert a string's syllables to a different transcription system.
[ "Convert", "a", "string", "s", "syllables", "to", "a", "different", "transcription", "system", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L313-L343
tsroten/dragonmapper
dragonmapper/transcriptions.py
numbered_to_accented
def numbered_to_accented(s): """Convert all numbered Pinyin syllables in *s* to accented Pinyin.""" return _convert(s, zhon.pinyin.syllable, numbered_syllable_to_accented, add_apostrophes=True)
python
def numbered_to_accented(s): """Convert all numbered Pinyin syllables in *s* to accented Pinyin.""" return _convert(s, zhon.pinyin.syllable, numbered_syllable_to_accented, add_apostrophes=True)
[ "def", "numbered_to_accented", "(", "s", ")", ":", "return", "_convert", "(", "s", ",", "zhon", ".", "pinyin", ".", "syllable", ",", "numbered_syllable_to_accented", ",", "add_apostrophes", "=", "True", ")" ]
Convert all numbered Pinyin syllables in *s* to accented Pinyin.
[ "Convert", "all", "numbered", "Pinyin", "syllables", "in", "*", "s", "*", "to", "accented", "Pinyin", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L346-L349
tsroten/dragonmapper
dragonmapper/transcriptions.py
pinyin_to_zhuyin
def pinyin_to_zhuyin(s): """Convert all Pinyin syllables in *s* to Zhuyin. Spaces are added between connected syllables and syllable-separating apostrophes are removed. """ return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_zhuyin, remove_apostrophes=True, separate_syl...
python
def pinyin_to_zhuyin(s): """Convert all Pinyin syllables in *s* to Zhuyin. Spaces are added between connected syllables and syllable-separating apostrophes are removed. """ return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_zhuyin, remove_apostrophes=True, separate_syl...
[ "def", "pinyin_to_zhuyin", "(", "s", ")", ":", "return", "_convert", "(", "s", ",", "zhon", ".", "pinyin", ".", "syllable", ",", "pinyin_syllable_to_zhuyin", ",", "remove_apostrophes", "=", "True", ",", "separate_syllables", "=", "True", ")" ]
Convert all Pinyin syllables in *s* to Zhuyin. Spaces are added between connected syllables and syllable-separating apostrophes are removed.
[ "Convert", "all", "Pinyin", "syllables", "in", "*", "s", "*", "to", "Zhuyin", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L357-L365
tsroten/dragonmapper
dragonmapper/transcriptions.py
pinyin_to_ipa
def pinyin_to_ipa(s): """Convert all Pinyin syllables in *s* to IPA. Spaces are added between connected syllables and syllable-separating apostrophes are removed. """ return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_ipa, remove_apostrophes=True, separate_syllables=Tr...
python
def pinyin_to_ipa(s): """Convert all Pinyin syllables in *s* to IPA. Spaces are added between connected syllables and syllable-separating apostrophes are removed. """ return _convert(s, zhon.pinyin.syllable, pinyin_syllable_to_ipa, remove_apostrophes=True, separate_syllables=Tr...
[ "def", "pinyin_to_ipa", "(", "s", ")", ":", "return", "_convert", "(", "s", ",", "zhon", ".", "pinyin", ".", "syllable", ",", "pinyin_syllable_to_ipa", ",", "remove_apostrophes", "=", "True", ",", "separate_syllables", "=", "True", ")" ]
Convert all Pinyin syllables in *s* to IPA. Spaces are added between connected syllables and syllable-separating apostrophes are removed.
[ "Convert", "all", "Pinyin", "syllables", "in", "*", "s", "*", "to", "IPA", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L368-L376
tsroten/dragonmapper
dragonmapper/transcriptions.py
zhuyin_to_pinyin
def zhuyin_to_pinyin(s, accented=True): """Convert all Zhuyin syllables in *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ if accented: function = _zhuyin_syllable_to_accented else: ...
python
def zhuyin_to_pinyin(s, accented=True): """Convert all Zhuyin syllables in *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ if accented: function = _zhuyin_syllable_to_accented else: ...
[ "def", "zhuyin_to_pinyin", "(", "s", ",", "accented", "=", "True", ")", ":", "if", "accented", ":", "function", "=", "_zhuyin_syllable_to_accented", "else", ":", "function", "=", "_zhuyin_syllable_to_numbered", "return", "_convert", "(", "s", ",", "zhon", ".", ...
Convert all Zhuyin syllables in *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone.
[ "Convert", "all", "Zhuyin", "syllables", "in", "*", "s", "*", "to", "Pinyin", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L379-L390
tsroten/dragonmapper
dragonmapper/transcriptions.py
ipa_to_pinyin
def ipa_to_pinyin(s, accented=True): """Convert all IPA syllables in *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ if accented: function = _ipa_syllable_to_accented else: functio...
python
def ipa_to_pinyin(s, accented=True): """Convert all IPA syllables in *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ if accented: function = _ipa_syllable_to_accented else: functio...
[ "def", "ipa_to_pinyin", "(", "s", ",", "accented", "=", "True", ")", ":", "if", "accented", ":", "function", "=", "_ipa_syllable_to_accented", "else", ":", "function", "=", "_ipa_syllable_to_numbered", "return", "_convert", "(", "s", ",", "_IPA_SYLLABLE", ",", ...
Convert all IPA syllables in *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone.
[ "Convert", "all", "IPA", "syllables", "in", "*", "s", "*", "to", "Pinyin", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L398-L409
tsroten/dragonmapper
dragonmapper/transcriptions.py
to_pinyin
def to_pinyin(s, accented=True): """Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ identity = identify(s) if identity == PINYIN: if _has_accented_vowels(s): return s i...
python
def to_pinyin(s, accented=True): """Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone. """ identity = identify(s) if identity == PINYIN: if _has_accented_vowels(s): return s i...
[ "def", "to_pinyin", "(", "s", ",", "accented", "=", "True", ")", ":", "identity", "=", "identify", "(", "s", ")", "if", "identity", "==", "PINYIN", ":", "if", "_has_accented_vowels", "(", "s", ")", ":", "return", "s", "if", "accented", "else", "accente...
Convert *s* to Pinyin. If *accented* is ``True``, diacritics are added to the Pinyin syllables. If it's ``False``, numbers are used to indicate tone.
[ "Convert", "*", "s", "*", "to", "Pinyin", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L417-L435
tsroten/dragonmapper
dragonmapper/transcriptions.py
to_zhuyin
def to_zhuyin(s): """Convert *s* to Zhuyin.""" identity = identify(s) if identity == ZHUYIN: return s elif identity == PINYIN: return pinyin_to_zhuyin(s) elif identity == IPA: return ipa_to_zhuyin(s) else: raise ValueError("String is not a valid Chinese transcript...
python
def to_zhuyin(s): """Convert *s* to Zhuyin.""" identity = identify(s) if identity == ZHUYIN: return s elif identity == PINYIN: return pinyin_to_zhuyin(s) elif identity == IPA: return ipa_to_zhuyin(s) else: raise ValueError("String is not a valid Chinese transcript...
[ "def", "to_zhuyin", "(", "s", ")", ":", "identity", "=", "identify", "(", "s", ")", "if", "identity", "==", "ZHUYIN", ":", "return", "s", "elif", "identity", "==", "PINYIN", ":", "return", "pinyin_to_zhuyin", "(", "s", ")", "elif", "identity", "==", "I...
Convert *s* to Zhuyin.
[ "Convert", "*", "s", "*", "to", "Zhuyin", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L438-L448
tsroten/dragonmapper
dragonmapper/transcriptions.py
to_ipa
def to_ipa(s): """Convert *s* to IPA.""" identity = identify(s) if identity == IPA: return s elif identity == PINYIN: return pinyin_to_ipa(s) elif identity == ZHUYIN: return zhuyin_to_ipa(s) else: raise ValueError("String is not a valid Chinese transcription.")
python
def to_ipa(s): """Convert *s* to IPA.""" identity = identify(s) if identity == IPA: return s elif identity == PINYIN: return pinyin_to_ipa(s) elif identity == ZHUYIN: return zhuyin_to_ipa(s) else: raise ValueError("String is not a valid Chinese transcription.")
[ "def", "to_ipa", "(", "s", ")", ":", "identity", "=", "identify", "(", "s", ")", "if", "identity", "==", "IPA", ":", "return", "s", "elif", "identity", "==", "PINYIN", ":", "return", "pinyin_to_ipa", "(", "s", ")", "elif", "identity", "==", "ZHUYIN", ...
Convert *s* to IPA.
[ "Convert", "*", "s", "*", "to", "IPA", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L451-L461
tsroten/dragonmapper
dragonmapper/transcriptions.py
_is_pattern_match
def _is_pattern_match(re_pattern, s): """Check if a re pattern expression matches an entire string.""" match = re.match(re_pattern, s, re.I) return match.group() == s if match else False
python
def _is_pattern_match(re_pattern, s): """Check if a re pattern expression matches an entire string.""" match = re.match(re_pattern, s, re.I) return match.group() == s if match else False
[ "def", "_is_pattern_match", "(", "re_pattern", ",", "s", ")", ":", "match", "=", "re", ".", "match", "(", "re_pattern", ",", "s", ",", "re", ".", "I", ")", "return", "match", ".", "group", "(", ")", "==", "s", "if", "match", "else", "False" ]
Check if a re pattern expression matches an entire string.
[ "Check", "if", "a", "re", "pattern", "expression", "matches", "an", "entire", "string", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L464-L467
tsroten/dragonmapper
dragonmapper/transcriptions.py
is_pinyin
def is_pinyin(s): """Check if *s* consists of valid Pinyin.""" re_pattern = ('(?:%(word)s|[ \t%(punctuation)s])+' % {'word': zhon.pinyin.word, 'punctuation': zhon.pinyin.punctuation}) return _is_pattern_match(re_pattern, s)
python
def is_pinyin(s): """Check if *s* consists of valid Pinyin.""" re_pattern = ('(?:%(word)s|[ \t%(punctuation)s])+' % {'word': zhon.pinyin.word, 'punctuation': zhon.pinyin.punctuation}) return _is_pattern_match(re_pattern, s)
[ "def", "is_pinyin", "(", "s", ")", ":", "re_pattern", "=", "(", "'(?:%(word)s|[ \\t%(punctuation)s])+'", "%", "{", "'word'", ":", "zhon", ".", "pinyin", ".", "word", ",", "'punctuation'", ":", "zhon", ".", "pinyin", ".", "punctuation", "}", ")", "return", ...
Check if *s* consists of valid Pinyin.
[ "Check", "if", "*", "s", "*", "consists", "of", "valid", "Pinyin", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L470-L475
tsroten/dragonmapper
dragonmapper/transcriptions.py
is_zhuyin_compatible
def is_zhuyin_compatible(s): """Checks if *s* is consists of Zhuyin-compatible characters. This does not check if *s* contains valid Zhuyin syllables; for that see :func:`is_zhuyin`. Besides Zhuyin characters and tone marks, spaces are also accepted. This function checks that all characters in *s*...
python
def is_zhuyin_compatible(s): """Checks if *s* is consists of Zhuyin-compatible characters. This does not check if *s* contains valid Zhuyin syllables; for that see :func:`is_zhuyin`. Besides Zhuyin characters and tone marks, spaces are also accepted. This function checks that all characters in *s*...
[ "def", "is_zhuyin_compatible", "(", "s", ")", ":", "printable_zhuyin", "=", "zhon", ".", "zhuyin", ".", "characters", "+", "zhon", ".", "zhuyin", ".", "marks", "+", "' '", "return", "_is_pattern_match", "(", "'[%s]+'", "%", "printable_zhuyin", ",", "s", ")" ...
Checks if *s* is consists of Zhuyin-compatible characters. This does not check if *s* contains valid Zhuyin syllables; for that see :func:`is_zhuyin`. Besides Zhuyin characters and tone marks, spaces are also accepted. This function checks that all characters in *s* exist in :data:`zhon.zhuyin.cha...
[ "Checks", "if", "*", "s", "*", "is", "consists", "of", "Zhuyin", "-", "compatible", "characters", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L497-L509
tsroten/dragonmapper
dragonmapper/transcriptions.py
is_ipa
def is_ipa(s): """Check if *s* consists of valid Chinese IPA.""" re_pattern = ('(?:%(syllable)s|[ \t%(punctuation)s])+' % {'syllable': _IPA_SYLLABLE, 'punctuation': zhon.pinyin.punctuation}) return _is_pattern_match(re_pattern, s)
python
def is_ipa(s): """Check if *s* consists of valid Chinese IPA.""" re_pattern = ('(?:%(syllable)s|[ \t%(punctuation)s])+' % {'syllable': _IPA_SYLLABLE, 'punctuation': zhon.pinyin.punctuation}) return _is_pattern_match(re_pattern, s)
[ "def", "is_ipa", "(", "s", ")", ":", "re_pattern", "=", "(", "'(?:%(syllable)s|[ \\t%(punctuation)s])+'", "%", "{", "'syllable'", ":", "_IPA_SYLLABLE", ",", "'punctuation'", ":", "zhon", ".", "pinyin", ".", "punctuation", "}", ")", "return", "_is_pattern_match", ...
Check if *s* consists of valid Chinese IPA.
[ "Check", "if", "*", "s", "*", "consists", "of", "valid", "Chinese", "IPA", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L512-L517
tsroten/dragonmapper
dragonmapper/transcriptions.py
identify
def identify(s): """Identify a given string's transcription system. *s* is the string to identify. The string is checked to see if its contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`, :data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the string's identity. If *s* ...
python
def identify(s): """Identify a given string's transcription system. *s* is the string to identify. The string is checked to see if its contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`, :data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the string's identity. If *s* ...
[ "def", "identify", "(", "s", ")", ":", "if", "is_pinyin", "(", "s", ")", ":", "return", "PINYIN", "elif", "is_zhuyin", "(", "s", ")", ":", "return", "ZHUYIN", "elif", "is_ipa", "(", "s", ")", ":", "return", "IPA", "else", ":", "return", "UNKNOWN" ]
Identify a given string's transcription system. *s* is the string to identify. The string is checked to see if its contents are valid Pinyin, Zhuyin, or IPA. The :data:`PINYIN`, :data:`ZHUYIN`, and :data:`IPA` constants are returned to indicate the string's identity. If *s* is not a valid transcrip...
[ "Identify", "a", "given", "string", "s", "transcription", "system", "." ]
train
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L520-L548
lanius/tinyik
tinyik/optimizer.py
NewtonOptimizer.prepare
def prepare(self, f): """Accept an objective function for optimization.""" self.g = autograd.grad(f) self.h = autograd.hessian(f)
python
def prepare(self, f): """Accept an objective function for optimization.""" self.g = autograd.grad(f) self.h = autograd.hessian(f)
[ "def", "prepare", "(", "self", ",", "f", ")", ":", "self", ".", "g", "=", "autograd", ".", "grad", "(", "f", ")", "self", ".", "h", "=", "autograd", ".", "hessian", "(", "f", ")" ]
Accept an objective function for optimization.
[ "Accept", "an", "objective", "function", "for", "optimization", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L16-L19
lanius/tinyik
tinyik/optimizer.py
NewtonOptimizer.optimize
def optimize(self, x0, target): """Calculate an optimum argument of an objective function.""" x = x0 for _ in range(self.maxiter): delta = np.linalg.solve(self.h(x, target), -self.g(x, target)) x = x + delta if np.linalg.norm(delta) < self.tol: ...
python
def optimize(self, x0, target): """Calculate an optimum argument of an objective function.""" x = x0 for _ in range(self.maxiter): delta = np.linalg.solve(self.h(x, target), -self.g(x, target)) x = x + delta if np.linalg.norm(delta) < self.tol: ...
[ "def", "optimize", "(", "self", ",", "x0", ",", "target", ")", ":", "x", "=", "x0", "for", "_", "in", "range", "(", "self", ".", "maxiter", ")", ":", "delta", "=", "np", ".", "linalg", ".", "solve", "(", "self", ".", "h", "(", "x", ",", "targ...
Calculate an optimum argument of an objective function.
[ "Calculate", "an", "optimum", "argument", "of", "an", "objective", "function", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L21-L29
lanius/tinyik
tinyik/optimizer.py
ConjugateGradientOptimizer.optimize
def optimize(self, x0, target): """Calculate an optimum argument of an objective function.""" x = x0 for i in range(self.maxiter): g = self.g(x, target) h = self.h(x, target) if i == 0: alpha = 0 m = g else: ...
python
def optimize(self, x0, target): """Calculate an optimum argument of an objective function.""" x = x0 for i in range(self.maxiter): g = self.g(x, target) h = self.h(x, target) if i == 0: alpha = 0 m = g else: ...
[ "def", "optimize", "(", "self", ",", "x0", ",", "target", ")", ":", "x", "=", "x0", "for", "i", "in", "range", "(", "self", ".", "maxiter", ")", ":", "g", "=", "self", ".", "g", "(", "x", ",", "target", ")", "h", "=", "self", ".", "h", "(",...
Calculate an optimum argument of an objective function.
[ "Calculate", "an", "optimum", "argument", "of", "an", "objective", "function", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L69-L86
lanius/tinyik
tinyik/optimizer.py
ScipyOptimizer.optimize
def optimize(self, angles0, target): """Calculate an optimum argument of an objective function.""" def new_objective(angles): return self.f(angles, target) return scipy.optimize.minimize( new_objective, angles0, **self.optimizer_opt).x
python
def optimize(self, angles0, target): """Calculate an optimum argument of an objective function.""" def new_objective(angles): return self.f(angles, target) return scipy.optimize.minimize( new_objective, angles0, **self.optimizer_opt).x
[ "def", "optimize", "(", "self", ",", "angles0", ",", "target", ")", ":", "def", "new_objective", "(", "angles", ")", ":", "return", "self", ".", "f", "(", "angles", ",", "target", ")", "return", "scipy", ".", "optimize", ".", "minimize", "(", "new_obje...
Calculate an optimum argument of an objective function.
[ "Calculate", "an", "optimum", "argument", "of", "an", "objective", "function", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L106-L114
lanius/tinyik
tinyik/optimizer.py
ScipySmoothOptimizer.optimize
def optimize(self, angles0, target): """Calculate an optimum argument of an objective function.""" def new_objective(angles): a = angles - angles0 if isinstance(self.smooth_factor, (np.ndarray, list)): if len(a) == len(self.smooth_factor): retu...
python
def optimize(self, angles0, target): """Calculate an optimum argument of an objective function.""" def new_objective(angles): a = angles - angles0 if isinstance(self.smooth_factor, (np.ndarray, list)): if len(a) == len(self.smooth_factor): retu...
[ "def", "optimize", "(", "self", ",", "angles0", ",", "target", ")", ":", "def", "new_objective", "(", "angles", ")", ":", "a", "=", "angles", "-", "angles0", "if", "isinstance", "(", "self", ".", "smooth_factor", ",", "(", "np", ".", "ndarray", ",", ...
Calculate an optimum argument of an objective function.
[ "Calculate", "an", "optimum", "argument", "of", "an", "objective", "function", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L130-L147
lanius/tinyik
tinyik/solver.py
FKSolver.solve
def solve(self, angles): """Calculate a position of the end-effector and return it.""" return reduce( lambda a, m: np.dot(m, a), reversed(self._matrices(angles)), np.array([0., 0., 0., 1.]) )[:3]
python
def solve(self, angles): """Calculate a position of the end-effector and return it.""" return reduce( lambda a, m: np.dot(m, a), reversed(self._matrices(angles)), np.array([0., 0., 0., 1.]) )[:3]
[ "def", "solve", "(", "self", ",", "angles", ")", ":", "return", "reduce", "(", "lambda", "a", ",", "m", ":", "np", ".", "dot", "(", "m", ",", "a", ")", ",", "reversed", "(", "self", ".", "_matrices", "(", "angles", ")", ")", ",", "np", ".", "...
Calculate a position of the end-effector and return it.
[ "Calculate", "a", "position", "of", "the", "end", "-", "effector", "and", "return", "it", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/solver.py#L26-L32
lanius/tinyik
tinyik/solver.py
IKSolver.solve
def solve(self, angles0, target): """Calculate joint angles and returns it.""" return self.optimizer.optimize(np.array(angles0), target)
python
def solve(self, angles0, target): """Calculate joint angles and returns it.""" return self.optimizer.optimize(np.array(angles0), target)
[ "def", "solve", "(", "self", ",", "angles0", ",", "target", ")", ":", "return", "self", ".", "optimizer", ".", "optimize", "(", "np", ".", "array", "(", "angles0", ")", ",", "target", ")" ]
Calculate joint angles and returns it.
[ "Calculate", "joint", "angles", "and", "returns", "it", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/solver.py#L47-L49
lanius/tinyik
tinyik/component.py
Link.matrix
def matrix(self, _): """Return translation matrix in homogeneous coordinates.""" x, y, z = self.coord return np.array([ [1., 0., 0., x], [0., 1., 0., y], [0., 0., 1., z], [0., 0., 0., 1.] ])
python
def matrix(self, _): """Return translation matrix in homogeneous coordinates.""" x, y, z = self.coord return np.array([ [1., 0., 0., x], [0., 1., 0., y], [0., 0., 1., z], [0., 0., 0., 1.] ])
[ "def", "matrix", "(", "self", ",", "_", ")", ":", "x", ",", "y", ",", "z", "=", "self", ".", "coord", "return", "np", ".", "array", "(", "[", "[", "1.", ",", "0.", ",", "0.", ",", "x", "]", ",", "[", "0.", ",", "1.", ",", "0.", ",", "y"...
Return translation matrix in homogeneous coordinates.
[ "Return", "translation", "matrix", "in", "homogeneous", "coordinates", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/component.py#L13-L21
lanius/tinyik
tinyik/component.py
Joint.matrix
def matrix(self, angle): """Return rotation matrix in homogeneous coordinates.""" _rot_mat = { 'x': self._x_rot, 'y': self._y_rot, 'z': self._z_rot } return _rot_mat[self.axis](angle)
python
def matrix(self, angle): """Return rotation matrix in homogeneous coordinates.""" _rot_mat = { 'x': self._x_rot, 'y': self._y_rot, 'z': self._z_rot } return _rot_mat[self.axis](angle)
[ "def", "matrix", "(", "self", ",", "angle", ")", ":", "_rot_mat", "=", "{", "'x'", ":", "self", ".", "_x_rot", ",", "'y'", ":", "self", ".", "_y_rot", ",", "'z'", ":", "self", ".", "_z_rot", "}", "return", "_rot_mat", "[", "self", ".", "axis", "]...
Return rotation matrix in homogeneous coordinates.
[ "Return", "rotation", "matrix", "in", "homogeneous", "coordinates", "." ]
train
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/component.py#L31-L38
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.set_logger
def set_logger(self, logger): """ Set a logger to send debug messages to Parameters ---------- logger : `Logger <http://docs.python.org/2/library/logging.html>`_ A python logger used to get debugging output from this module. """ self.__logger = logger...
python
def set_logger(self, logger): """ Set a logger to send debug messages to Parameters ---------- logger : `Logger <http://docs.python.org/2/library/logging.html>`_ A python logger used to get debugging output from this module. """ self.__logger = logger...
[ "def", "set_logger", "(", "self", ",", "logger", ")", ":", "self", ".", "__logger", "=", "logger", "self", ".", "session", ".", "set_logger", "(", "self", ".", "__logger", ")" ]
Set a logger to send debug messages to Parameters ---------- logger : `Logger <http://docs.python.org/2/library/logging.html>`_ A python logger used to get debugging output from this module.
[ "Set", "a", "logger", "to", "send", "debug", "messages", "to" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L92-L102
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.version
def version(self): """ Return the version number of the Lending Club Investor tool Returns ------- string The version number string """ this_path = os.path.dirname(os.path.realpath(__file__)) version_file = os.path.join(this_path, 'VERSION') ...
python
def version(self): """ Return the version number of the Lending Club Investor tool Returns ------- string The version number string """ this_path = os.path.dirname(os.path.realpath(__file__)) version_file = os.path.join(this_path, 'VERSION') ...
[ "def", "version", "(", "self", ")", ":", "this_path", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "version_file", "=", "os", ".", "path", ".", "join", "(", "this_path", ",", "'VERSION'",...
Return the version number of the Lending Club Investor tool Returns ------- string The version number string
[ "Return", "the", "version", "number", "of", "the", "Lending", "Club", "Investor", "tool" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L104-L115
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.authenticate
def authenticate(self, email=None, password=None): """ Attempt to authenticate the user. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns -...
python
def authenticate(self, email=None, password=None): """ Attempt to authenticate the user. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns -...
[ "def", "authenticate", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ")", ":", "if", "self", ".", "session", ".", "authenticate", "(", "email", ",", "password", ")", ":", "return", "True" ]
Attempt to authenticate the user. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns ------- boolean True if the user authenticated or ra...
[ "Attempt", "to", "authenticate", "the", "user", "." ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L117-L141
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.get_cash_balance
def get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """ cash = False try: response = self.session.get('/browse/cashBalanceAj.action') ...
python
def get_cash_balance(self): """ Returns the account cash balance available for investing Returns ------- float The cash balance in your account. """ cash = False try: response = self.session.get('/browse/cashBalanceAj.action') ...
[ "def", "get_cash_balance", "(", "self", ")", ":", "cash", "=", "False", "try", ":", "response", "=", "self", ".", "session", ".", "get", "(", "'/browse/cashBalanceAj.action'", ")", "json_response", "=", "response", ".", "json", "(", ")", "if", "self", ".",...
Returns the account cash balance available for investing Returns ------- float The cash balance in your account.
[ "Returns", "the", "account", "cash", "balance", "available", "for", "investing" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L154-L186
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.get_portfolio_list
def get_portfolio_list(self, names_only=False): """ Get your list of named portfolios from the lendingclub.com Parameters ---------- names_only : boolean, optional If set to True, the function will return a list of portfolio names, instead of portfolio objects ...
python
def get_portfolio_list(self, names_only=False): """ Get your list of named portfolios from the lendingclub.com Parameters ---------- names_only : boolean, optional If set to True, the function will return a list of portfolio names, instead of portfolio objects ...
[ "def", "get_portfolio_list", "(", "self", ",", "names_only", "=", "False", ")", ":", "folios", "=", "[", "]", "response", "=", "self", ".", "session", ".", "get", "(", "'/data/portfolioManagement?method=getLCPortfolios'", ")", "json_response", "=", "response", "...
Get your list of named portfolios from the lendingclub.com Parameters ---------- names_only : boolean, optional If set to True, the function will return a list of portfolio names, instead of portfolio objects Returns ------- list A list of portfo...
[ "Get", "your", "list", "of", "named", "portfolios", "from", "the", "lendingclub", ".", "com" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L203-L229
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.assign_to_portfolio
def assign_to_portfolio(self, portfolio_name, loan_id, order_id): """ Assign a note to a named portfolio. `loan_id` and `order_id` can be either integer values or lists. If choosing lists, they both **MUST** be the same length and line up. For example, `order_id[5]` must be the order ID ...
python
def assign_to_portfolio(self, portfolio_name, loan_id, order_id): """ Assign a note to a named portfolio. `loan_id` and `order_id` can be either integer values or lists. If choosing lists, they both **MUST** be the same length and line up. For example, `order_id[5]` must be the order ID ...
[ "def", "assign_to_portfolio", "(", "self", ",", "portfolio_name", ",", "loan_id", ",", "order_id", ")", ":", "response", "=", "None", "assert", "type", "(", "loan_id", ")", "==", "type", "(", "order_id", ")", ",", "\"Both loan_id and order_id need to be the same t...
Assign a note to a named portfolio. `loan_id` and `order_id` can be either integer values or lists. If choosing lists, they both **MUST** be the same length and line up. For example, `order_id[5]` must be the order ID for `loan_id[5]` Parameters ---------- portfolio_name : strin...
[ "Assign", "a", "note", "to", "a", "named", "portfolio", ".", "loan_id", "and", "order_id", "can", "be", "either", "integer", "values", "or", "lists", ".", "If", "choosing", "lists", "they", "both", "**", "MUST", "**", "be", "the", "same", "length", "and"...
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L258-L323
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.search
def search(self, filters=None, start_index=0, limit=100): """ Search for a list of notes that can be invested in. (similar to searching for notes in the Browse section on the site) Parameters ---------- filters : lendingclub.filters.*, optional The filter to ...
python
def search(self, filters=None, start_index=0, limit=100): """ Search for a list of notes that can be invested in. (similar to searching for notes in the Browse section on the site) Parameters ---------- filters : lendingclub.filters.*, optional The filter to ...
[ "def", "search", "(", "self", ",", "filters", "=", "None", ",", "start_index", "=", "0", ",", "limit", "=", "100", ")", ":", "assert", "filters", "is", "None", "or", "isinstance", "(", "filters", ",", "Filter", ")", ",", "'filter is not a lendingclub.filte...
Search for a list of notes that can be invested in. (similar to searching for notes in the Browse section on the site) Parameters ---------- filters : lendingclub.filters.*, optional The filter to use to search for notes. If no filter is passed, a wildcard search ...
[ "Search", "for", "a", "list", "of", "notes", "that", "can", "be", "invested", "in", ".", "(", "similar", "to", "searching", "for", "notes", "in", "the", "Browse", "section", "on", "the", "site", ")" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L325-L378
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.build_portfolio
def build_portfolio(self, cash, max_per_note=25, min_percent=0, max_percent=20, filters=None, automatically_invest=False, do_not_clear_staging=False): """ Returns a list of loan notes that are diversified by your min/max percent request and filters. One way to invest in these loan notes, is to s...
python
def build_portfolio(self, cash, max_per_note=25, min_percent=0, max_percent=20, filters=None, automatically_invest=False, do_not_clear_staging=False): """ Returns a list of loan notes that are diversified by your min/max percent request and filters. One way to invest in these loan notes, is to s...
[ "def", "build_portfolio", "(", "self", ",", "cash", ",", "max_per_note", "=", "25", ",", "min_percent", "=", "0", ",", "max_percent", "=", "20", ",", "filters", "=", "None", ",", "automatically_invest", "=", "False", ",", "do_not_clear_staging", "=", "False"...
Returns a list of loan notes that are diversified by your min/max percent request and filters. One way to invest in these loan notes, is to start an order and use add_batch to add all the loan fragments to them. (see examples) Parameters ---------- cash : int The tot...
[ "Returns", "a", "list", "of", "loan", "notes", "that", "are", "diversified", "by", "your", "min", "/", "max", "percent", "request", "and", "filters", ".", "One", "way", "to", "invest", "in", "these", "loan", "notes", "is", "to", "start", "an", "order", ...
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L380-L594
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.my_notes
def my_notes(self, start_index=0, limit=100, get_all=False, sort_by='loanId', sort_dir='asc'): """ Return all the loan notes you've already invested in. By default it'll return 100 results at a time. Parameters ---------- start_index : int, optional The result index ...
python
def my_notes(self, start_index=0, limit=100, get_all=False, sort_by='loanId', sort_dir='asc'): """ Return all the loan notes you've already invested in. By default it'll return 100 results at a time. Parameters ---------- start_index : int, optional The result index ...
[ "def", "my_notes", "(", "self", ",", "start_index", "=", "0", ",", "limit", "=", "100", ",", "get_all", "=", "False", ",", "sort_by", "=", "'loanId'", ",", "sort_dir", "=", "'asc'", ")", ":", "index", "=", "start_index", "notes", "=", "{", "'loans'", ...
Return all the loan notes you've already invested in. By default it'll return 100 results at a time. Parameters ---------- start_index : int, optional The result index to start on. By default only 100 records will be returned at a time, so use this to start at a later in...
[ "Return", "all", "the", "loan", "notes", "you", "ve", "already", "invested", "in", ".", "By", "default", "it", "ll", "return", "100", "results", "at", "a", "time", "." ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L596-L656
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.get_note
def get_note(self, note_id): """ Get a loan note that you've invested in by ID Parameters ---------- note_id : int The note ID Returns ------- dict A dictionary representing the matching note or False Examples ---...
python
def get_note(self, note_id): """ Get a loan note that you've invested in by ID Parameters ---------- note_id : int The note ID Returns ------- dict A dictionary representing the matching note or False Examples ---...
[ "def", "get_note", "(", "self", ",", "note_id", ")", ":", "index", "=", "0", "while", "True", ":", "notes", "=", "self", ".", "my_notes", "(", "start_index", "=", "index", ",", "sort_by", "=", "'noteId'", ")", "if", "notes", "[", "'result'", "]", "!=...
Get a loan note that you've invested in by ID Parameters ---------- note_id : int The note ID Returns ------- dict A dictionary representing the matching note or False Examples -------- >>> from lendingclub import Len...
[ "Get", "a", "loan", "note", "that", "you", "ve", "invested", "in", "by", "ID" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L658-L710
jgillick/LendingClub
lendingclub/__init__.py
LendingClub.search_my_notes
def search_my_notes(self, loan_id=None, order_id=None, grade=None, portfolio_name=None, status=None, term=None): """ Search for notes you are invested in. Use the parameters to define how to search. Passing no parameters is the same as calling `my_notes(get_all=True)` Parameters ...
python
def search_my_notes(self, loan_id=None, order_id=None, grade=None, portfolio_name=None, status=None, term=None): """ Search for notes you are invested in. Use the parameters to define how to search. Passing no parameters is the same as calling `my_notes(get_all=True)` Parameters ...
[ "def", "search_my_notes", "(", "self", ",", "loan_id", "=", "None", ",", "order_id", "=", "None", ",", "grade", "=", "None", ",", "portfolio_name", "=", "None", ",", "status", "=", "None", ",", "term", "=", "None", ")", ":", "assert", "grade", "is", ...
Search for notes you are invested in. Use the parameters to define how to search. Passing no parameters is the same as calling `my_notes(get_all=True)` Parameters ---------- loan_id : int, optional Search for notes for a specific loan. Since a loan is broken up into a pool o...
[ "Search", "for", "notes", "you", "are", "invested", "in", ".", "Use", "the", "parameters", "to", "define", "how", "to", "search", ".", "Passing", "no", "parameters", "is", "the", "same", "as", "calling", "my_notes", "(", "get_all", "=", "True", ")" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L712-L808
jgillick/LendingClub
lendingclub/__init__.py
Order.add
def add(self, loan_id, amount): """ Add a loan and amount you want to invest, to your order. If this loan is already in your order, it's amount will be replaced with the this new amount Parameters ---------- loan_id : int or dict The ID of the loan yo...
python
def add(self, loan_id, amount): """ Add a loan and amount you want to invest, to your order. If this loan is already in your order, it's amount will be replaced with the this new amount Parameters ---------- loan_id : int or dict The ID of the loan yo...
[ "def", "add", "(", "self", ",", "loan_id", ",", "amount", ")", ":", "assert", "amount", ">", "0", "and", "amount", "%", "25", "==", "0", ",", "'Amount must be a multiple of 25'", "assert", "type", "(", "amount", ")", "in", "(", "float", ",", "int", ")"...
Add a loan and amount you want to invest, to your order. If this loan is already in your order, it's amount will be replaced with the this new amount Parameters ---------- loan_id : int or dict The ID of the loan you want to add or a dictionary containing a `loan_id`...
[ "Add", "a", "loan", "and", "amount", "you", "want", "to", "invest", "to", "your", "order", ".", "If", "this", "loan", "is", "already", "in", "your", "order", "it", "s", "amount", "will", "be", "replaced", "with", "the", "this", "new", "amount" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L906-L928
jgillick/LendingClub
lendingclub/__init__.py
Order.add_batch
def add_batch(self, loans, batch_amount=None): """ Add a batch of loans to your order. Parameters ---------- loans : list A list of dictionary objects representing each loan and the amount you want to invest in it (see examples below). batch_amount : int, opt...
python
def add_batch(self, loans, batch_amount=None): """ Add a batch of loans to your order. Parameters ---------- loans : list A list of dictionary objects representing each loan and the amount you want to invest in it (see examples below). batch_amount : int, opt...
[ "def", "add_batch", "(", "self", ",", "loans", ",", "batch_amount", "=", "None", ")", ":", "assert", "batch_amount", "is", "None", "or", "batch_amount", "%", "25", "==", "0", ",", "'batch_amount must be a multiple of 25'", "# Add each loan", "assert", "type", "(...
Add a batch of loans to your order. Parameters ---------- loans : list A list of dictionary objects representing each loan and the amount you want to invest in it (see examples below). batch_amount : int, optional The dollar amount you want to set on ALL loans in...
[ "Add", "a", "batch", "of", "loans", "to", "your", "order", "." ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L943-L994
jgillick/LendingClub
lendingclub/__init__.py
Order.execute
def execute(self, portfolio_name=None): """ Place the order with LendingClub Parameters ---------- portfolio_name : string The name of the portfolio to add the invested loan notes to. This can be a new or existing portfolio name. Raises -...
python
def execute(self, portfolio_name=None): """ Place the order with LendingClub Parameters ---------- portfolio_name : string The name of the portfolio to add the invested loan notes to. This can be a new or existing portfolio name. Raises -...
[ "def", "execute", "(", "self", ",", "portfolio_name", "=", "None", ")", ":", "assert", "self", ".", "order_id", "==", "0", ",", "'This order has already been place. Start a new order.'", "assert", "len", "(", "self", ".", "loans", ")", ">", "0", ",", "'There a...
Place the order with LendingClub Parameters ---------- portfolio_name : string The name of the portfolio to add the invested loan notes to. This can be a new or existing portfolio name. Raises ------ LendingClubError Returns ----...
[ "Place", "the", "order", "with", "LendingClub" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1014-L1047
jgillick/LendingClub
lendingclub/__init__.py
Order.assign_to_portfolio
def assign_to_portfolio(self, portfolio_name=None): """ Assign all the notes in this order to a portfolio Parameters ---------- portfolio_name -- The name of the portfolio to assign it to (new or existing) Raises ------ LendingClubError Retu...
python
def assign_to_portfolio(self, portfolio_name=None): """ Assign all the notes in this order to a portfolio Parameters ---------- portfolio_name -- The name of the portfolio to assign it to (new or existing) Raises ------ LendingClubError Retu...
[ "def", "assign_to_portfolio", "(", "self", ",", "portfolio_name", "=", "None", ")", ":", "assert", "self", ".", "order_id", ">", "0", ",", "'You need to execute this order before you can assign to a portfolio.'", "# Get loan IDs as a list", "loan_ids", "=", "self", ".", ...
Assign all the notes in this order to a portfolio Parameters ---------- portfolio_name -- The name of the portfolio to assign it to (new or existing) Raises ------ LendingClubError Returns ------- boolean True on success
[ "Assign", "all", "the", "notes", "in", "this", "order", "to", "a", "portfolio" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1049-L1074
jgillick/LendingClub
lendingclub/__init__.py
Order.__stage_order
def __stage_order(self): """ Add all the loans to the LC order session """ # Skip staging...probably not a good idea...you've been warned if self.__already_staged is True and self.__i_know_what_im_doing is True: self.__log('Not staging the order...I hope you know wha...
python
def __stage_order(self): """ Add all the loans to the LC order session """ # Skip staging...probably not a good idea...you've been warned if self.__already_staged is True and self.__i_know_what_im_doing is True: self.__log('Not staging the order...I hope you know wha...
[ "def", "__stage_order", "(", "self", ")", ":", "# Skip staging...probably not a good idea...you've been warned", "if", "self", ".", "__already_staged", "is", "True", "and", "self", ".", "__i_know_what_im_doing", "is", "True", ":", "self", ".", "__log", "(", "'Not stag...
Add all the loans to the LC order session
[ "Add", "all", "the", "loans", "to", "the", "LC", "order", "session" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1076-L1132
jgillick/LendingClub
lendingclub/__init__.py
Order.__get_strut_token
def __get_strut_token(self): """ Move the staged loan notes to the order stage and get the struts token from the place order HTML. The order will not be placed until calling _confirm_order() Returns ------- dict A dict with the token name and value ...
python
def __get_strut_token(self): """ Move the staged loan notes to the order stage and get the struts token from the place order HTML. The order will not be placed until calling _confirm_order() Returns ------- dict A dict with the token name and value ...
[ "def", "__get_strut_token", "(", "self", ")", ":", "try", ":", "# Move to the place order page and get the struts token", "response", "=", "self", ".", "lc", ".", "session", ".", "get", "(", "'/portfolio/placeOrder.action'", ")", "soup", "=", "BeautifulSoup", "(", "...
Move the staged loan notes to the order stage and get the struts token from the place order HTML. The order will not be placed until calling _confirm_order() Returns ------- dict A dict with the token name and value
[ "Move", "the", "staged", "loan", "notes", "to", "the", "order", "stage", "and", "get", "the", "struts", "token", "from", "the", "place", "order", "HTML", ".", "The", "order", "will", "not", "be", "placed", "until", "calling", "_confirm_order", "()" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1134-L1183
jgillick/LendingClub
lendingclub/__init__.py
Order.__place_order
def __place_order(self, token): """ Use the struts token to place the order. Parameters ---------- token : string The struts token received from the place order page Returns ------- int The completed order ID. """ ...
python
def __place_order(self, token): """ Use the struts token to place the order. Parameters ---------- token : string The struts token received from the place order page Returns ------- int The completed order ID. """ ...
[ "def", "__place_order", "(", "self", ",", "token", ")", ":", "order_id", "=", "0", "response", "=", "None", "if", "not", "token", "or", "token", "[", "'value'", "]", "==", "''", ":", "raise", "LendingClubError", "(", "'The token parameter is False, None or unk...
Use the struts token to place the order. Parameters ---------- token : string The struts token received from the place order page Returns ------- int The completed order ID.
[ "Use", "the", "struts", "token", "to", "place", "the", "order", "." ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1185-L1231
jgillick/LendingClub
lendingclub/session.py
Session.__continue_session
def __continue_session(self): """ Check if the time since the last HTTP request is under the session timeout limit. If it's been too long since the last request attempt to authenticate again. """ now = time.time() diff = abs(now - self.last_request_time) t...
python
def __continue_session(self): """ Check if the time since the last HTTP request is under the session timeout limit. If it's been too long since the last request attempt to authenticate again. """ now = time.time() diff = abs(now - self.last_request_time) t...
[ "def", "__continue_session", "(", "self", ")", ":", "now", "=", "time", ".", "time", "(", ")", "diff", "=", "abs", "(", "now", "-", "self", ".", "last_request_time", ")", "timeout_sec", "=", "self", ".", "session_timeout", "*", "60", "# convert minutes to ...
Check if the time since the last HTTP request is under the session timeout limit. If it's been too long since the last request attempt to authenticate again.
[ "Check", "if", "the", "time", "since", "the", "last", "HTTP", "request", "is", "under", "the", "session", "timeout", "limit", ".", "If", "it", "s", "been", "too", "long", "since", "the", "last", "request", "attempt", "to", "authenticate", "again", "." ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L73-L85
jgillick/LendingClub
lendingclub/session.py
Session.build_url
def build_url(self, path): """ Build a LendingClub URL from a URL path (without the domain). Parameters ---------- path : string The path part of the URL after the domain. i.e. https://www.lendingclub.com/<path> """ url = '{0}{1}'.format(self.base_url...
python
def build_url(self, path): """ Build a LendingClub URL from a URL path (without the domain). Parameters ---------- path : string The path part of the URL after the domain. i.e. https://www.lendingclub.com/<path> """ url = '{0}{1}'.format(self.base_url...
[ "def", "build_url", "(", "self", ",", "path", ")", ":", "url", "=", "'{0}{1}'", ".", "format", "(", "self", ".", "base_url", ",", "path", ")", "url", "=", "re", ".", "sub", "(", "'([^:])//'", ",", "'\\\\1/'", ",", "url", ")", "# Remove double slashes",...
Build a LendingClub URL from a URL path (without the domain). Parameters ---------- path : string The path part of the URL after the domain. i.e. https://www.lendingclub.com/<path>
[ "Build", "a", "LendingClub", "URL", "from", "a", "URL", "path", "(", "without", "the", "domain", ")", "." ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L99-L110
jgillick/LendingClub
lendingclub/session.py
Session.authenticate
def authenticate(self, email=None, password=None): """ Authenticate with LendingClub and preserve the user session for future requests. This will raise an exception if the login appears to have failed, otherwise it returns True. Since Lending Club doesn't seem to have a login API, the c...
python
def authenticate(self, email=None, password=None): """ Authenticate with LendingClub and preserve the user session for future requests. This will raise an exception if the login appears to have failed, otherwise it returns True. Since Lending Club doesn't seem to have a login API, the c...
[ "def", "authenticate", "(", "self", ",", "email", "=", "None", ",", "password", "=", "None", ")", ":", "# Get email and password", "if", "email", "is", "None", ":", "email", "=", "self", ".", "email", "else", ":", "self", ".", "email", "=", "email", "i...
Authenticate with LendingClub and preserve the user session for future requests. This will raise an exception if the login appears to have failed, otherwise it returns True. Since Lending Club doesn't seem to have a login API, the code has to try to decide if the login worked or not by looking ...
[ "Authenticate", "with", "LendingClub", "and", "preserve", "the", "user", "session", "for", "future", "requests", ".", "This", "will", "raise", "an", "exception", "if", "the", "login", "appears", "to", "have", "failed", "otherwise", "it", "returns", "True", "."...
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L112-L216
jgillick/LendingClub
lendingclub/session.py
Session.is_site_available
def is_site_available(self): """ Returns true if we can access LendingClub.com This is also a simple test to see if there's a network connection Returns ------- boolean True or False """ try: response = requests.head(self.base_url)...
python
def is_site_available(self): """ Returns true if we can access LendingClub.com This is also a simple test to see if there's a network connection Returns ------- boolean True or False """ try: response = requests.head(self.base_url)...
[ "def", "is_site_available", "(", "self", ")", ":", "try", ":", "response", "=", "requests", ".", "head", "(", "self", ".", "base_url", ")", "status", "=", "response", ".", "status_code", "return", "200", "<=", "status", "<", "400", "# Returns true if the sta...
Returns true if we can access LendingClub.com This is also a simple test to see if there's a network connection Returns ------- boolean True or False
[ "Returns", "true", "if", "we", "can", "access", "LendingClub", ".", "com", "This", "is", "also", "a", "simple", "test", "to", "see", "if", "there", "s", "a", "network", "connection" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L218-L233
jgillick/LendingClub
lendingclub/session.py
Session.request
def request(self, method, path, query=None, data=None, redirects=True): """ Sends HTTP request to LendingClub. Parameters ---------- method : {GET, POST, HEAD, DELETE} The HTTP method to use: GET, POST, HEAD or DELETE path : string The path that w...
python
def request(self, method, path, query=None, data=None, redirects=True): """ Sends HTTP request to LendingClub. Parameters ---------- method : {GET, POST, HEAD, DELETE} The HTTP method to use: GET, POST, HEAD or DELETE path : string The path that w...
[ "def", "request", "(", "self", ",", "method", ",", "path", ",", "query", "=", "None", ",", "data", "=", "None", ",", "redirects", "=", "True", ")", ":", "# Check session time", "self", ".", "__continue_session", "(", ")", "try", ":", "url", "=", "self"...
Sends HTTP request to LendingClub. Parameters ---------- method : {GET, POST, HEAD, DELETE} The HTTP method to use: GET, POST, HEAD or DELETE path : string The path that will be appended to the domain defined in :attr:`base_url`. query : dict ...
[ "Sends", "HTTP", "request", "to", "LendingClub", "." ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L235-L290
jgillick/LendingClub
lendingclub/session.py
Session.post
def post(self, path, query=None, data=None, redirects=True): """ POST request wrapper for :func:`request()` """ return self.request('POST', path, query, data, redirects)
python
def post(self, path, query=None, data=None, redirects=True): """ POST request wrapper for :func:`request()` """ return self.request('POST', path, query, data, redirects)
[ "def", "post", "(", "self", ",", "path", ",", "query", "=", "None", ",", "data", "=", "None", ",", "redirects", "=", "True", ")", ":", "return", "self", ".", "request", "(", "'POST'", ",", "path", ",", "query", ",", "data", ",", "redirects", ")" ]
POST request wrapper for :func:`request()`
[ "POST", "request", "wrapper", "for", ":", "func", ":", "request", "()" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L292-L296
jgillick/LendingClub
lendingclub/session.py
Session.get
def get(self, path, query=None, redirects=True): """ GET request wrapper for :func:`request()` """ return self.request('GET', path, query, None, redirects)
python
def get(self, path, query=None, redirects=True): """ GET request wrapper for :func:`request()` """ return self.request('GET', path, query, None, redirects)
[ "def", "get", "(", "self", ",", "path", ",", "query", "=", "None", ",", "redirects", "=", "True", ")", ":", "return", "self", ".", "request", "(", "'GET'", ",", "path", ",", "query", ",", "None", ",", "redirects", ")" ]
GET request wrapper for :func:`request()`
[ "GET", "request", "wrapper", "for", ":", "func", ":", "request", "()" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L298-L302
jgillick/LendingClub
lendingclub/session.py
Session.head
def head(self, path, query=None, data=None, redirects=True): """ HEAD request wrapper for :func:`request()` """ return self.request('HEAD', path, query, None, redirects)
python
def head(self, path, query=None, data=None, redirects=True): """ HEAD request wrapper for :func:`request()` """ return self.request('HEAD', path, query, None, redirects)
[ "def", "head", "(", "self", ",", "path", ",", "query", "=", "None", ",", "data", "=", "None", ",", "redirects", "=", "True", ")", ":", "return", "self", ".", "request", "(", "'HEAD'", ",", "path", ",", "query", ",", "None", ",", "redirects", ")" ]
HEAD request wrapper for :func:`request()`
[ "HEAD", "request", "wrapper", "for", ":", "func", ":", "request", "()" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L304-L308
jgillick/LendingClub
lendingclub/session.py
Session.json_success
def json_success(self, json): """ Check the JSON response object for the success flag Parameters ---------- json : dict A dictionary representing a JSON object from lendingclub.com """ if type(json) is dict and 'result' in json and json['result'] == '...
python
def json_success(self, json): """ Check the JSON response object for the success flag Parameters ---------- json : dict A dictionary representing a JSON object from lendingclub.com """ if type(json) is dict and 'result' in json and json['result'] == '...
[ "def", "json_success", "(", "self", ",", "json", ")", ":", "if", "type", "(", "json", ")", "is", "dict", "and", "'result'", "in", "json", "and", "json", "[", "'result'", "]", "==", "'success'", ":", "return", "True", "return", "False" ]
Check the JSON response object for the success flag Parameters ---------- json : dict A dictionary representing a JSON object from lendingclub.com
[ "Check", "the", "JSON", "response", "object", "for", "the", "success", "flag" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L316-L327
jgillick/LendingClub
lendingclub/filters.py
Filter.__merge_values
def __merge_values(self, from_dict, to_dict): """ Merge dictionary objects recursively, by only updating keys existing in to_dict """ for key, value in from_dict.iteritems(): # Only if the key already exists if key in to_dict: # Make sure the val...
python
def __merge_values(self, from_dict, to_dict): """ Merge dictionary objects recursively, by only updating keys existing in to_dict """ for key, value in from_dict.iteritems(): # Only if the key already exists if key in to_dict: # Make sure the val...
[ "def", "__merge_values", "(", "self", ",", "from_dict", ",", "to_dict", ")", ":", "for", "key", ",", "value", "in", "from_dict", ".", "iteritems", "(", ")", ":", "# Only if the key already exists", "if", "key", "in", "to_dict", ":", "# Make sure the values are t...
Merge dictionary objects recursively, by only updating keys existing in to_dict
[ "Merge", "dictionary", "objects", "recursively", "by", "only", "updating", "keys", "existing", "in", "to_dict" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L159-L179
jgillick/LendingClub
lendingclub/filters.py
Filter.__normalize_grades
def __normalize_grades(self): """ Adjust the grades list. If a grade has been set, set All to false """ if 'grades' in self and self['grades']['All'] is True: for grade in self['grades']: if grade != 'All' and self['grades'][grade] is True: ...
python
def __normalize_grades(self): """ Adjust the grades list. If a grade has been set, set All to false """ if 'grades' in self and self['grades']['All'] is True: for grade in self['grades']: if grade != 'All' and self['grades'][grade] is True: ...
[ "def", "__normalize_grades", "(", "self", ")", ":", "if", "'grades'", "in", "self", "and", "self", "[", "'grades'", "]", "[", "'All'", "]", "is", "True", ":", "for", "grade", "in", "self", "[", "'grades'", "]", ":", "if", "grade", "!=", "'All'", "and...
Adjust the grades list. If a grade has been set, set All to false
[ "Adjust", "the", "grades", "list", ".", "If", "a", "grade", "has", "been", "set", "set", "All", "to", "false" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L197-L207
jgillick/LendingClub
lendingclub/filters.py
Filter.__normalize_progress
def __normalize_progress(self): """ Adjust the funding progress filter to be a factor of 10 """ progress = self['funding_progress'] if progress % 10 != 0: progress = round(float(progress) / 10) progress = int(progress) * 10 self['funding_prog...
python
def __normalize_progress(self): """ Adjust the funding progress filter to be a factor of 10 """ progress = self['funding_progress'] if progress % 10 != 0: progress = round(float(progress) / 10) progress = int(progress) * 10 self['funding_prog...
[ "def", "__normalize_progress", "(", "self", ")", ":", "progress", "=", "self", "[", "'funding_progress'", "]", "if", "progress", "%", "10", "!=", "0", ":", "progress", "=", "round", "(", "float", "(", "progress", ")", "/", "10", ")", "progress", "=", "...
Adjust the funding progress filter to be a factor of 10
[ "Adjust", "the", "funding", "progress", "filter", "to", "be", "a", "factor", "of", "10" ]
train
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L209-L219