sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
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() ...
Read and process an initial handshake message from Storm.
entailment
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...
Send a message to Storm via stdout.
entailment
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...
Report an exception back to Storm via logging. :param exception: a Python exception. :param tup: a :class:`Tuple` object.
entailment
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...
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 ...
entailment
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...
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....
entailment
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*...
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.
entailment
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 =...
Properly kill Python process including zombie threads.
entailment
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...
Returns a TextIOWrapper around the given stream that handles UTF-8 encoding/decoding.
entailment
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...
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:: ...
entailment
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
Serialize to JSON a message dictionary.
entailment
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...
Read a tuple from the pipe to Storm.
entailment
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...
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 ``...
entailment
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...
Indicate that processing of a Tuple has succeeded. :param tup: the Tuple to acknowledge. :type tup: :class:`str` or :class:`pystorm.component.Tuple`
entailment
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":...
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`
entailment
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):...
The inside of ``run``'s infinite loop. Separated out so it can be properly unit tested.
entailment
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...
Process an exception encountered while running the ``run()`` loop. Called right before program exits.
entailment
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)
Modified emit that will not return task IDs after emitting. See :class:`pystorm.component.Bolt` for more information. :returns: ``None``.
entailment
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....
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...
entailment
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...
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.
entailment
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...
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``.
entailment
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...
Process an exception encountered while running the ``run()`` loop. Called right before program exits.
entailment
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()
The inside of ``_batch_entry``'s infinite loop. Separated out so it can be properly unit tested.
entailment
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)
Entry point for the batcher thread.
entailment
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...
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...
entailment
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()...
Serialize a message dictionary and write it to the output stream.
entailment
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) ...
Convert the FFI result to Python data structures
entailment
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...
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.
entailment
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...
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 '/'.
entailment
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...
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...
entailment
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, ...
Enclose a reading within a container, e.g. '[]'.
entailment
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. ...
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...
entailment
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...
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*...
entailment
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...
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...
entailment
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...
Load the transcription mapping data into a dictionary.
entailment
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]
Convert a numbered Pinyin vowel to an accented Pinyin vowel.
entailment
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)
Convert an accented Pinyin vowel to a numbered Pinyin vowel.
entailment
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], '...
Return the syllable and tone of a numbered Pinyin syllable.
entailment
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...
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...
entailment
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 ...
Return the syllable and tone of a Zhuyin syllable.
entailment
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...
Return the syllable and tone of an IPA syllable.
entailment
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)
Restore a lowercase string's characters to their original case.
entailment
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...
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.
entailment
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_...
Convert accented Pinyin syllable *s* to a numbered Pinyin syllable.
entailment
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...
Convert Pinyin syllable *s* to a Zhuyin syllable.
entailment
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...
Convert Pinyin syllable *s* to an IPA syllable.
entailment
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...
Convert Zhuyin syllable *s* to a numbered Pinyin syllable.
entailment
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...
Convert IPA syllable *s* to a numbered Pinyin syllable.
entailment
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...
Convert a string's syllables to a different transcription system.
entailment
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)
Convert all numbered Pinyin syllables in *s* to accented Pinyin.
entailment
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...
Convert all Pinyin syllables in *s* to Zhuyin. Spaces are added between connected syllables and syllable-separating apostrophes are removed.
entailment
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...
Convert all Pinyin syllables in *s* to IPA. Spaces are added between connected syllables and syllable-separating apostrophes are removed.
entailment
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: ...
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.
entailment
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...
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.
entailment
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...
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.
entailment
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...
Convert *s* to Zhuyin.
entailment
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.")
Convert *s* to IPA.
entailment
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
Check if a re pattern expression matches an entire string.
entailment
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)
Check if *s* consists of valid Pinyin.
entailment
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*...
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...
entailment
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)
Check if *s* consists of valid Chinese IPA.
entailment
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* ...
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...
entailment
def prepare(self, f): """Accept an objective function for optimization.""" self.g = autograd.grad(f) self.h = autograd.hessian(f)
Accept an objective function for optimization.
entailment
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: ...
Calculate an optimum argument of an objective function.
entailment
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: ...
Calculate an optimum argument of an objective function.
entailment
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
Calculate an optimum argument of an objective function.
entailment
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...
Calculate an optimum argument of an objective function.
entailment
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]
Calculate a position of the end-effector and return it.
entailment
def solve(self, angles0, target): """Calculate joint angles and returns it.""" return self.optimizer.optimize(np.array(angles0), target)
Calculate joint angles and returns it.
entailment
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.] ])
Return translation matrix in homogeneous coordinates.
entailment
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)
Return rotation matrix in homogeneous coordinates.
entailment
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...
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.
entailment
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') ...
Return the version number of the Lending Club Investor tool Returns ------- string The version number string
entailment
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 -...
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...
entailment
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') ...
Returns the account cash balance available for investing Returns ------- float The cash balance in your account.
entailment
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 ...
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...
entailment
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 ...
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...
entailment
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 ...
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 ...
entailment
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...
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...
entailment
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 ...
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...
entailment
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 ---...
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...
entailment
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 ...
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...
entailment
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...
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`...
entailment
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...
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...
entailment
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 -...
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 ----...
entailment
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...
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
entailment
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...
Add all the loans to the LC order session
entailment
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 ...
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
entailment
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. """ ...
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.
entailment
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...
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.
entailment
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...
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>
entailment
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...
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 ...
entailment
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)...
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
entailment
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...
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 ...
entailment
def post(self, path, query=None, data=None, redirects=True): """ POST request wrapper for :func:`request()` """ return self.request('POST', path, query, data, redirects)
POST request wrapper for :func:`request()`
entailment
def get(self, path, query=None, redirects=True): """ GET request wrapper for :func:`request()` """ return self.request('GET', path, query, None, redirects)
GET request wrapper for :func:`request()`
entailment
def head(self, path, query=None, data=None, redirects=True): """ HEAD request wrapper for :func:`request()` """ return self.request('HEAD', path, query, None, redirects)
HEAD request wrapper for :func:`request()`
entailment
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'] == '...
Check the JSON response object for the success flag Parameters ---------- json : dict A dictionary representing a JSON object from lendingclub.com
entailment
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...
Merge dictionary objects recursively, by only updating keys existing in to_dict
entailment
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: ...
Adjust the grades list. If a grade has been set, set All to false
entailment
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...
Adjust the funding progress filter to be a factor of 10
entailment