repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
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", "." ]
0f853e007c79e03cefdb4a0794423f84dce4c2f3
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L505-L512
train
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 topology is shutting down) the lock being acquired will freeze the rest of the bolt, which is precisely what this batcher seeks to avoid. """ tup = self.read_tuple() with self._batch_lock: self._current_tups = [tup] if self.is_heartbeat(tup): self.send_message({"command": "sync"}) elif self.is_tick(tup): self.process_tick(tup) else: self.process(tup) # reset so that we don't accidentally fail the wrong Tuples # if a successive call to read_tuple fails self._current_tups = []
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 topology is shutting down) the lock being acquired will freeze the rest of the bolt, which is precisely what this batcher seeks to avoid. """ tup = self.read_tuple() with self._batch_lock: self._current_tups = [tup] if self.is_heartbeat(tup): self.send_message({"command": "sync"}) elif self.is_tick(tup): self.process_tick(tup) else: self.process(tup) # reset so that we don't accidentally fail the wrong Tuples # if a successive call to read_tuple fails self._current_tups = []
[ "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 lock being acquired will freeze the rest of the bolt, which is precisely what this batcher seeks to avoid.
[ "The", "inside", "of", "run", "s", "infinite", "loop", "." ]
0f853e007c79e03cefdb4a0794423f84dce4c2f3
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/bolt.py#L523-L546
train
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() except IOError: raise StormWentAwayError() except: log.exception("Failed to send message: %r", msg_dict)
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() except IOError: raise StormWentAwayError() except: log.exception("Failed to send message: %r", msg_dict)
[ "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", "." ]
0f853e007c79e03cefdb4a0794423f84dce4c2f3
https://github.com/pystorm/pystorm/blob/0f853e007c79e03cefdb4a0794423f84dce4c2f3/pystorm/serializers/serializer.py#L27-L37
train
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) ls_e = np.frombuffer(array_str_e, float, array_size).tolist() ls_n = np.frombuffer(array_str_n, float, array_size).tolist() return ls_e, ls_n
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) ls_e = np.frombuffer(array_str_e, float, array_size).tolist() ls_n = np.frombuffer(array_str_n, float, array_size).tolist() return ls_e, ls_n
[ "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" ]
b0f5ca8b4942a835a834aed4c1fdb4d827c72342
https://github.com/urschrei/convertbng/blob/b0f5ca8b4942a835a834aed4c1fdb4d827c72342/convertbng/util.py#L122-L134
train
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, filename)) return data.decode(encoding).splitlines()
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, filename)) return data.decode(encoding).splitlines()
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/data/__init__.py#L13-L22
train
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 name, file_name in (('words', 'hanzi_pinyin_words.tsv'), ('characters', 'hanzi_pinyin_characters.tsv')): # Split the lines by tabs: [[hanzi, pinyin]...]. lines = [line.split('\t') for line in dragonmapper.data.load_data_file(file_name)] # Make a dictionary: {hanzi: [pinyin, pinyin]...}. data[name] = {hanzi: pinyin.split('/') for hanzi, pinyin in lines} return data
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 name, file_name in (('words', 'hanzi_pinyin_words.tsv'), ('characters', 'hanzi_pinyin_characters.tsv')): # Split the lines by tabs: [[hanzi, pinyin]...]. lines = [line.split('\t') for line in dragonmapper.data.load_data_file(file_name)] # Make a dictionary: {hanzi: [pinyin, pinyin]...}. data[name] = {hanzi: pinyin.split('/') for hanzi, pinyin in lines} return data
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L36-L54
train
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 like this: [[CHAR_READING1, CHAR_READING2 ...], ...] When returning character readings, if a character wasn't recognized, the original character is returned, e.g. [[CHAR_READING1, ...], CHAR, ...] """ try: return _HANZI_PINYIN_MAP['words'][hanzi] except KeyError: return [_CHARACTERS.get(character, character) for character in hanzi]
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 like this: [[CHAR_READING1, CHAR_READING2 ...], ...] When returning character readings, if a character wasn't recognized, the original character is returned, e.g. [[CHAR_READING1, ...], CHAR, ...] """ try: return _HANZI_PINYIN_MAP['words'][hanzi] except KeyError: return [_CHARACTERS.get(character, character) for character in hanzi]
[ "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_READING2 ...], ...] When returning character readings, if a character wasn't recognized, the original character is returned, e.g. [[CHAR_READING1, ...], CHAR, ...]
[ "Return", "the", "Pinyin", "reading", "for", "a", "Chinese", "word", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L61-L77
train
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, 'readings': readings} return enclosed_readings
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, 'readings': readings} return enclosed_readings
[ "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", ".", "[]", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L80-L86
train
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. *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 boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched. """ hanzi = s pinyin = '' # Process the given string. while hanzi: # Get the next match in the given string. match = re.search('[^%s%s]+' % (delimiter, zhon.hanzi.punctuation), hanzi) # There are no more matches, but the string isn't finished yet. if match is None and hanzi: pinyin += hanzi break match_start, match_end = match.span() # Process the punctuation marks that occur before the match. if match_start > 0: pinyin += hanzi[0:match_start] # Get the Chinese word/character readings. readings = _hanzi_to_pinyin(match.group()) # Process the returned word readings. if match.group() in _WORDS: if all_readings: reading = _enclose_readings(container, _READING_SEPARATOR.join(readings)) else: reading = readings[0] pinyin += reading # Process the returned character readings. else: # Process each character individually. for character in readings: # Don't touch unrecognized characters. if isinstance(character, str): pinyin += character # Format multiple readings. elif isinstance(character, list) and all_readings: pinyin += _enclose_readings( container, _READING_SEPARATOR.join(character)) # Select and format the most common reading. elif isinstance(character, list) and not all_readings: # Add an apostrophe to separate syllables. if (pinyin and character[0][0] in zhon.pinyin.vowels and pinyin[-1] in zhon.pinyin.lowercase): pinyin += "'" pinyin += character[0] # Move ahead in the given string. hanzi = hanzi[match_end:] if accented: return pinyin else: return accented_to_numbered(pinyin)
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. *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 boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched. """ hanzi = s pinyin = '' # Process the given string. while hanzi: # Get the next match in the given string. match = re.search('[^%s%s]+' % (delimiter, zhon.hanzi.punctuation), hanzi) # There are no more matches, but the string isn't finished yet. if match is None and hanzi: pinyin += hanzi break match_start, match_end = match.span() # Process the punctuation marks that occur before the match. if match_start > 0: pinyin += hanzi[0:match_start] # Get the Chinese word/character readings. readings = _hanzi_to_pinyin(match.group()) # Process the returned word readings. if match.group() in _WORDS: if all_readings: reading = _enclose_readings(container, _READING_SEPARATOR.join(readings)) else: reading = readings[0] pinyin += reading # Process the returned character readings. else: # Process each character individually. for character in readings: # Don't touch unrecognized characters. if isinstance(character, str): pinyin += character # Format multiple readings. elif isinstance(character, list) and all_readings: pinyin += _enclose_readings( container, _READING_SEPARATOR.join(character)) # Select and format the most common reading. elif isinstance(character, list) and not all_readings: # Add an apostrophe to separate syllables. if (pinyin and character[0][0] in zhon.pinyin.vowels and pinyin[-1] in zhon.pinyin.lowercase): pinyin += "'" pinyin += character[0] # Move ahead in the given string. hanzi = hanzi[match_end:] if accented: return pinyin else: return accented_to_numbered(pinyin)
[ "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 differentiate between words and characters so that a more accurate reading can be returned. *all_readings* is a boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched.
[ "Convert", "a", "string", "s", "Chinese", "characters", "to", "Pinyin", "readings", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L89-L168
train
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 characters so that a more accurate reading can be returned. *all_readings* is a boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched. """ numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False) zhuyin = pinyin_to_zhuyin(numbered_pinyin) return zhuyin
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 characters so that a more accurate reading can be returned. *all_readings* is a boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched. """ numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False) zhuyin = pinyin_to_zhuyin(numbered_pinyin) return zhuyin
[ "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* is a boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched.
[ "Convert", "a", "string", "s", "Chinese", "characters", "to", "Zhuyin", "readings", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L171-L191
train
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 more accurate reading can be returned. *all_readings* is a boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched. """ numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False) ipa = pinyin_to_ipa(numbered_pinyin) return ipa
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 more accurate reading can be returned. *all_readings* is a boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched. """ numbered_pinyin = to_pinyin(s, delimiter, all_readings, container, False) ipa = pinyin_to_ipa(numbered_pinyin) return ipa
[ "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 boolean value indicating whether or not to return all possible readings in the case of words/characters that have multiple readings. *container* is a two character string that is used to enclose words/characters if *all_readings* is ``True``. The default ``'[]'`` is used like this: ``'[READING1/READING2]'``. Characters not recognized as Chinese are left untouched.
[ "Convert", "a", "string", "s", "Chinese", "characters", "to", "IPA", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/hanzi.py#L194-L214
train
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_map[z] = {'Pinyin': p, 'IPA': i} ipa_map[i] = {'Pinyin': p, 'Zhuyin': z} return pinyin_map, zhuyin_map, ipa_map
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_map[z] = {'Pinyin': p, 'IPA': i} ipa_map[i] = {'Pinyin': p, 'Zhuyin': z} return pinyin_map, zhuyin_map, ipa_map
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L46-L55
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L69-L73
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L76-L80
train
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], '5' elif tone_number in '12345': syllable, tone = unparsed_syllable[:-1], tone_number else: raise ValueError("Invalid syllable: %s" % unparsed_syllable) return syllable, tone
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], '5' elif tone_number in '12345': syllable, tone = unparsed_syllable[:-1], tone_number else: raise ValueError("Invalid syllable: %s" % unparsed_syllable) return syllable, tone
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L83-L94
train
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 tone to the end of the syllable. 2. Otherwise, assume the syllable is tone 5 (no accent marks). """ if unparsed_syllable[0] == '\u00B7': # Special case for middle dot tone mark. return unparsed_syllable[1:], '5' for character in unparsed_syllable: if character in _ACCENTED_VOWELS: vowel, tone = _accented_vowel_to_numbered(character) return unparsed_syllable.replace(character, vowel), tone return unparsed_syllable, '5'
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 tone to the end of the syllable. 2. Otherwise, assume the syllable is tone 5 (no accent marks). """ if unparsed_syllable[0] == '\u00B7': # Special case for middle dot tone mark. return unparsed_syllable[1:], '5' for character in unparsed_syllable: if character in _ACCENTED_VOWELS: vowel, tone = _accented_vowel_to_numbered(character) return unparsed_syllable.replace(character, vowel), tone return unparsed_syllable, '5'
[ "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, assume the syllable is tone 5 (no accent marks).
[ "Return", "the", "syllable", "and", "tone", "of", "an", "accented", "Pinyin", "syllable", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L97-L116
train
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 in _ZHUYIN_TONES.items(): if zhuyin_tone == tone_mark: syllable, tone = unparsed_syllable[:-1], tone_number else: raise ValueError("Invalid syllable: %s" % unparsed_syllable) return syllable, tone
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 in _ZHUYIN_TONES.items(): if zhuyin_tone == tone_mark: syllable, tone = unparsed_syllable[:-1], tone_number else: raise ValueError("Invalid syllable: %s" % unparsed_syllable) return syllable, tone
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L132-L144
train
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_mark in _IPA_TONES.items(): if ipa_tone.group() == tone_mark: tone = tone_number break syllable = unparsed_syllable[0:ipa_tone.start()] return syllable, 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_mark in _IPA_TONES.items(): if ipa_tone.group() == tone_mark: tone = tone_number break syllable = unparsed_syllable[0:ipa_tone.start()] return syllable, 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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L147-L159
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L167-L174
train
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. Otherwise, put the tone mark on the last vowel. """ if s == 'r5': return 'r' # Special case for 'r' suffix. lowercase_syllable, case_memory = _lower_case(s) syllable, tone = _parse_numbered_syllable(lowercase_syllable) syllable = syllable.replace('v', '\u00fc') if re.search('[%s]' % _UNACCENTED_VOWELS, syllable) is None: return s if 'a' in syllable: accented_a = _numbered_vowel_to_accented('a', tone) accented_syllable = syllable.replace('a', accented_a) elif 'e' in syllable: accented_e = _numbered_vowel_to_accented('e', tone) accented_syllable = syllable.replace('e', accented_e) elif 'o' in syllable: accented_o = _numbered_vowel_to_accented('o', tone) accented_syllable = syllable.replace('o', accented_o) else: vowel = syllable[max(map(syllable.rfind, _UNACCENTED_VOWELS))] accented_vowel = _numbered_vowel_to_accented(vowel, tone) accented_syllable = syllable.replace(vowel, accented_vowel) return _restore_case(accented_syllable, case_memory)
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. Otherwise, put the tone mark on the last vowel. """ if s == 'r5': return 'r' # Special case for 'r' suffix. lowercase_syllable, case_memory = _lower_case(s) syllable, tone = _parse_numbered_syllable(lowercase_syllable) syllable = syllable.replace('v', '\u00fc') if re.search('[%s]' % _UNACCENTED_VOWELS, syllable) is None: return s if 'a' in syllable: accented_a = _numbered_vowel_to_accented('a', tone) accented_syllable = syllable.replace('a', accented_a) elif 'e' in syllable: accented_e = _numbered_vowel_to_accented('e', tone) accented_syllable = syllable.replace('e', accented_e) elif 'o' in syllable: accented_o = _numbered_vowel_to_accented('o', tone) accented_syllable = syllable.replace('o', accented_o) else: vowel = syllable[max(map(syllable.rfind, _UNACCENTED_VOWELS))] accented_vowel = _numbered_vowel_to_accented(vowel, tone) accented_syllable = syllable.replace(vowel, accented_vowel) return _restore_case(accented_syllable, case_memory)
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L177-L209
train
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_case(s) numbered_syllable, tone = _parse_accented_syllable(lowercase_syllable) return _restore_case(numbered_syllable, case_memory) + tone
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_case(s) numbered_syllable, tone = _parse_accented_syllable(lowercase_syllable) return _restore_case(numbered_syllable, case_memory) + tone
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L212-L220
train
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 zhuyin_syllable + _ZHUYIN_TONES[tone]
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 zhuyin_syllable + _ZHUYIN_TONES[tone]
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L223-L230
train
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 + _IPA_TONES[tone]
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 + _IPA_TONES[tone]
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L233-L240
train
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) return pinyin_syllable + tone
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) return pinyin_syllable + tone
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L243-L250
train
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 + tone
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 + tone
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L278-L285
train
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.IGNORECASE | re.UNICODE) if match is None and original: # There are no more matches, but the given string isn't fully # processed yet. new += original break match_start, match_end = match.span() if match_start > 0: # Handle extra characters before matched syllable. if (new and remove_apostrophes and match_start == 1 and original[0] == "'"): pass # Remove the apostrophe between Pinyin syllables. if separate_syllables: # Separate syllables by a space. new += ' ' else: new += original[0:match_start] else: # Matched syllable starts immediately. if new and separate_syllables: # Separate syllables by a space. new += ' ' elif (new and add_apostrophes and match.group()[0].lower() in _UNACCENTED_VOWELS): new += "'" # Convert the matched syllable. new += syllable_function(match.group()) original = original[match_end:] return new
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.IGNORECASE | re.UNICODE) if match is None and original: # There are no more matches, but the given string isn't fully # processed yet. new += original break match_start, match_end = match.span() if match_start > 0: # Handle extra characters before matched syllable. if (new and remove_apostrophes and match_start == 1 and original[0] == "'"): pass # Remove the apostrophe between Pinyin syllables. if separate_syllables: # Separate syllables by a space. new += ' ' else: new += original[0:match_start] else: # Matched syllable starts immediately. if new and separate_syllables: # Separate syllables by a space. new += ' ' elif (new and add_apostrophes and match.group()[0].lower() in _UNACCENTED_VOWELS): new += "'" # Convert the matched syllable. new += syllable_function(match.group()) original = original[match_end:] return new
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L313-L343
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L346-L349
train
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_syllables=True)
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_syllables=True)
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L357-L365
train
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=True)
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=True)
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L368-L376
train
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: function = _zhuyin_syllable_to_numbered return _convert(s, zhon.zhuyin.syllable, function)
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: function = _zhuyin_syllable_to_numbered return _convert(s, zhon.zhuyin.syllable, function)
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L379-L390
train
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: function = _ipa_syllable_to_numbered return _convert(s, _IPA_SYLLABLE, function)
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: function = _ipa_syllable_to_numbered return _convert(s, _IPA_SYLLABLE, function)
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L398-L409
train
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 if accented else accented_to_numbered(s) else: return numbered_to_accented(s) if accented else s elif identity == ZHUYIN: return zhuyin_to_pinyin(s, accented=accented) elif identity == IPA: return ipa_to_pinyin(s, accented=accented) else: raise ValueError("String is not a valid Chinese transcription.")
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 if accented else accented_to_numbered(s) else: return numbered_to_accented(s) if accented else s elif identity == ZHUYIN: return zhuyin_to_pinyin(s, accented=accented) elif identity == IPA: return ipa_to_pinyin(s, accented=accented) else: raise ValueError("String is not a valid Chinese transcription.")
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L417-L435
train
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 transcription.")
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 transcription.")
[ "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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L438-L448
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L451-L461
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L464-L467
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L470-L475
train
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* exist in :data:`zhon.zhuyin.characters`, :data:`zhon.zhuyin.marks`, or ``' '``. """ printable_zhuyin = zhon.zhuyin.characters + zhon.zhuyin.marks + ' ' return _is_pattern_match('[%s]+' % printable_zhuyin, 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* exist in :data:`zhon.zhuyin.characters`, :data:`zhon.zhuyin.marks`, or ``' '``. """ printable_zhuyin = zhon.zhuyin.characters + zhon.zhuyin.marks + ' ' return _is_pattern_match('[%s]+' % printable_zhuyin, 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.characters`, :data:`zhon.zhuyin.marks`, or ``' '``.
[ "Checks", "if", "*", "s", "*", "is", "consists", "of", "Zhuyin", "-", "compatible", "characters", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L497-L509
train
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", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L512-L517
train
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* is not a valid transcription system, then :data:`UNKNOWN` is returned. When checking for valid Pinyin or Zhuyin, testing is done on a syllable level, not a character level. For example, just because a string is composed of characters used in Pinyin, doesn't mean that it will identify as Pinyin; it must actually consist of valid Pinyin syllables. The same applies for Zhuyin. When checking for IPA, testing is only done on a character level. In other words, a string just needs to consist of Chinese IPA characters in order to identify as IPA. """ if is_pinyin(s): return PINYIN elif is_zhuyin(s): return ZHUYIN elif is_ipa(s): return IPA else: return UNKNOWN
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* is not a valid transcription system, then :data:`UNKNOWN` is returned. When checking for valid Pinyin or Zhuyin, testing is done on a syllable level, not a character level. For example, just because a string is composed of characters used in Pinyin, doesn't mean that it will identify as Pinyin; it must actually consist of valid Pinyin syllables. The same applies for Zhuyin. When checking for IPA, testing is only done on a character level. In other words, a string just needs to consist of Chinese IPA characters in order to identify as IPA. """ if is_pinyin(s): return PINYIN elif is_zhuyin(s): return ZHUYIN elif is_ipa(s): return IPA else: return UNKNOWN
[ "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 transcription system, then :data:`UNKNOWN` is returned. When checking for valid Pinyin or Zhuyin, testing is done on a syllable level, not a character level. For example, just because a string is composed of characters used in Pinyin, doesn't mean that it will identify as Pinyin; it must actually consist of valid Pinyin syllables. The same applies for Zhuyin. When checking for IPA, testing is only done on a character level. In other words, a string just needs to consist of Chinese IPA characters in order to identify as IPA.
[ "Identify", "a", "given", "string", "s", "transcription", "system", "." ]
68eaf43c32725f4b4923c01284cfc0112079e8ab
https://github.com/tsroten/dragonmapper/blob/68eaf43c32725f4b4923c01284cfc0112079e8ab/dragonmapper/transcriptions.py#L520-L548
train
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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L16-L19
train
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: break return x
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: break return x
[ "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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L21-L29
train
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: alpha = - np.dot(m, np.dot(h, g)) / np.dot(m, np.dot(h, m)) m = g + np.dot(alpha, m) t = - np.dot(m, g) / np.dot(m, np.dot(h, m)) delta = np.dot(t, m) x = x + delta if np.linalg.norm(delta) < self.tol: break return x
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: alpha = - np.dot(m, np.dot(h, g)) / np.dot(m, np.dot(h, m)) m = g + np.dot(alpha, m) t = - np.dot(m, g) / np.dot(m, np.dot(h, m)) delta = np.dot(t, m) x = x + delta if np.linalg.norm(delta) < self.tol: break return x
[ "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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L69-L86
train
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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L106-L114
train
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): return (self.f(angles, target) + np.sum(self.smooth_factor * np.power(a, 2))) else: raise ValueError('len(smooth_factor) != number of joints') else: return (self.f(angles, target) + self.smooth_factor * np.sum(np.power(a, 2))) 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): a = angles - angles0 if isinstance(self.smooth_factor, (np.ndarray, list)): if len(a) == len(self.smooth_factor): return (self.f(angles, target) + np.sum(self.smooth_factor * np.power(a, 2))) else: raise ValueError('len(smooth_factor) != number of joints') else: return (self.f(angles, target) + self.smooth_factor * np.sum(np.power(a, 2))) return scipy.optimize.minimize( new_objective, angles0, **self.optimizer_opt).x
[ "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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/optimizer.py#L130-L147
train
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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/solver.py#L26-L32
train
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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/solver.py#L47-L49
train
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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/component.py#L13-L21
train
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", "." ]
dffe5031ee044caf43e51746c4b0a6d45922d50e
https://github.com/lanius/tinyik/blob/dffe5031ee044caf43e51746c4b0a6d45922d50e/tinyik/component.py#L31-L38
train
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 self.session.set_logger(self.__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 self.session.set_logger(self.__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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L92-L102
train
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') return open(version_file).read().strip()
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') return open(version_file).read().strip()
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L104-L115
train
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 ------- boolean True if the user authenticated or raises an exception if not Raises ------ session.AuthenticationError If authentication failed session.NetworkError If a network error occurred """ if self.session.authenticate(email, password): return True
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 ------- boolean True if the user authenticated or raises an exception if not Raises ------ session.AuthenticationError If authentication failed session.NetworkError If a network error occurred """ if self.session.authenticate(email, password): return True
[ "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 raises an exception if not Raises ------ session.AuthenticationError If authentication failed session.NetworkError If a network error occurred
[ "Attempt", "to", "authenticate", "the", "user", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L117-L141
train
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') json_response = response.json() if self.session.json_success(json_response): self.__log('Cash available: {0}'.format(json_response['cashBalance'])) cash_value = json_response['cashBalance'] # Convert currency to float value # Match values like $1,000.12 or 1,0000$ cash_match = re.search('^[^0-9]?([0-9\.,]+)[^0-9]?', cash_value) if cash_match: cash_str = cash_match.group(1) cash_str = cash_str.replace(',', '') cash = float(cash_str) else: self.__log('Could not get cash balance: {0}'.format(response.text)) except Exception as e: self.__log('Could not get the cash balance on the account: Error: {0}\nJSON: {1}'.format(str(e), response.text)) raise e return cash
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') json_response = response.json() if self.session.json_success(json_response): self.__log('Cash available: {0}'.format(json_response['cashBalance'])) cash_value = json_response['cashBalance'] # Convert currency to float value # Match values like $1,000.12 or 1,0000$ cash_match = re.search('^[^0-9]?([0-9\.,]+)[^0-9]?', cash_value) if cash_match: cash_str = cash_match.group(1) cash_str = cash_str.replace(',', '') cash = float(cash_str) else: self.__log('Could not get cash balance: {0}'.format(response.text)) except Exception as e: self.__log('Could not get the cash balance on the account: Error: {0}\nJSON: {1}'.format(str(e), response.text)) raise e return cash
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L154-L186
train
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 Returns ------- list A list of portfolios (or names, if `names_only` is True) """ folios = [] response = self.session.get('/data/portfolioManagement?method=getLCPortfolios') json_response = response.json() # Get portfolios and create a list of names if self.session.json_success(json_response): folios = json_response['results'] if names_only is True: for i, folio in enumerate(folios): folios[i] = folio['portfolioName'] return folios
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 Returns ------- list A list of portfolios (or names, if `names_only` is True) """ folios = [] response = self.session.get('/data/portfolioManagement?method=getLCPortfolios') json_response = response.json() # Get portfolios and create a list of names if self.session.json_success(json_response): folios = json_response['results'] if names_only is True: for i, folio in enumerate(folios): folios[i] = folio['portfolioName'] return folios
[ "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 portfolios (or names, if `names_only` is True)
[ "Get", "your", "list", "of", "named", "portfolios", "from", "the", "lendingclub", ".", "com" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L203-L229
train
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 for `loan_id[5]` Parameters ---------- portfolio_name : string The name of the portfolio to assign a the loan note to -- new or existing loan_id : int or list The loan ID, or list of loan IDs, to assign to the portfolio order_id : int or list The order ID, or list of order IDs, that this loan note was invested with. You can find this in the dict returned from `get_note()` Returns ------- boolean True on success """ response = None assert type(loan_id) == type(order_id), "Both loan_id and order_id need to be the same type" assert type(loan_id) in (int, list), "loan_id and order_id can only be int or list types" assert type(loan_id) is int or (type(loan_id) is list and len(loan_id) == len(order_id)), "If order_id and loan_id are lists, they both need to be the same length" # Data post = { 'loan_id': loan_id, 'record_id': loan_id, 'order_id': order_id } query = { 'method': 'createLCPortfolio', 'lcportfolio_name': portfolio_name } # Is it an existing portfolio existing = self.get_portfolio_list() for folio in existing: if folio['portfolioName'] == portfolio_name: query['method'] = 'addToLCPortfolio' # Send response = self.session.post('/data/portfolioManagement', query=query, data=post) json_response = response.json() # Failed if not self.session.json_success(json_response): raise LendingClubError('Could not assign order to portfolio \'{0}\''.format(portfolio_name), response) # Success else: # Assigned to another portfolio, for some reason, raise warning if 'portfolioName' in json_response and json_response['portfolioName'] != portfolio_name: raise LendingClubError('Added order to portfolio "{0}" - NOT - "{1}", and I don\'t know why'.format(json_response['portfolioName'], portfolio_name)) # Assigned to the correct portfolio else: self.__log('Added order to portfolio "{0}"'.format(portfolio_name)) return True return False
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 for `loan_id[5]` Parameters ---------- portfolio_name : string The name of the portfolio to assign a the loan note to -- new or existing loan_id : int or list The loan ID, or list of loan IDs, to assign to the portfolio order_id : int or list The order ID, or list of order IDs, that this loan note was invested with. You can find this in the dict returned from `get_note()` Returns ------- boolean True on success """ response = None assert type(loan_id) == type(order_id), "Both loan_id and order_id need to be the same type" assert type(loan_id) in (int, list), "loan_id and order_id can only be int or list types" assert type(loan_id) is int or (type(loan_id) is list and len(loan_id) == len(order_id)), "If order_id and loan_id are lists, they both need to be the same length" # Data post = { 'loan_id': loan_id, 'record_id': loan_id, 'order_id': order_id } query = { 'method': 'createLCPortfolio', 'lcportfolio_name': portfolio_name } # Is it an existing portfolio existing = self.get_portfolio_list() for folio in existing: if folio['portfolioName'] == portfolio_name: query['method'] = 'addToLCPortfolio' # Send response = self.session.post('/data/portfolioManagement', query=query, data=post) json_response = response.json() # Failed if not self.session.json_success(json_response): raise LendingClubError('Could not assign order to portfolio \'{0}\''.format(portfolio_name), response) # Success else: # Assigned to another portfolio, for some reason, raise warning if 'portfolioName' in json_response and json_response['portfolioName'] != portfolio_name: raise LendingClubError('Added order to portfolio "{0}" - NOT - "{1}", and I don\'t know why'.format(json_response['portfolioName'], portfolio_name)) # Assigned to the correct portfolio else: self.__log('Added order to portfolio "{0}"'.format(portfolio_name)) return True return False
[ "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 : string The name of the portfolio to assign a the loan note to -- new or existing loan_id : int or list The loan ID, or list of loan IDs, to assign to the portfolio order_id : int or list The order ID, or list of order IDs, that this loan note was invested with. You can find this in the dict returned from `get_note()` Returns ------- boolean True on success
[ "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"...
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L258-L323
train
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 use to search for notes. If no filter is passed, a wildcard search will be performed. 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 index in the results. For example, to get results 200 - 300, set `start_index` to 200. (default is 0) limit : int, optional The number of results to return per request. (default is 100) Returns ------- dict A dictionary object with the list of matching loans under the `loans` key. """ assert filters is None or isinstance(filters, Filter), 'filter is not a lendingclub.filters.Filter' # Set filters if filters: filter_string = filters.search_string() else: filter_string = 'default' payload = { 'method': 'search', 'filter': filter_string, 'startindex': start_index, 'pagesize': limit } # Make request response = self.session.post('/browse/browseNotesAj.action', data=payload) json_response = response.json() if self.session.json_success(json_response): results = json_response['searchresult'] # Normalize results by converting loanGUID -> loan_id for loan in results['loans']: loan['loan_id'] = int(loan['loanGUID']) # Validate that fractions do indeed match the filters if filters is not None: filters.validate(results['loans']) return results return False
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 use to search for notes. If no filter is passed, a wildcard search will be performed. 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 index in the results. For example, to get results 200 - 300, set `start_index` to 200. (default is 0) limit : int, optional The number of results to return per request. (default is 100) Returns ------- dict A dictionary object with the list of matching loans under the `loans` key. """ assert filters is None or isinstance(filters, Filter), 'filter is not a lendingclub.filters.Filter' # Set filters if filters: filter_string = filters.search_string() else: filter_string = 'default' payload = { 'method': 'search', 'filter': filter_string, 'startindex': start_index, 'pagesize': limit } # Make request response = self.session.post('/browse/browseNotesAj.action', data=payload) json_response = response.json() if self.session.json_success(json_response): results = json_response['searchresult'] # Normalize results by converting loanGUID -> loan_id for loan in results['loans']: loan['loan_id'] = int(loan['loanGUID']) # Validate that fractions do indeed match the filters if filters is not None: filters.validate(results['loans']) return results return False
[ "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 will be performed. 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 index in the results. For example, to get results 200 - 300, set `start_index` to 200. (default is 0) limit : int, optional The number of results to return per request. (default is 100) Returns ------- dict A dictionary object with the list of matching loans under the `loans` key.
[ "Search", "for", "a", "list", "of", "notes", "that", "can", "be", "invested", "in", ".", "(", "similar", "to", "searching", "for", "notes", "in", "the", "Browse", "section", "on", "the", "site", ")" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L325-L378
train
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 start an order and use add_batch to add all the loan fragments to them. (see examples) Parameters ---------- cash : int The total amount you want to invest across a portfolio of loans (at least $25). max_per_note : int, optional The maximum dollar amount you want to invest per note. Must be a multiple of 25 min_percent : int, optional THIS IS NOT PER NOTE, but the minimum average percent of return for the entire portfolio. max_percent : int, optional THIS IS NOT PER NOTE, but the maxmimum average percent of return for the entire portfolio. filters : lendingclub.filters.*, optional The filters to use to search for portfolios automatically_invest : boolean, optional If you want the tool to create an order and automatically invest in the portfolio that matches your filter. (default False) do_not_clear_staging : boolean, optional Similar to automatically_invest, don't do this unless you know what you're doing. Setting this to True stops the method from clearing the loan staging area before returning Returns ------- dict A dict representing a new portfolio or False if nothing was found. If `automatically_invest` was set to `True`, the dict will contain an `order_id` key with the ID of the completed investment order. Notes ----- **The min/max_percent parameters** When searching for portfolios, these parameters will match a portfolio of loan notes which have an **AVERAGE** percent return between these values. If there are multiple portfolio matches, the one closes to the max percent will be chosen. Examples -------- Here we want to invest $400 in a portfolio with only B, C, D and E grade notes with an average overall return between 17% - 19%. This similar to finding a portfolio in the 'Invest' section on lendingclub.com:: >>> from lendingclub import LendingClub >>> from lendingclub.filters import Filter >>> lc = LendingClub() >>> lc.authenticate() Email:test@test.com Password: True >>> filters = Filter() # Set the search filters (only B, C, D and E grade notes) >>> filters['grades']['C'] = True >>> filters['grades']['D'] = True >>> filters['grades']['E'] = True >>> lc.get_cash_balance() # See the cash you have available for investing 463.80000000000001 >>> portfolio = lc.build_portfolio(400, # Invest $400 in a portfolio... min_percent=17.0, # Return percent average between 17 - 19% max_percent=19.0, max_per_note=50, # As much as $50 per note filters=filters) # Search using your filters >>> len(portfolio['loan_fractions']) # See how many loans are in this portfolio 16 >>> loans_notes = portfolio['loan_fractions'] >>> order = lc.start_order() # Start a new order >>> order.add_batch(loans_notes) # Add the loan notes to the order >>> order.execute() # Execute the order 1861880 Here we do a similar search, but automatically invest the found portfolio. **NOTE** This does not allow you to review the portfolio before you invest in it. >>> from lendingclub import LendingClub >>> from lendingclub.filters import Filter >>> lc = LendingClub() >>> lc.authenticate() Email:test@test.com Password: True # Filter shorthand >>> filters = Filter({'grades': {'B': True, 'C': True, 'D': True, 'E': True}}) >>> lc.get_cash_balance() # See the cash you have available for investing 463.80000000000001 >>> portfolio = lc.build_portfolio(400, min_percent=17.0, max_percent=19.0, max_per_note=50, filters=filters, automatically_invest=True) # Same settings, except invest immediately >>> portfolio['order_id'] # See order ID 1861880 """ assert filters is None or isinstance(filters, Filter), 'filter is not a lendingclub.filters.Filter' assert max_per_note >= 25, 'max_per_note must be greater than or equal to 25' # Set filters if filters: filter_str = filters.search_string() else: filter_str = 'default' # Start a new order self.session.clear_session_order() # Make request payload = { 'amount': cash, 'max_per_note': max_per_note, 'filter': filter_str } self.__log('POST VALUES -- amount: {0}, max_per_note: {1}, filter: ...'.format(cash, max_per_note)) response = self.session.post('/portfolio/lendingMatchOptionsV2.action', data=payload) json_response = response.json() # Options were found if self.session.json_success(json_response) and 'lmOptions' in json_response: options = json_response['lmOptions'] # Nothing found if type(options) is not list or json_response['numberTicks'] == 0: self.__log('No lending portfolios were returned with your search') return False # Choose an investment option based on the user's min/max values i = 0 match_index = -1 match_option = None for option in options: # A perfect match if option['percentage'] == max_percent: match_option = option match_index = i break # Over the max elif option['percentage'] > max_percent: break # Higher than the minimum percent and the current matched option elif option['percentage'] >= min_percent and (match_option is None or match_option['percentage'] < option['percentage']): match_option = option match_index = i i += 1 # Nothing matched if match_option is None: self.__log('No portfolios matched your percentage requirements') return False # Mark this portfolio for investing (in order to get a list of all notes) payload = { 'order_amount': cash, 'lending_match_point': match_index, 'lending_match_version': 'v2' } self.session.get('/portfolio/recommendPortfolio.action', query=payload) # Get all loan fractions payload = { 'method': 'getPortfolio' } response = self.session.get('/data/portfolio', query=payload) json_response = response.json() # Extract fractions from response fractions = [] if 'loanFractions' in json_response: fractions = json_response['loanFractions'] # Normalize by converting loanFractionAmount to invest_amount for frac in fractions: frac['invest_amount'] = frac['loanFractionAmount'] # Raise error if amount is greater than max_per_note if frac['invest_amount'] > max_per_note: raise LendingClubError('ERROR: LendingClub tried to invest ${0} in a loan note. Your max per note is set to ${1}. Portfolio investment canceled.'.format(frac['invest_amount'], max_per_note)) if len(fractions) == 0: self.__log('The selected portfolio didn\'t have any loans') return False match_option['loan_fractions'] = fractions # Validate that fractions do indeed match the filters if filters is not None: filters.validate(fractions) # Not investing -- reset portfolio search session and return if automatically_invest is not True: if do_not_clear_staging is not True: self.session.clear_session_order() # Invest in this porfolio elif automatically_invest is True: # just to be sure order = self.start_order() # This should probably only be ever done here...ever. order._Order__already_staged = True order._Order__i_know_what_im_doing = True order.add_batch(match_option['loan_fractions']) order_id = order.execute() match_option['order_id'] = order_id return match_option else: raise LendingClubError('Could not find any portfolio options that match your filters', response) return False
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 start an order and use add_batch to add all the loan fragments to them. (see examples) Parameters ---------- cash : int The total amount you want to invest across a portfolio of loans (at least $25). max_per_note : int, optional The maximum dollar amount you want to invest per note. Must be a multiple of 25 min_percent : int, optional THIS IS NOT PER NOTE, but the minimum average percent of return for the entire portfolio. max_percent : int, optional THIS IS NOT PER NOTE, but the maxmimum average percent of return for the entire portfolio. filters : lendingclub.filters.*, optional The filters to use to search for portfolios automatically_invest : boolean, optional If you want the tool to create an order and automatically invest in the portfolio that matches your filter. (default False) do_not_clear_staging : boolean, optional Similar to automatically_invest, don't do this unless you know what you're doing. Setting this to True stops the method from clearing the loan staging area before returning Returns ------- dict A dict representing a new portfolio or False if nothing was found. If `automatically_invest` was set to `True`, the dict will contain an `order_id` key with the ID of the completed investment order. Notes ----- **The min/max_percent parameters** When searching for portfolios, these parameters will match a portfolio of loan notes which have an **AVERAGE** percent return between these values. If there are multiple portfolio matches, the one closes to the max percent will be chosen. Examples -------- Here we want to invest $400 in a portfolio with only B, C, D and E grade notes with an average overall return between 17% - 19%. This similar to finding a portfolio in the 'Invest' section on lendingclub.com:: >>> from lendingclub import LendingClub >>> from lendingclub.filters import Filter >>> lc = LendingClub() >>> lc.authenticate() Email:test@test.com Password: True >>> filters = Filter() # Set the search filters (only B, C, D and E grade notes) >>> filters['grades']['C'] = True >>> filters['grades']['D'] = True >>> filters['grades']['E'] = True >>> lc.get_cash_balance() # See the cash you have available for investing 463.80000000000001 >>> portfolio = lc.build_portfolio(400, # Invest $400 in a portfolio... min_percent=17.0, # Return percent average between 17 - 19% max_percent=19.0, max_per_note=50, # As much as $50 per note filters=filters) # Search using your filters >>> len(portfolio['loan_fractions']) # See how many loans are in this portfolio 16 >>> loans_notes = portfolio['loan_fractions'] >>> order = lc.start_order() # Start a new order >>> order.add_batch(loans_notes) # Add the loan notes to the order >>> order.execute() # Execute the order 1861880 Here we do a similar search, but automatically invest the found portfolio. **NOTE** This does not allow you to review the portfolio before you invest in it. >>> from lendingclub import LendingClub >>> from lendingclub.filters import Filter >>> lc = LendingClub() >>> lc.authenticate() Email:test@test.com Password: True # Filter shorthand >>> filters = Filter({'grades': {'B': True, 'C': True, 'D': True, 'E': True}}) >>> lc.get_cash_balance() # See the cash you have available for investing 463.80000000000001 >>> portfolio = lc.build_portfolio(400, min_percent=17.0, max_percent=19.0, max_per_note=50, filters=filters, automatically_invest=True) # Same settings, except invest immediately >>> portfolio['order_id'] # See order ID 1861880 """ assert filters is None or isinstance(filters, Filter), 'filter is not a lendingclub.filters.Filter' assert max_per_note >= 25, 'max_per_note must be greater than or equal to 25' # Set filters if filters: filter_str = filters.search_string() else: filter_str = 'default' # Start a new order self.session.clear_session_order() # Make request payload = { 'amount': cash, 'max_per_note': max_per_note, 'filter': filter_str } self.__log('POST VALUES -- amount: {0}, max_per_note: {1}, filter: ...'.format(cash, max_per_note)) response = self.session.post('/portfolio/lendingMatchOptionsV2.action', data=payload) json_response = response.json() # Options were found if self.session.json_success(json_response) and 'lmOptions' in json_response: options = json_response['lmOptions'] # Nothing found if type(options) is not list or json_response['numberTicks'] == 0: self.__log('No lending portfolios were returned with your search') return False # Choose an investment option based on the user's min/max values i = 0 match_index = -1 match_option = None for option in options: # A perfect match if option['percentage'] == max_percent: match_option = option match_index = i break # Over the max elif option['percentage'] > max_percent: break # Higher than the minimum percent and the current matched option elif option['percentage'] >= min_percent and (match_option is None or match_option['percentage'] < option['percentage']): match_option = option match_index = i i += 1 # Nothing matched if match_option is None: self.__log('No portfolios matched your percentage requirements') return False # Mark this portfolio for investing (in order to get a list of all notes) payload = { 'order_amount': cash, 'lending_match_point': match_index, 'lending_match_version': 'v2' } self.session.get('/portfolio/recommendPortfolio.action', query=payload) # Get all loan fractions payload = { 'method': 'getPortfolio' } response = self.session.get('/data/portfolio', query=payload) json_response = response.json() # Extract fractions from response fractions = [] if 'loanFractions' in json_response: fractions = json_response['loanFractions'] # Normalize by converting loanFractionAmount to invest_amount for frac in fractions: frac['invest_amount'] = frac['loanFractionAmount'] # Raise error if amount is greater than max_per_note if frac['invest_amount'] > max_per_note: raise LendingClubError('ERROR: LendingClub tried to invest ${0} in a loan note. Your max per note is set to ${1}. Portfolio investment canceled.'.format(frac['invest_amount'], max_per_note)) if len(fractions) == 0: self.__log('The selected portfolio didn\'t have any loans') return False match_option['loan_fractions'] = fractions # Validate that fractions do indeed match the filters if filters is not None: filters.validate(fractions) # Not investing -- reset portfolio search session and return if automatically_invest is not True: if do_not_clear_staging is not True: self.session.clear_session_order() # Invest in this porfolio elif automatically_invest is True: # just to be sure order = self.start_order() # This should probably only be ever done here...ever. order._Order__already_staged = True order._Order__i_know_what_im_doing = True order.add_batch(match_option['loan_fractions']) order_id = order.execute() match_option['order_id'] = order_id return match_option else: raise LendingClubError('Could not find any portfolio options that match your filters', response) return False
[ "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 total amount you want to invest across a portfolio of loans (at least $25). max_per_note : int, optional The maximum dollar amount you want to invest per note. Must be a multiple of 25 min_percent : int, optional THIS IS NOT PER NOTE, but the minimum average percent of return for the entire portfolio. max_percent : int, optional THIS IS NOT PER NOTE, but the maxmimum average percent of return for the entire portfolio. filters : lendingclub.filters.*, optional The filters to use to search for portfolios automatically_invest : boolean, optional If you want the tool to create an order and automatically invest in the portfolio that matches your filter. (default False) do_not_clear_staging : boolean, optional Similar to automatically_invest, don't do this unless you know what you're doing. Setting this to True stops the method from clearing the loan staging area before returning Returns ------- dict A dict representing a new portfolio or False if nothing was found. If `automatically_invest` was set to `True`, the dict will contain an `order_id` key with the ID of the completed investment order. Notes ----- **The min/max_percent parameters** When searching for portfolios, these parameters will match a portfolio of loan notes which have an **AVERAGE** percent return between these values. If there are multiple portfolio matches, the one closes to the max percent will be chosen. Examples -------- Here we want to invest $400 in a portfolio with only B, C, D and E grade notes with an average overall return between 17% - 19%. This similar to finding a portfolio in the 'Invest' section on lendingclub.com:: >>> from lendingclub import LendingClub >>> from lendingclub.filters import Filter >>> lc = LendingClub() >>> lc.authenticate() Email:test@test.com Password: True >>> filters = Filter() # Set the search filters (only B, C, D and E grade notes) >>> filters['grades']['C'] = True >>> filters['grades']['D'] = True >>> filters['grades']['E'] = True >>> lc.get_cash_balance() # See the cash you have available for investing 463.80000000000001 >>> portfolio = lc.build_portfolio(400, # Invest $400 in a portfolio... min_percent=17.0, # Return percent average between 17 - 19% max_percent=19.0, max_per_note=50, # As much as $50 per note filters=filters) # Search using your filters >>> len(portfolio['loan_fractions']) # See how many loans are in this portfolio 16 >>> loans_notes = portfolio['loan_fractions'] >>> order = lc.start_order() # Start a new order >>> order.add_batch(loans_notes) # Add the loan notes to the order >>> order.execute() # Execute the order 1861880 Here we do a similar search, but automatically invest the found portfolio. **NOTE** This does not allow you to review the portfolio before you invest in it. >>> from lendingclub import LendingClub >>> from lendingclub.filters import Filter >>> lc = LendingClub() >>> lc.authenticate() Email:test@test.com Password: True # Filter shorthand >>> filters = Filter({'grades': {'B': True, 'C': True, 'D': True, 'E': True}}) >>> lc.get_cash_balance() # See the cash you have available for investing 463.80000000000001 >>> portfolio = lc.build_portfolio(400, min_percent=17.0, max_percent=19.0, max_per_note=50, filters=filters, automatically_invest=True) # Same settings, except invest immediately >>> portfolio['order_id'] # See order ID 1861880
[ "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", ...
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L380-L594
train
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 to start on. By default only 100 records will be returned at a time, so use this to start at a later index in the results. For example, to get results 200 - 300, set `start_index` to 200. (default is 0) limit : int, optional The number of results to return per request. (default is 100) get_all : boolean, optional Return all results in one request, instead of 100 per request. sort_by : string, optional What key to sort on sort_dir : {'asc', 'desc'}, optional Which direction to sort Returns ------- dict A dictionary with a list of matching notes on the `loans` key """ index = start_index notes = { 'loans': [], 'total': 0, 'result': 'success' } while True: payload = { 'sortBy': sort_by, 'dir': sort_dir, 'startindex': index, 'pagesize': limit, 'namespace': '/account' } response = self.session.post('/account/loansAj.action', data=payload) json_response = response.json() # Notes returned if self.session.json_success(json_response): notes['loans'] += json_response['searchresult']['loans'] notes['total'] = json_response['searchresult']['totalRecords'] # Error else: notes['result'] = json_response['result'] break # Load more if get_all is True and len(notes['loans']) < notes['total']: index += limit # End else: break return notes
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 to start on. By default only 100 records will be returned at a time, so use this to start at a later index in the results. For example, to get results 200 - 300, set `start_index` to 200. (default is 0) limit : int, optional The number of results to return per request. (default is 100) get_all : boolean, optional Return all results in one request, instead of 100 per request. sort_by : string, optional What key to sort on sort_dir : {'asc', 'desc'}, optional Which direction to sort Returns ------- dict A dictionary with a list of matching notes on the `loans` key """ index = start_index notes = { 'loans': [], 'total': 0, 'result': 'success' } while True: payload = { 'sortBy': sort_by, 'dir': sort_dir, 'startindex': index, 'pagesize': limit, 'namespace': '/account' } response = self.session.post('/account/loansAj.action', data=payload) json_response = response.json() # Notes returned if self.session.json_success(json_response): notes['loans'] += json_response['searchresult']['loans'] notes['total'] = json_response['searchresult']['totalRecords'] # Error else: notes['result'] = json_response['result'] break # Load more if get_all is True and len(notes['loans']) < notes['total']: index += limit # End else: break return notes
[ "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 index in the results. For example, to get results 200 - 300, set `start_index` to 200. (default is 0) limit : int, optional The number of results to return per request. (default is 100) get_all : boolean, optional Return all results in one request, instead of 100 per request. sort_by : string, optional What key to sort on sort_dir : {'asc', 'desc'}, optional Which direction to sort Returns ------- dict A dictionary with a list of matching notes on the `loans` key
[ "Return", "all", "the", "loan", "notes", "you", "ve", "already", "invested", "in", ".", "By", "default", "it", "ll", "return", "100", "results", "at", "a", "time", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L596-L656
train
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 -------- >>> from lendingclub import LendingClub >>> lc = LendingClub(email='test@test.com', password='secret123') >>> lc.authenticate() True >>> notes = lc.my_notes() # Get the first 100 loan notes >>> len(notes['loans']) 100 >>> notes['total'] # See the total number of loan notes you have 630 >>> notes = lc.my_notes(start_index=100) # Get the next 100 loan notes >>> len(notes['loans']) 100 >>> notes = lc.my_notes(get_all=True) # Get all notes in one request (may be slow) >>> len(notes['loans']) 630 """ index = 0 while True: notes = self.my_notes(start_index=index, sort_by='noteId') if notes['result'] != 'success': break # If the first note has a higher ID, we've passed it if notes['loans'][0]['noteId'] > note_id: break # If the last note has a higher ID, it could be in this record set if notes['loans'][-1]['noteId'] >= note_id: for note in notes['loans']: if note['noteId'] == note_id: return note index += 100 return False
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 -------- >>> from lendingclub import LendingClub >>> lc = LendingClub(email='test@test.com', password='secret123') >>> lc.authenticate() True >>> notes = lc.my_notes() # Get the first 100 loan notes >>> len(notes['loans']) 100 >>> notes['total'] # See the total number of loan notes you have 630 >>> notes = lc.my_notes(start_index=100) # Get the next 100 loan notes >>> len(notes['loans']) 100 >>> notes = lc.my_notes(get_all=True) # Get all notes in one request (may be slow) >>> len(notes['loans']) 630 """ index = 0 while True: notes = self.my_notes(start_index=index, sort_by='noteId') if notes['result'] != 'success': break # If the first note has a higher ID, we've passed it if notes['loans'][0]['noteId'] > note_id: break # If the last note has a higher ID, it could be in this record set if notes['loans'][-1]['noteId'] >= note_id: for note in notes['loans']: if note['noteId'] == note_id: return note index += 100 return False
[ "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 LendingClub >>> lc = LendingClub(email='test@test.com', password='secret123') >>> lc.authenticate() True >>> notes = lc.my_notes() # Get the first 100 loan notes >>> len(notes['loans']) 100 >>> notes['total'] # See the total number of loan notes you have 630 >>> notes = lc.my_notes(start_index=100) # Get the next 100 loan notes >>> len(notes['loans']) 100 >>> notes = lc.my_notes(get_all=True) # Get all notes in one request (may be slow) >>> len(notes['loans']) 630
[ "Get", "a", "loan", "note", "that", "you", "ve", "invested", "in", "by", "ID" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L658-L710
train
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 ---------- loan_id : int, optional Search for notes for a specific loan. Since a loan is broken up into a pool of notes, it's possible to invest multiple notes in a single loan order_id : int, optional Search for notes from a particular investment order. grade : {A, B, C, D, E, F, G}, optional Match by a particular loan grade portfolio_name : string, optional Search for notes in a portfolio with this name (case sensitive) status : string, {issued, in-review, in-funding, current, charged-off, late, in-grace-period, fully-paid}, optional The funding status string. term : {60, 36}, optional Term length, either 60 or 36 (for 5 year and 3 year, respectively) Returns ------- dict A dictionary with a list of matching notes on the `loans` key """ assert grade is None or type(grade) is str, 'grade must be a string' assert portfolio_name is None or type(portfolio_name) is str, 'portfolio_name must be a string' index = 0 found = [] sort_by = 'orderId' if order_id is not None else 'loanId' group_id = order_id if order_id is not None else loan_id # first match by order, then by loan # Normalize grade if grade is not None: grade = grade[0].upper() # Normalize status if status is not None: status = re.sub('[^a-zA-Z\-]', ' ', status.lower()) # remove all non alpha characters status = re.sub('days', ' ', status) # remove days status = re.sub('\s+', '-', status.strip()) # replace spaces with dash status = re.sub('(^-+)|(-+$)', '', status) while True: notes = self.my_notes(start_index=index, sort_by=sort_by) if notes['result'] != 'success': break # If the first note has a higher ID, we've passed it if group_id is not None and notes['loans'][0][sort_by] > group_id: break # If the last note has a higher ID, it could be in this record set if group_id is None or notes['loans'][-1][sort_by] >= group_id: for note in notes['loans']: # Order ID, no match if order_id is not None and note['orderId'] != order_id: continue # Loan ID, no match if loan_id is not None and note['loanId'] != loan_id: continue # Grade, no match if grade is not None and note['rate'][0] != grade: continue # Portfolio, no match if portfolio_name is not None and note['portfolioName'][0] != portfolio_name: continue # Term, no match if term is not None and note['loanLength'] != term: continue # Status if status is not None: # Normalize status message nstatus = re.sub('[^a-zA-Z\-]', ' ', note['status'].lower()) # remove all non alpha characters nstatus = re.sub('days', ' ', nstatus) # remove days nstatus = re.sub('\s+', '-', nstatus.strip()) # replace spaces with dash nstatus = re.sub('(^-+)|(-+$)', '', nstatus) # No match if nstatus != status: continue # Must be a match found.append(note) index += 100 return found
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 ---------- loan_id : int, optional Search for notes for a specific loan. Since a loan is broken up into a pool of notes, it's possible to invest multiple notes in a single loan order_id : int, optional Search for notes from a particular investment order. grade : {A, B, C, D, E, F, G}, optional Match by a particular loan grade portfolio_name : string, optional Search for notes in a portfolio with this name (case sensitive) status : string, {issued, in-review, in-funding, current, charged-off, late, in-grace-period, fully-paid}, optional The funding status string. term : {60, 36}, optional Term length, either 60 or 36 (for 5 year and 3 year, respectively) Returns ------- dict A dictionary with a list of matching notes on the `loans` key """ assert grade is None or type(grade) is str, 'grade must be a string' assert portfolio_name is None or type(portfolio_name) is str, 'portfolio_name must be a string' index = 0 found = [] sort_by = 'orderId' if order_id is not None else 'loanId' group_id = order_id if order_id is not None else loan_id # first match by order, then by loan # Normalize grade if grade is not None: grade = grade[0].upper() # Normalize status if status is not None: status = re.sub('[^a-zA-Z\-]', ' ', status.lower()) # remove all non alpha characters status = re.sub('days', ' ', status) # remove days status = re.sub('\s+', '-', status.strip()) # replace spaces with dash status = re.sub('(^-+)|(-+$)', '', status) while True: notes = self.my_notes(start_index=index, sort_by=sort_by) if notes['result'] != 'success': break # If the first note has a higher ID, we've passed it if group_id is not None and notes['loans'][0][sort_by] > group_id: break # If the last note has a higher ID, it could be in this record set if group_id is None or notes['loans'][-1][sort_by] >= group_id: for note in notes['loans']: # Order ID, no match if order_id is not None and note['orderId'] != order_id: continue # Loan ID, no match if loan_id is not None and note['loanId'] != loan_id: continue # Grade, no match if grade is not None and note['rate'][0] != grade: continue # Portfolio, no match if portfolio_name is not None and note['portfolioName'][0] != portfolio_name: continue # Term, no match if term is not None and note['loanLength'] != term: continue # Status if status is not None: # Normalize status message nstatus = re.sub('[^a-zA-Z\-]', ' ', note['status'].lower()) # remove all non alpha characters nstatus = re.sub('days', ' ', nstatus) # remove days nstatus = re.sub('\s+', '-', nstatus.strip()) # replace spaces with dash nstatus = re.sub('(^-+)|(-+$)', '', nstatus) # No match if nstatus != status: continue # Must be a match found.append(note) index += 100 return found
[ "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 of notes, it's possible to invest multiple notes in a single loan order_id : int, optional Search for notes from a particular investment order. grade : {A, B, C, D, E, F, G}, optional Match by a particular loan grade portfolio_name : string, optional Search for notes in a portfolio with this name (case sensitive) status : string, {issued, in-review, in-funding, current, charged-off, late, in-grace-period, fully-paid}, optional The funding status string. term : {60, 36}, optional Term length, either 60 or 36 (for 5 year and 3 year, respectively) Returns ------- dict A dictionary with a list of matching notes on the `loans` key
[ "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", ")" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L712-L808
train
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 you want to add or a dictionary containing a `loan_id` value amount : int % 25 The dollar amount you want to invest in this loan, as a multiple of 25. """ assert amount > 0 and amount % 25 == 0, 'Amount must be a multiple of 25' assert type(amount) in (float, int), 'Amount must be a number' if type(loan_id) is dict: loan = loan_id assert 'loan_id' in loan and type(loan['loan_id']) is int, 'loan_id must be a number or dictionary containing a loan_id value' loan_id = loan['loan_id'] assert type(loan_id) in [str, unicode, int], 'Loan ID must be an integer number or a string' self.loans[loan_id] = amount
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 you want to add or a dictionary containing a `loan_id` value amount : int % 25 The dollar amount you want to invest in this loan, as a multiple of 25. """ assert amount > 0 and amount % 25 == 0, 'Amount must be a multiple of 25' assert type(amount) in (float, int), 'Amount must be a number' if type(loan_id) is dict: loan = loan_id assert 'loan_id' in loan and type(loan['loan_id']) is int, 'loan_id must be a number or dictionary containing a loan_id value' loan_id = loan['loan_id'] assert type(loan_id) in [str, unicode, int], 'Loan ID must be an integer number or a string' self.loans[loan_id] = amount
[ "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` value amount : int % 25 The dollar amount you want to invest in this loan, as a multiple of 25.
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L906-L928
train
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, optional The dollar amount you want to set on ALL loans in this batch. **NOTE:** This will override the invest_amount value for each loan. Examples -------- Each item in the loans list can either be a loan ID OR a dictionary object containing `loan_id` and `invest_amount` values. The invest_amount value is the dollar amount you wish to invest in this loan. **List of IDs**:: # Invest $50 in 3 loans order.add_batch([1234, 2345, 3456], 50) **List of Dictionaries**:: # Invest different amounts in each loans order.add_batch([ {'loan_id': 1234, invest_amount: 50}, {'loan_id': 2345, invest_amount: 25}, {'loan_id': 3456, invest_amount: 150} ]) """ assert batch_amount is None or batch_amount % 25 == 0, 'batch_amount must be a multiple of 25' # Add each loan assert type(loans) is list, 'The loans property must be a list. (not {0})'.format(type(loans)) for loan in loans: loan_id = loan amount = batch_amount # Extract ID and amount from loan dict if type(loan) is dict: assert 'loan_id' in loan, 'Each loan dict must have a loan_id value' assert batch_amount or 'invest_amount' in loan, 'Could not determine how much to invest in loan {0}'.format(loan['loan_id']) loan_id = loan['loan_id'] if amount is None and 'invest_amount' in loan: amount = loan['invest_amount'] assert amount is not None, 'Could not determine how much to invest in loan {0}'.format(loan_id) assert amount % 25 == 0, 'Amount to invest must be a multiple of 25 (loan_id: {0})'.format(loan_id) self.add(loan_id, amount)
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, optional The dollar amount you want to set on ALL loans in this batch. **NOTE:** This will override the invest_amount value for each loan. Examples -------- Each item in the loans list can either be a loan ID OR a dictionary object containing `loan_id` and `invest_amount` values. The invest_amount value is the dollar amount you wish to invest in this loan. **List of IDs**:: # Invest $50 in 3 loans order.add_batch([1234, 2345, 3456], 50) **List of Dictionaries**:: # Invest different amounts in each loans order.add_batch([ {'loan_id': 1234, invest_amount: 50}, {'loan_id': 2345, invest_amount: 25}, {'loan_id': 3456, invest_amount: 150} ]) """ assert batch_amount is None or batch_amount % 25 == 0, 'batch_amount must be a multiple of 25' # Add each loan assert type(loans) is list, 'The loans property must be a list. (not {0})'.format(type(loans)) for loan in loans: loan_id = loan amount = batch_amount # Extract ID and amount from loan dict if type(loan) is dict: assert 'loan_id' in loan, 'Each loan dict must have a loan_id value' assert batch_amount or 'invest_amount' in loan, 'Could not determine how much to invest in loan {0}'.format(loan['loan_id']) loan_id = loan['loan_id'] if amount is None and 'invest_amount' in loan: amount = loan['invest_amount'] assert amount is not None, 'Could not determine how much to invest in loan {0}'.format(loan_id) assert amount % 25 == 0, 'Amount to invest must be a multiple of 25 (loan_id: {0})'.format(loan_id) self.add(loan_id, amount)
[ "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 this batch. **NOTE:** This will override the invest_amount value for each loan. Examples -------- Each item in the loans list can either be a loan ID OR a dictionary object containing `loan_id` and `invest_amount` values. The invest_amount value is the dollar amount you wish to invest in this loan. **List of IDs**:: # Invest $50 in 3 loans order.add_batch([1234, 2345, 3456], 50) **List of Dictionaries**:: # Invest different amounts in each loans order.add_batch([ {'loan_id': 1234, invest_amount: 50}, {'loan_id': 2345, invest_amount: 25}, {'loan_id': 3456, invest_amount: 150} ])
[ "Add", "a", "batch", "of", "loans", "to", "your", "order", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L943-L994
train
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 ------ LendingClubError Returns ------- int The completed order ID """ assert self.order_id == 0, 'This order has already been place. Start a new order.' assert len(self.loans) > 0, 'There aren\'t any loans in your order' # Place the order self.__stage_order() token = self.__get_strut_token() self.order_id = self.__place_order(token) self.__log('Order #{0} was successfully submitted'.format(self.order_id)) # Assign to portfolio if portfolio_name: return self.assign_to_portfolio(portfolio_name) return self.order_id
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 ------ LendingClubError Returns ------- int The completed order ID """ assert self.order_id == 0, 'This order has already been place. Start a new order.' assert len(self.loans) > 0, 'There aren\'t any loans in your order' # Place the order self.__stage_order() token = self.__get_strut_token() self.order_id = self.__place_order(token) self.__log('Order #{0} was successfully submitted'.format(self.order_id)) # Assign to portfolio if portfolio_name: return self.assign_to_portfolio(portfolio_name) return self.order_id
[ "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 ------- int The completed order ID
[ "Place", "the", "order", "with", "LendingClub" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1014-L1047
train
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 Returns ------- boolean True on success """ 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.loans.keys() # Make a list of 1 order ID per loan order_ids = [self.order_id]*len(loan_ids) return self.lc.assign_to_portfolio(portfolio_name, loan_ids, order_ids)
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 Returns ------- boolean True on success """ 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.loans.keys() # Make a list of 1 order ID per loan order_ids = [self.order_id]*len(loan_ids) return self.lc.assign_to_portfolio(portfolio_name, loan_ids, order_ids)
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1049-L1074
train
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 what you\'re doing...'.format(len(self.loans))) return self.__log('Staging order for {0} loan notes...'.format(len(self.loans))) # Create a fresh order session self.lc.session.clear_session_order() # # Stage all the loans to the order # loan_ids = self.loans.keys() self.__log('Staging loans {0}'.format(loan_ids)) # LendingClub requires you to search for the loans before you can stage them f = FilterByLoanID(loan_ids) results = self.lc.search(f, limit=len(self.loans)) if len(results['loans']) == 0 or results['totalRecords'] != len(self.loans): raise LendingClubError('Could not stage the loans. The number of loans in your batch does not match totalRecords. {0} != {1}'.format(len(self.loans), results['totalRecords']), results) # Stage each loan for loan_id, amount in self.loans.iteritems(): payload = { 'method': 'addToPortfolio', 'loan_id': loan_id, 'loan_amount': amount, 'remove': 'false' } response = self.lc.session.get('/data/portfolio', query=payload) json_response = response.json() # Ensure it was successful before moving on if not self.lc.session.json_success(json_response): raise LendingClubError('Could not stage loan {0} on the order: {1}'.format(loan_id, response.text), response) # # Add all staged loans to the order # payload = { 'method': 'addToPortfolioNew' } response = self.lc.session.get('/data/portfolio', query=payload) json_response = response.json() if self.lc.session.json_success(json_response): self.__log(json_response['message']) return True else: raise self.__log('Could not add loans to the order: {0}'.format(response.text)) raise LendingClubError('Could not add loans to the order', response.text)
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 what you\'re doing...'.format(len(self.loans))) return self.__log('Staging order for {0} loan notes...'.format(len(self.loans))) # Create a fresh order session self.lc.session.clear_session_order() # # Stage all the loans to the order # loan_ids = self.loans.keys() self.__log('Staging loans {0}'.format(loan_ids)) # LendingClub requires you to search for the loans before you can stage them f = FilterByLoanID(loan_ids) results = self.lc.search(f, limit=len(self.loans)) if len(results['loans']) == 0 or results['totalRecords'] != len(self.loans): raise LendingClubError('Could not stage the loans. The number of loans in your batch does not match totalRecords. {0} != {1}'.format(len(self.loans), results['totalRecords']), results) # Stage each loan for loan_id, amount in self.loans.iteritems(): payload = { 'method': 'addToPortfolio', 'loan_id': loan_id, 'loan_amount': amount, 'remove': 'false' } response = self.lc.session.get('/data/portfolio', query=payload) json_response = response.json() # Ensure it was successful before moving on if not self.lc.session.json_success(json_response): raise LendingClubError('Could not stage loan {0} on the order: {1}'.format(loan_id, response.text), response) # # Add all staged loans to the order # payload = { 'method': 'addToPortfolioNew' } response = self.lc.session.get('/data/portfolio', query=payload) json_response = response.json() if self.lc.session.json_success(json_response): self.__log(json_response['message']) return True else: raise self.__log('Could not add loans to the order: {0}'.format(response.text)) raise LendingClubError('Could not add loans to the order', response.text)
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1076-L1132
train
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 """ try: # Move to the place order page and get the struts token response = self.lc.session.get('/portfolio/placeOrder.action') soup = BeautifulSoup(response.text, "html5lib") # Example HTML with the stuts token: """ <input type="hidden" name="struts.token.name" value="token" /> <input type="hidden" name="token" value="C4MJZP39Q86KDX8KN8SBTVCP0WSFBXEL" /> """ # 'struts.token.name' defines the field name with the token value strut_tag = None strut_token_name = soup.find('input', {'name': 'struts.token.name'}) if strut_token_name and strut_token_name['value'].strip(): # Get form around the strut.token.name element form = soup.form # assumed for parent in strut_token_name.parents: if parent and parent.name == 'form': form = parent break # Get strut token value strut_token_name = strut_token_name['value'] strut_tag = soup.find('input', {'name': strut_token_name}) if strut_tag and strut_tag['value'].strip(): return {'name': strut_token_name, 'value': strut_tag['value'].strip()} # No strut token found self.__log('No struts token! HTML: {0}'.format(response.text)) raise LendingClubError('No struts token. Please report this error.', response) except Exception as e: self.__log('Could not get struts token. Error message: {0}'.format(str(e))) raise LendingClubError('Could not get struts token. Error message: {0}'.format(str(e)))
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 """ try: # Move to the place order page and get the struts token response = self.lc.session.get('/portfolio/placeOrder.action') soup = BeautifulSoup(response.text, "html5lib") # Example HTML with the stuts token: """ <input type="hidden" name="struts.token.name" value="token" /> <input type="hidden" name="token" value="C4MJZP39Q86KDX8KN8SBTVCP0WSFBXEL" /> """ # 'struts.token.name' defines the field name with the token value strut_tag = None strut_token_name = soup.find('input', {'name': 'struts.token.name'}) if strut_token_name and strut_token_name['value'].strip(): # Get form around the strut.token.name element form = soup.form # assumed for parent in strut_token_name.parents: if parent and parent.name == 'form': form = parent break # Get strut token value strut_token_name = strut_token_name['value'] strut_tag = soup.find('input', {'name': strut_token_name}) if strut_tag and strut_tag['value'].strip(): return {'name': strut_token_name, 'value': strut_tag['value'].strip()} # No strut token found self.__log('No struts token! HTML: {0}'.format(response.text)) raise LendingClubError('No struts token. Please report this error.', response) except Exception as e: self.__log('Could not get struts token. Error message: {0}'.format(str(e))) raise LendingClubError('Could not get struts token. Error message: {0}'.format(str(e)))
[ "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", "()" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1134-L1183
train
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. """ order_id = 0 response = None if not token or token['value'] == '': raise LendingClubError('The token parameter is False, None or unknown.') # Process order confirmation page try: # Place the order payload = {} if token: payload['struts.token.name'] = token['name'] payload[token['name']] = token['value'] response = self.lc.session.post('/portfolio/orderConfirmed.action', data=payload) # Process HTML for the order ID html = response.text soup = BeautifulSoup(html, 'html5lib') # Order num order_field = soup.find(id='order_id') if order_field: order_id = int(order_field['value']) # Did not find an ID if order_id == 0: self.__log('An investment order was submitted, but a confirmation ID could not be determined') raise LendingClubError('No order ID was found when placing the order.', response) else: return order_id except Exception as e: raise LendingClubError('Could not place the order: {0}'.format(str(e)), response)
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. """ order_id = 0 response = None if not token or token['value'] == '': raise LendingClubError('The token parameter is False, None or unknown.') # Process order confirmation page try: # Place the order payload = {} if token: payload['struts.token.name'] = token['name'] payload[token['name']] = token['value'] response = self.lc.session.post('/portfolio/orderConfirmed.action', data=payload) # Process HTML for the order ID html = response.text soup = BeautifulSoup(html, 'html5lib') # Order num order_field = soup.find(id='order_id') if order_field: order_id = int(order_field['value']) # Did not find an ID if order_id == 0: self.__log('An investment order was submitted, but a confirmation ID could not be determined') raise LendingClubError('No order ID was found when placing the order.', response) else: return order_id except Exception as e: raise LendingClubError('Could not place the order: {0}'.format(str(e)), response)
[ "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", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/__init__.py#L1185-L1231
train
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) timeout_sec = self.session_timeout * 60 # convert minutes to seconds if diff >= timeout_sec: self.__log('Session timed out, attempting to authenticate') self.authenticate()
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) timeout_sec = self.session_timeout * 60 # convert minutes to seconds if diff >= timeout_sec: self.__log('Session timed out, attempting to authenticate') self.authenticate()
[ "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", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L73-L85
train
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, path) url = re.sub('([^:])//', '\\1/', url) # Remove double slashes return 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, path) url = re.sub('([^:])//', '\\1/', url) # Remove double slashes return 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", ")", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L99-L110
train
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 code has to try to decide if the login worked or not by looking at the URL redirect and parsing the returned HTML for errors. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns ------- boolean True on success or throws an exception on failure. Raises ------ session.AuthenticationError If authentication failed session.NetworkError If a network error occurred """ # Get email and password if email is None: email = self.email else: self.email = email if password is None: password = self.__pass else: self.__pass = password # Get them from the user if email is None: email = raw_input('Email:') self.email = email if password is None: password = getpass.getpass() self.__pass = password self.__log('Attempting to authenticate: {0}'.format(self.email)) # Start session self.__session = requests.Session() self.__session.headers = { 'Referer': 'https://www.lendingclub.com/', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31' } # Set last request time to now self.last_request_time = time.time() # Send login request to LC payload = { 'login_email': email, 'login_password': password } response = self.post('/account/login.action', data=payload, redirects=False) # Get URL redirect URL and save the last part of the path as the endpoint response_url = response.url if response.status_code == 302: response_url = response.headers['location'] endpoint = response_url.split('/')[-1] # Debugging self.__log('Status code: {0}'.format(response.status_code)) self.__log('Redirected to: {0}'.format(response_url)) self.__log('Cookies: {0}'.format(str(response.cookies.keys()))) # Show query and data that the server received if 'x-echo-query' in response.headers: self.__log('Query: {0}'.format(response.headers['x-echo-query'])) if 'x-echo-data' in response.headers: self.__log('Data: {0}'.format(response.headers['x-echo-data'])) # Parse any errors from the HTML soup = BeautifulSoup(response.text, "html5lib") errors = soup.find(id='master_error-list') if errors: errors = errors.text.strip() # Remove extra spaces and newlines from error message errors = re.sub('\t+', '', errors) errors = re.sub('\s*\n+\s*', ' * ', errors) if errors == '': errors = None # Raise error if errors is not None: raise AuthenticationError(errors) # Redirected back to the login page...must be an error if endpoint == 'login.action': raise AuthenticationError('Unknown! Redirected back to the login page without an error message') return True
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 code has to try to decide if the login worked or not by looking at the URL redirect and parsing the returned HTML for errors. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns ------- boolean True on success or throws an exception on failure. Raises ------ session.AuthenticationError If authentication failed session.NetworkError If a network error occurred """ # Get email and password if email is None: email = self.email else: self.email = email if password is None: password = self.__pass else: self.__pass = password # Get them from the user if email is None: email = raw_input('Email:') self.email = email if password is None: password = getpass.getpass() self.__pass = password self.__log('Attempting to authenticate: {0}'.format(self.email)) # Start session self.__session = requests.Session() self.__session.headers = { 'Referer': 'https://www.lendingclub.com/', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.65 Safari/537.31' } # Set last request time to now self.last_request_time = time.time() # Send login request to LC payload = { 'login_email': email, 'login_password': password } response = self.post('/account/login.action', data=payload, redirects=False) # Get URL redirect URL and save the last part of the path as the endpoint response_url = response.url if response.status_code == 302: response_url = response.headers['location'] endpoint = response_url.split('/')[-1] # Debugging self.__log('Status code: {0}'.format(response.status_code)) self.__log('Redirected to: {0}'.format(response_url)) self.__log('Cookies: {0}'.format(str(response.cookies.keys()))) # Show query and data that the server received if 'x-echo-query' in response.headers: self.__log('Query: {0}'.format(response.headers['x-echo-query'])) if 'x-echo-data' in response.headers: self.__log('Data: {0}'.format(response.headers['x-echo-data'])) # Parse any errors from the HTML soup = BeautifulSoup(response.text, "html5lib") errors = soup.find(id='master_error-list') if errors: errors = errors.text.strip() # Remove extra spaces and newlines from error message errors = re.sub('\t+', '', errors) errors = re.sub('\s*\n+\s*', ' * ', errors) if errors == '': errors = None # Raise error if errors is not None: raise AuthenticationError(errors) # Redirected back to the login page...must be an error if endpoint == 'login.action': raise AuthenticationError('Unknown! Redirected back to the login page without an error message') return True
[ "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 at the URL redirect and parsing the returned HTML for errors. Parameters ---------- email : string The email of a user on Lending Club password : string The user's password, for authentication. Returns ------- boolean True on success or throws an exception on failure. Raises ------ session.AuthenticationError If authentication failed session.NetworkError If a network error occurred
[ "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", "."...
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L112-L216
train
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) status = response.status_code return 200 <= status < 400 # Returns true if the status code is greater than 200 and less than 400 except Exception: return False
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) status = response.status_code return 200 <= status < 400 # Returns true if the status code is greater than 200 and less than 400 except Exception: return False
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L218-L233
train
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 will be appended to the domain defined in :attr:`base_url`. query : dict A dictionary of query string parameters data : dict A dictionary of POST data values redirects : boolean True to follow redirects, False to return the original response from the server. Returns ------- requests.Response A `requests.Response <http://docs.python-requests.org/en/latest/api/#requests.Response>`_ object """ # Check session time self.__continue_session() try: url = self.build_url(path) method = method.upper() self.__log('{0} request to: {1}'.format(method, url)) if method == 'POST': request = self.__session.post(url, params=query, data=data, allow_redirects=redirects) elif method == 'GET': request = self.__session.get(url, params=query, data=data, allow_redirects=redirects) elif method == 'HEAD': request = self.__session.head(url, params=query, data=data, allow_redirects=redirects) elif method == 'DELETE': request = self.__session.delete(url, params=query, data=data, allow_redirects=redirects) else: raise SessionError('{0} is not a supported HTTP method'.format(method)) self.last_response = request self.__log('Status code: {0}'.format(request.status_code)) # Update session time self.last_request_time = time.time() except (RequestException, ConnectionError, TooManyRedirects, HTTPError) as e: raise NetworkError('{0} failed to: {1}'.format(method, url), e) except Timeout: raise NetworkError('{0} request timed out: {1}'.format(method, url), e) return request
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 will be appended to the domain defined in :attr:`base_url`. query : dict A dictionary of query string parameters data : dict A dictionary of POST data values redirects : boolean True to follow redirects, False to return the original response from the server. Returns ------- requests.Response A `requests.Response <http://docs.python-requests.org/en/latest/api/#requests.Response>`_ object """ # Check session time self.__continue_session() try: url = self.build_url(path) method = method.upper() self.__log('{0} request to: {1}'.format(method, url)) if method == 'POST': request = self.__session.post(url, params=query, data=data, allow_redirects=redirects) elif method == 'GET': request = self.__session.get(url, params=query, data=data, allow_redirects=redirects) elif method == 'HEAD': request = self.__session.head(url, params=query, data=data, allow_redirects=redirects) elif method == 'DELETE': request = self.__session.delete(url, params=query, data=data, allow_redirects=redirects) else: raise SessionError('{0} is not a supported HTTP method'.format(method)) self.last_response = request self.__log('Status code: {0}'.format(request.status_code)) # Update session time self.last_request_time = time.time() except (RequestException, ConnectionError, TooManyRedirects, HTTPError) as e: raise NetworkError('{0} failed to: {1}'.format(method, url), e) except Timeout: raise NetworkError('{0} request timed out: {1}'.format(method, url), e) return request
[ "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 A dictionary of query string parameters data : dict A dictionary of POST data values redirects : boolean True to follow redirects, False to return the original response from the server. Returns ------- requests.Response A `requests.Response <http://docs.python-requests.org/en/latest/api/#requests.Response>`_ object
[ "Sends", "HTTP", "request", "to", "LendingClub", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L235-L290
train
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", "()" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L292-L296
train
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", "()" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L298-L302
train
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", "()" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L304-L308
train
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'] == 'success': return True return False
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'] == 'success': return True return False
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/session.py#L316-L327
train
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 values are the same datatype assert type(to_dict[key]) is type(from_dict[key]), 'Data type for {0} is incorrect: {1}, should be {2}'.format(key, type(from_dict[key]), type(to_dict[key])) # Recursively dive into the next dictionary if type(to_dict[key]) is dict: to_dict[key] = self.__merge_values(from_dict[key], to_dict[key]) # Replace value else: to_dict[key] = from_dict[key] return to_dict
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 values are the same datatype assert type(to_dict[key]) is type(from_dict[key]), 'Data type for {0} is incorrect: {1}, should be {2}'.format(key, type(from_dict[key]), type(to_dict[key])) # Recursively dive into the next dictionary if type(to_dict[key]) is dict: to_dict[key] = self.__merge_values(from_dict[key], to_dict[key]) # Replace value else: to_dict[key] = from_dict[key] return to_dict
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L159-L179
train
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: self['grades']['All'] = False break
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: self['grades']['All'] = False break
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L197-L207
train
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_progress'] = progress
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_progress'] = progress
[ "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" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L209-L219
train
jgillick/LendingClub
lendingclub/filters.py
Filter.__normalize
def __normalize(self): """ Adjusts the values of the filters to be correct. For example, if you set grade 'B' to True, then 'All' should be set to False """ # Don't normalize if we're already normalizing or intializing if self.__normalizing is True or self.__initialized is False: return self.__normalizing = True self.__normalize_grades() self.__normalize_progress() self.__normalizing = False
python
def __normalize(self): """ Adjusts the values of the filters to be correct. For example, if you set grade 'B' to True, then 'All' should be set to False """ # Don't normalize if we're already normalizing or intializing if self.__normalizing is True or self.__initialized is False: return self.__normalizing = True self.__normalize_grades() self.__normalize_progress() self.__normalizing = False
[ "def", "__normalize", "(", "self", ")", ":", "# Don't normalize if we're already normalizing or intializing", "if", "self", ".", "__normalizing", "is", "True", "or", "self", ".", "__initialized", "is", "False", ":", "return", "self", ".", "__normalizing", "=", "True...
Adjusts the values of the filters to be correct. For example, if you set grade 'B' to True, then 'All' should be set to False
[ "Adjusts", "the", "values", "of", "the", "filters", "to", "be", "correct", ".", "For", "example", "if", "you", "set", "grade", "B", "to", "True", "then", "All", "should", "be", "set", "to", "False" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L221-L235
train
jgillick/LendingClub
lendingclub/filters.py
Filter.validate_one
def validate_one(self, loan): """ Validate a single loan result record against the filters Parameters ---------- loan : dict A single loan note record Returns ------- boolean True or raises FilterValidationError Raises ------ FilterValidationError If the loan does not match the filter criteria """ assert type(loan) is dict, 'loan parameter must be a dictionary object' # Map the loan value keys to the filter keys req = { 'loanGUID': 'loan_id', 'loanGrade': 'grade', 'loanLength': 'term', 'loanUnfundedAmount': 'progress', 'loanAmountRequested': 'progress', 'alreadyInvestedIn': 'exclude_existing', 'purpose': 'loan_purpose', } # Throw an error if the loan does not contain one of the criteria keys that this filter has for key, criteria in req.iteritems(): if criteria in self and key not in loan: raise FilterValidationError('Loan does not have a "{0}" value.'.format(key), loan, criteria) # Loan ID if 'loan_id' in self: loan_ids = str(self['loan_id']).split(',') if str(loan['loanGUID']) not in loan_ids: raise FilterValidationError('Did not meet filter criteria for loan ID. {0} does not match {1}'.format(loan['loanGUID'], self['loan_id']), loan=loan, criteria='loan ID') # Grade grade = loan['loanGrade'][0] # Extract the letter portion of the loan if 'grades' in self and self['grades']['All'] is not True: if grade not in self['grades']: raise FilterValidationError('Loan grade "{0}" is unknown'.format(grade), loan, 'grade') elif self['grades'][grade] is False: raise FilterValidationError(loan=loan, criteria='grade') # Term if 'term' in self and self['term'] is not None: if loan['loanLength'] == 36 and self['term']['Year3'] is False: raise FilterValidationError(loan=loan, criteria='loan term') elif loan['loanLength'] == 60 and self['term']['Year5'] is False: raise FilterValidationError(loan=loan, criteria='loan term') # Progress if 'funding_progress' in self: loan_progress = (1 - (loan['loanUnfundedAmount'] / loan['loanAmountRequested'])) * 100 if self['funding_progress'] > loan_progress: raise FilterValidationError(loan=loan, criteria='funding progress') # Exclude existing if 'exclude_existing' in self: if self['exclude_existing'] is True and loan['alreadyInvestedIn'] is True: raise FilterValidationError(loan=loan, criteria='exclude loans you are invested in') # Loan purpose (either an array or single value) if 'loan_purpose' in self and loan['purpose'] is not False: purpose = self['loan_purpose'] if type(purpose) is not dict: purpose = {purpose: True} if 'All' not in purpose or purpose['All'] is False: if loan['purpose'] not in purpose: raise FilterValidationError(loan=loan, criteria='loan purpose') return True
python
def validate_one(self, loan): """ Validate a single loan result record against the filters Parameters ---------- loan : dict A single loan note record Returns ------- boolean True or raises FilterValidationError Raises ------ FilterValidationError If the loan does not match the filter criteria """ assert type(loan) is dict, 'loan parameter must be a dictionary object' # Map the loan value keys to the filter keys req = { 'loanGUID': 'loan_id', 'loanGrade': 'grade', 'loanLength': 'term', 'loanUnfundedAmount': 'progress', 'loanAmountRequested': 'progress', 'alreadyInvestedIn': 'exclude_existing', 'purpose': 'loan_purpose', } # Throw an error if the loan does not contain one of the criteria keys that this filter has for key, criteria in req.iteritems(): if criteria in self and key not in loan: raise FilterValidationError('Loan does not have a "{0}" value.'.format(key), loan, criteria) # Loan ID if 'loan_id' in self: loan_ids = str(self['loan_id']).split(',') if str(loan['loanGUID']) not in loan_ids: raise FilterValidationError('Did not meet filter criteria for loan ID. {0} does not match {1}'.format(loan['loanGUID'], self['loan_id']), loan=loan, criteria='loan ID') # Grade grade = loan['loanGrade'][0] # Extract the letter portion of the loan if 'grades' in self and self['grades']['All'] is not True: if grade not in self['grades']: raise FilterValidationError('Loan grade "{0}" is unknown'.format(grade), loan, 'grade') elif self['grades'][grade] is False: raise FilterValidationError(loan=loan, criteria='grade') # Term if 'term' in self and self['term'] is not None: if loan['loanLength'] == 36 and self['term']['Year3'] is False: raise FilterValidationError(loan=loan, criteria='loan term') elif loan['loanLength'] == 60 and self['term']['Year5'] is False: raise FilterValidationError(loan=loan, criteria='loan term') # Progress if 'funding_progress' in self: loan_progress = (1 - (loan['loanUnfundedAmount'] / loan['loanAmountRequested'])) * 100 if self['funding_progress'] > loan_progress: raise FilterValidationError(loan=loan, criteria='funding progress') # Exclude existing if 'exclude_existing' in self: if self['exclude_existing'] is True and loan['alreadyInvestedIn'] is True: raise FilterValidationError(loan=loan, criteria='exclude loans you are invested in') # Loan purpose (either an array or single value) if 'loan_purpose' in self and loan['purpose'] is not False: purpose = self['loan_purpose'] if type(purpose) is not dict: purpose = {purpose: True} if 'All' not in purpose or purpose['All'] is False: if loan['purpose'] not in purpose: raise FilterValidationError(loan=loan, criteria='loan purpose') return True
[ "def", "validate_one", "(", "self", ",", "loan", ")", ":", "assert", "type", "(", "loan", ")", "is", "dict", ",", "'loan parameter must be a dictionary object'", "# Map the loan value keys to the filter keys", "req", "=", "{", "'loanGUID'", ":", "'loan_id'", ",", "'...
Validate a single loan result record against the filters Parameters ---------- loan : dict A single loan note record Returns ------- boolean True or raises FilterValidationError Raises ------ FilterValidationError If the loan does not match the filter criteria
[ "Validate", "a", "single", "loan", "result", "record", "against", "the", "filters" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L265-L344
train
jgillick/LendingClub
lendingclub/filters.py
Filter.search_string
def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """ self.__normalize() # Get the template tmpl_source = unicode(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compiler.compile(tmpl_source) out = template(self) if not out: return False out = ''.join(out) # # Cleanup output and remove all extra space # # remove extra spaces out = re.sub('\n', '', out) out = re.sub('\s{3,}', ' ', out) # Remove hanging commas i.e: [1, 2,] out = re.sub(',\s*([}\\]])', '\\1', out) # Space between brackets i.e: ], [ out = re.sub('([{\\[}\\]])(,?)\s*([{\\[}\\]])', '\\1\\2\\3', out) # Cleanup spaces around [, {, }, ], : and , characters out = re.sub('\s*([{\\[\\]}:,])\s*', '\\1', out) return out
python
def search_string(self): """" Returns the JSON string that LendingClub expects for it's search """ self.__normalize() # Get the template tmpl_source = unicode(open(self.tmpl_file).read()) # Process template compiler = Compiler() template = compiler.compile(tmpl_source) out = template(self) if not out: return False out = ''.join(out) # # Cleanup output and remove all extra space # # remove extra spaces out = re.sub('\n', '', out) out = re.sub('\s{3,}', ' ', out) # Remove hanging commas i.e: [1, 2,] out = re.sub(',\s*([}\\]])', '\\1', out) # Space between brackets i.e: ], [ out = re.sub('([{\\[}\\]])(,?)\s*([{\\[}\\]])', '\\1\\2\\3', out) # Cleanup spaces around [, {, }, ], : and , characters out = re.sub('\s*([{\\[\\]}:,])\s*', '\\1', out) return out
[ "def", "search_string", "(", "self", ")", ":", "self", ".", "__normalize", "(", ")", "# Get the template", "tmpl_source", "=", "unicode", "(", "open", "(", "self", ".", "tmpl_file", ")", ".", "read", "(", ")", ")", "# Process template", "compiler", "=", "C...
Returns the JSON string that LendingClub expects for it's search
[ "Returns", "the", "JSON", "string", "that", "LendingClub", "expects", "for", "it", "s", "search" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L346-L380
train
jgillick/LendingClub
lendingclub/filters.py
SavedFilter.all_filters
def all_filters(lc): """ Get a list of all your saved filters Parameters ---------- lc : :py:class:`lendingclub.LendingClub` An instance of the authenticated LendingClub class Returns ------- list A list of lendingclub.filters.SavedFilter objects """ filters = [] response = lc.session.get('/browse/getSavedFiltersAj.action') json_response = response.json() # Load all filters if lc.session.json_success(json_response): for saved in json_response['filters']: filters.append(SavedFilter(lc, saved['id'])) return filters
python
def all_filters(lc): """ Get a list of all your saved filters Parameters ---------- lc : :py:class:`lendingclub.LendingClub` An instance of the authenticated LendingClub class Returns ------- list A list of lendingclub.filters.SavedFilter objects """ filters = [] response = lc.session.get('/browse/getSavedFiltersAj.action') json_response = response.json() # Load all filters if lc.session.json_success(json_response): for saved in json_response['filters']: filters.append(SavedFilter(lc, saved['id'])) return filters
[ "def", "all_filters", "(", "lc", ")", ":", "filters", "=", "[", "]", "response", "=", "lc", ".", "session", ".", "get", "(", "'/browse/getSavedFiltersAj.action'", ")", "json_response", "=", "response", ".", "json", "(", ")", "# Load all filters", "if", "lc",...
Get a list of all your saved filters Parameters ---------- lc : :py:class:`lendingclub.LendingClub` An instance of the authenticated LendingClub class Returns ------- list A list of lendingclub.filters.SavedFilter objects
[ "Get", "a", "list", "of", "all", "your", "saved", "filters" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L431-L455
train
jgillick/LendingClub
lendingclub/filters.py
SavedFilter.load
def load(self): """ Load the filter from the server """ # Attempt to load the saved filter payload = { 'id': self.id } response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload) self.response = response json_response = response.json() if self.lc.session.json_success(json_response) and json_response['filterName'] != 'No filters': self.name = json_response['filterName'] # # Parse out the filter JSON string manually from the response JSON. # If the filter JSON is modified at all, or any value is out of order, # LendingClub will reject the filter and perform a wildcard search instead, # without any error. So we need to retain the filter JSON value exactly how it is given to us. # text = response.text # Cut off everything before "filter": [...] text = re.sub('\n', '', text) text = re.sub('^.*?,\s*["\']filter["\']:\s*\[(.*)', '[\\1', text) # Now loop through the string until we find the end of the filter block # This is a simple parser that keeps track of block elements, quotes and # escape characters blockTracker = [] blockChars = { '[': ']', '{': '}' } inQuote = False lastChar = None json_text = "" for char in text: json_text += char # Escape char if char == '\\': if lastChar == '\\': lastChar = '' else: lastChar = char continue # Quotes if char == "'" or char == '"': if inQuote is False: # Starting a quote block inQuote = char elif inQuote == char: # Ending a quote block inQuote = False lastChar = char continue # Start of a block if char in blockChars.keys(): blockTracker.insert(0, blockChars[char]) # End of a block, remove from block path elif len(blockTracker) > 0 and char == blockTracker[0]: blockTracker.pop(0) # No more blocks in the tracker which means we're at the end of the filter block if len(blockTracker) == 0 and lastChar is not None: break lastChar = char # Verify valid JSON try: if json_text.strip() == '': raise SavedFilterError('A saved filter could not be found for ID {0}'.format(self.id), response) json_test = json.loads(json_text) # Make sure it looks right assert type(json_test) is list, 'Expecting a list, instead received a {0}'.format(type(json_test)) assert 'm_id' in json_test[0], 'Expecting a \'m_id\' property in each filter' assert 'm_value' in json_test[0], 'Expecting a \'m_value\' property in each filter' self.json = json_test except Exception as e: raise SavedFilterError('Could not parse filter from the JSON response: {0}'.format(str(e))) self.json_text = json_text self.__analyze() else: raise SavedFilterError('A saved filter could not be found for ID {0}'.format(self.id), response)
python
def load(self): """ Load the filter from the server """ # Attempt to load the saved filter payload = { 'id': self.id } response = self.lc.session.get('/browse/getSavedFilterAj.action', query=payload) self.response = response json_response = response.json() if self.lc.session.json_success(json_response) and json_response['filterName'] != 'No filters': self.name = json_response['filterName'] # # Parse out the filter JSON string manually from the response JSON. # If the filter JSON is modified at all, or any value is out of order, # LendingClub will reject the filter and perform a wildcard search instead, # without any error. So we need to retain the filter JSON value exactly how it is given to us. # text = response.text # Cut off everything before "filter": [...] text = re.sub('\n', '', text) text = re.sub('^.*?,\s*["\']filter["\']:\s*\[(.*)', '[\\1', text) # Now loop through the string until we find the end of the filter block # This is a simple parser that keeps track of block elements, quotes and # escape characters blockTracker = [] blockChars = { '[': ']', '{': '}' } inQuote = False lastChar = None json_text = "" for char in text: json_text += char # Escape char if char == '\\': if lastChar == '\\': lastChar = '' else: lastChar = char continue # Quotes if char == "'" or char == '"': if inQuote is False: # Starting a quote block inQuote = char elif inQuote == char: # Ending a quote block inQuote = False lastChar = char continue # Start of a block if char in blockChars.keys(): blockTracker.insert(0, blockChars[char]) # End of a block, remove from block path elif len(blockTracker) > 0 and char == blockTracker[0]: blockTracker.pop(0) # No more blocks in the tracker which means we're at the end of the filter block if len(blockTracker) == 0 and lastChar is not None: break lastChar = char # Verify valid JSON try: if json_text.strip() == '': raise SavedFilterError('A saved filter could not be found for ID {0}'.format(self.id), response) json_test = json.loads(json_text) # Make sure it looks right assert type(json_test) is list, 'Expecting a list, instead received a {0}'.format(type(json_test)) assert 'm_id' in json_test[0], 'Expecting a \'m_id\' property in each filter' assert 'm_value' in json_test[0], 'Expecting a \'m_value\' property in each filter' self.json = json_test except Exception as e: raise SavedFilterError('Could not parse filter from the JSON response: {0}'.format(str(e))) self.json_text = json_text self.__analyze() else: raise SavedFilterError('A saved filter could not be found for ID {0}'.format(self.id), response)
[ "def", "load", "(", "self", ")", ":", "# Attempt to load the saved filter", "payload", "=", "{", "'id'", ":", "self", ".", "id", "}", "response", "=", "self", ".", "lc", ".", "session", ".", "get", "(", "'/browse/getSavedFilterAj.action'", ",", "query", "=",...
Load the filter from the server
[ "Load", "the", "filter", "from", "the", "server" ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L468-L561
train
jgillick/LendingClub
lendingclub/filters.py
SavedFilter.__analyze
def __analyze(self): """ Analyze the filter JSON and attempt to parse out the individual filters. """ filter_values = {} # ID to filter name mapping name_map = { 10: 'grades', 11: 'loan_purpose', 13: 'approved', 15: 'funding_progress', 38: 'exclude_existing', 39: 'term', 43: 'keyword' } if self.json is not None: filters = self.json for f in filters: if 'm_id' in f: name = f['m_id'] # Get the name to represent this filter if f['m_id'] in name_map: name = name_map[f['m_id']] # Get values if 'm_value' in f: raw_values = f['m_value'] value = {} # No value, skip it if raw_values is None: continue # Loop through multiple values if type(raw_values) is list: # A single non string value, is THE value if len(raw_values) == 1 and type(raw_values[0]['value']) not in [str, unicode]: value = raw_values[0]['value'] # Create a dict of values: name = True for val in raw_values: if type(val['value']) in [str, unicode]: value[val['value']] = True # A single value else: value = raw_values # Normalize grades array if name == 'grades': if 'All' not in value: value['All'] = False # Add filter value filter_values[name] = value dict.__setitem__(self, name, value) return filter_values
python
def __analyze(self): """ Analyze the filter JSON and attempt to parse out the individual filters. """ filter_values = {} # ID to filter name mapping name_map = { 10: 'grades', 11: 'loan_purpose', 13: 'approved', 15: 'funding_progress', 38: 'exclude_existing', 39: 'term', 43: 'keyword' } if self.json is not None: filters = self.json for f in filters: if 'm_id' in f: name = f['m_id'] # Get the name to represent this filter if f['m_id'] in name_map: name = name_map[f['m_id']] # Get values if 'm_value' in f: raw_values = f['m_value'] value = {} # No value, skip it if raw_values is None: continue # Loop through multiple values if type(raw_values) is list: # A single non string value, is THE value if len(raw_values) == 1 and type(raw_values[0]['value']) not in [str, unicode]: value = raw_values[0]['value'] # Create a dict of values: name = True for val in raw_values: if type(val['value']) in [str, unicode]: value[val['value']] = True # A single value else: value = raw_values # Normalize grades array if name == 'grades': if 'All' not in value: value['All'] = False # Add filter value filter_values[name] = value dict.__setitem__(self, name, value) return filter_values
[ "def", "__analyze", "(", "self", ")", ":", "filter_values", "=", "{", "}", "# ID to filter name mapping", "name_map", "=", "{", "10", ":", "'grades'", ",", "11", ":", "'loan_purpose'", ",", "13", ":", "'approved'", ",", "15", ":", "'funding_progress'", ",", ...
Analyze the filter JSON and attempt to parse out the individual filters.
[ "Analyze", "the", "filter", "JSON", "and", "attempt", "to", "parse", "out", "the", "individual", "filters", "." ]
4495f99fd869810f39c00e02b0f4112c6b210384
https://github.com/jgillick/LendingClub/blob/4495f99fd869810f39c00e02b0f4112c6b210384/lendingclub/filters.py#L572-L634
train
vnmabus/dcor
dcor/_dcor_internals.py
_float_copy_to_out
def _float_copy_to_out(out, origin): """ Copy origin to out and return it. If ``out`` is None, a new copy (casted to floating point) is used. If ``out`` and ``origin`` are the same, we simply return it. Otherwise we copy the values. """ if out is None: out = origin / 1 # The division forces cast to a floating point type elif out is not origin: np.copyto(out, origin) return out
python
def _float_copy_to_out(out, origin): """ Copy origin to out and return it. If ``out`` is None, a new copy (casted to floating point) is used. If ``out`` and ``origin`` are the same, we simply return it. Otherwise we copy the values. """ if out is None: out = origin / 1 # The division forces cast to a floating point type elif out is not origin: np.copyto(out, origin) return out
[ "def", "_float_copy_to_out", "(", "out", ",", "origin", ")", ":", "if", "out", "is", "None", ":", "out", "=", "origin", "/", "1", "# The division forces cast to a floating point type", "elif", "out", "is", "not", "origin", ":", "np", ".", "copyto", "(", "out...
Copy origin to out and return it. If ``out`` is None, a new copy (casted to floating point) is used. If ``out`` and ``origin`` are the same, we simply return it. Otherwise we copy the values.
[ "Copy", "origin", "to", "out", "and", "return", "it", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L40-L53
train
vnmabus/dcor
dcor/_dcor_internals.py
_double_centered_imp
def _double_centered_imp(a, out=None): """ Real implementation of :func:`double_centered`. This function is used to make parameter ``out`` keyword-only in Python 2. """ out = _float_copy_to_out(out, a) dim = np.size(a, 0) mu = np.sum(a) / (dim * dim) sum_cols = np.sum(a, 0, keepdims=True) sum_rows = np.sum(a, 1, keepdims=True) mu_cols = sum_cols / dim mu_rows = sum_rows / dim # Do one operation at a time, to improve broadcasting memory usage. out -= mu_rows out -= mu_cols out += mu return out
python
def _double_centered_imp(a, out=None): """ Real implementation of :func:`double_centered`. This function is used to make parameter ``out`` keyword-only in Python 2. """ out = _float_copy_to_out(out, a) dim = np.size(a, 0) mu = np.sum(a) / (dim * dim) sum_cols = np.sum(a, 0, keepdims=True) sum_rows = np.sum(a, 1, keepdims=True) mu_cols = sum_cols / dim mu_rows = sum_rows / dim # Do one operation at a time, to improve broadcasting memory usage. out -= mu_rows out -= mu_cols out += mu return out
[ "def", "_double_centered_imp", "(", "a", ",", "out", "=", "None", ")", ":", "out", "=", "_float_copy_to_out", "(", "out", ",", "a", ")", "dim", "=", "np", ".", "size", "(", "a", ",", "0", ")", "mu", "=", "np", ".", "sum", "(", "a", ")", "/", ...
Real implementation of :func:`double_centered`. This function is used to make parameter ``out`` keyword-only in Python 2.
[ "Real", "implementation", "of", ":", "func", ":", "double_centered", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L56-L79
train
vnmabus/dcor
dcor/_dcor_internals.py
_u_centered_imp
def _u_centered_imp(a, out=None): """ Real implementation of :func:`u_centered`. This function is used to make parameter ``out`` keyword-only in Python 2. """ out = _float_copy_to_out(out, a) dim = np.size(a, 0) u_mu = np.sum(a) / ((dim - 1) * (dim - 2)) sum_cols = np.sum(a, 0, keepdims=True) sum_rows = np.sum(a, 1, keepdims=True) u_mu_cols = np.ones((dim, 1)).dot(sum_cols / (dim - 2)) u_mu_rows = (sum_rows / (dim - 2)).dot(np.ones((1, dim))) # Do one operation at a time, to improve broadcasting memory usage. out -= u_mu_rows out -= u_mu_cols out += u_mu # The diagonal is zero out[np.eye(dim, dtype=bool)] = 0 return out
python
def _u_centered_imp(a, out=None): """ Real implementation of :func:`u_centered`. This function is used to make parameter ``out`` keyword-only in Python 2. """ out = _float_copy_to_out(out, a) dim = np.size(a, 0) u_mu = np.sum(a) / ((dim - 1) * (dim - 2)) sum_cols = np.sum(a, 0, keepdims=True) sum_rows = np.sum(a, 1, keepdims=True) u_mu_cols = np.ones((dim, 1)).dot(sum_cols / (dim - 2)) u_mu_rows = (sum_rows / (dim - 2)).dot(np.ones((1, dim))) # Do one operation at a time, to improve broadcasting memory usage. out -= u_mu_rows out -= u_mu_cols out += u_mu # The diagonal is zero out[np.eye(dim, dtype=bool)] = 0 return out
[ "def", "_u_centered_imp", "(", "a", ",", "out", "=", "None", ")", ":", "out", "=", "_float_copy_to_out", "(", "out", ",", "a", ")", "dim", "=", "np", ".", "size", "(", "a", ",", "0", ")", "u_mu", "=", "np", ".", "sum", "(", "a", ")", "/", "("...
Real implementation of :func:`u_centered`. This function is used to make parameter ``out`` keyword-only in Python 2.
[ "Real", "implementation", "of", ":", "func", ":", "u_centered", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L146-L172
train
vnmabus/dcor
dcor/_dcor_internals.py
u_product
def u_product(a, b): r""" Inner product in the Hilbert space of :math:`U`-centered distance matrices. This inner product is defined as .. math:: \frac{1}{n(n-3)} \sum_{i,j=1}^n a_{i, j} b_{i, j} Parameters ---------- a: array_like First input array to be multiplied. b: array_like Second input array to be multiplied. Returns ------- numpy scalar Inner product. See Also -------- mean_product Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> dcor.u_product(u_a, u_a) 6.0 >>> dcor.u_product(u_a, u_b) -8.0 Note that the formula is well defined as long as the matrices involved are square and have the same dimensions, even if they are not in the Hilbert space of :math:`U`-centered distance matrices >>> dcor.u_product(a, a) 132.0 Also the formula produces a division by 0 for 3x3 matrices >>> import warnings >>> b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> with warnings.catch_warnings(): ... warnings.simplefilter("ignore") ... dcor.u_product(b, b) inf """ n = np.size(a, 0) return np.sum(a * b) / (n * (n - 3))
python
def u_product(a, b): r""" Inner product in the Hilbert space of :math:`U`-centered distance matrices. This inner product is defined as .. math:: \frac{1}{n(n-3)} \sum_{i,j=1}^n a_{i, j} b_{i, j} Parameters ---------- a: array_like First input array to be multiplied. b: array_like Second input array to be multiplied. Returns ------- numpy scalar Inner product. See Also -------- mean_product Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> dcor.u_product(u_a, u_a) 6.0 >>> dcor.u_product(u_a, u_b) -8.0 Note that the formula is well defined as long as the matrices involved are square and have the same dimensions, even if they are not in the Hilbert space of :math:`U`-centered distance matrices >>> dcor.u_product(a, a) 132.0 Also the formula produces a division by 0 for 3x3 matrices >>> import warnings >>> b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> with warnings.catch_warnings(): ... warnings.simplefilter("ignore") ... dcor.u_product(b, b) inf """ n = np.size(a, 0) return np.sum(a * b) / (n * (n - 3))
[ "def", "u_product", "(", "a", ",", "b", ")", ":", "n", "=", "np", ".", "size", "(", "a", ",", "0", ")", "return", "np", ".", "sum", "(", "a", "*", "b", ")", "/", "(", "n", "*", "(", "n", "-", "3", ")", ")" ]
r""" Inner product in the Hilbert space of :math:`U`-centered distance matrices. This inner product is defined as .. math:: \frac{1}{n(n-3)} \sum_{i,j=1}^n a_{i, j} b_{i, j} Parameters ---------- a: array_like First input array to be multiplied. b: array_like Second input array to be multiplied. Returns ------- numpy scalar Inner product. See Also -------- mean_product Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> dcor.u_product(u_a, u_a) 6.0 >>> dcor.u_product(u_a, u_b) -8.0 Note that the formula is well defined as long as the matrices involved are square and have the same dimensions, even if they are not in the Hilbert space of :math:`U`-centered distance matrices >>> dcor.u_product(a, a) 132.0 Also the formula produces a division by 0 for 3x3 matrices >>> import warnings >>> b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> with warnings.catch_warnings(): ... warnings.simplefilter("ignore") ... dcor.u_product(b, b) inf
[ "r", "Inner", "product", "in", "the", "Hilbert", "space", "of", ":", "math", ":", "U", "-", "centered", "distance", "matrices", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L294-L367
train
vnmabus/dcor
dcor/_dcor_internals.py
u_projection
def u_projection(a): r""" Return the orthogonal projection function over :math:`a`. The function returned computes the orthogonal projection over :math:`a` in the Hilbert space of :math:`U`-centered distance matrices. The projection of a matrix :math:`B` over a matrix :math:`A` is defined as .. math:: \text{proj}_A(B) = \begin{cases} \frac{\langle A, B \rangle}{\langle A, A \rangle} A, & \text{if} \langle A, A \rangle \neq 0, \\ 0, & \text{if} \langle A, A \rangle = 0. \end{cases} where :math:`\langle {}\cdot{}, {}\cdot{} \rangle` is the scalar product in the Hilbert space of :math:`U`-centered distance matrices, given by the function :py:func:`u_product`. Parameters ---------- a: array_like :math:`U`-centered distance matrix. Returns ------- callable Function that receives a :math:`U`-centered distance matrix and computes its orthogonal projection over :math:`a`. See Also -------- u_complementary_projection u_centered Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> proj_a = dcor.u_projection(u_a) >>> proj_a(u_a) array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> proj_a(u_b) array([[-0. , 2.66666667, -1.33333333, -1.33333333], [ 2.66666667, -0. , -1.33333333, -1.33333333], [-1.33333333, -1.33333333, -0. , 2.66666667], [-1.33333333, -1.33333333, 2.66666667, -0. ]]) The function gives the correct result if :math:`\\langle A, A \\rangle = 0`. >>> proj_null = dcor.u_projection(np.zeros((4, 4))) >>> proj_null(u_a) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) """ c = a denominator = u_product(c, c) docstring = """ Orthogonal projection over a :math:`U`-centered distance matrix. This function was returned by :code:`u_projection`. The complete usage information is in the documentation of :code:`u_projection`. See Also -------- u_projection """ if denominator == 0: def projection(a): # noqa return np.zeros_like(c) else: def projection(a): # noqa return u_product(a, c) / denominator * c projection.__doc__ = docstring return projection
python
def u_projection(a): r""" Return the orthogonal projection function over :math:`a`. The function returned computes the orthogonal projection over :math:`a` in the Hilbert space of :math:`U`-centered distance matrices. The projection of a matrix :math:`B` over a matrix :math:`A` is defined as .. math:: \text{proj}_A(B) = \begin{cases} \frac{\langle A, B \rangle}{\langle A, A \rangle} A, & \text{if} \langle A, A \rangle \neq 0, \\ 0, & \text{if} \langle A, A \rangle = 0. \end{cases} where :math:`\langle {}\cdot{}, {}\cdot{} \rangle` is the scalar product in the Hilbert space of :math:`U`-centered distance matrices, given by the function :py:func:`u_product`. Parameters ---------- a: array_like :math:`U`-centered distance matrix. Returns ------- callable Function that receives a :math:`U`-centered distance matrix and computes its orthogonal projection over :math:`a`. See Also -------- u_complementary_projection u_centered Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> proj_a = dcor.u_projection(u_a) >>> proj_a(u_a) array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> proj_a(u_b) array([[-0. , 2.66666667, -1.33333333, -1.33333333], [ 2.66666667, -0. , -1.33333333, -1.33333333], [-1.33333333, -1.33333333, -0. , 2.66666667], [-1.33333333, -1.33333333, 2.66666667, -0. ]]) The function gives the correct result if :math:`\\langle A, A \\rangle = 0`. >>> proj_null = dcor.u_projection(np.zeros((4, 4))) >>> proj_null(u_a) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) """ c = a denominator = u_product(c, c) docstring = """ Orthogonal projection over a :math:`U`-centered distance matrix. This function was returned by :code:`u_projection`. The complete usage information is in the documentation of :code:`u_projection`. See Also -------- u_projection """ if denominator == 0: def projection(a): # noqa return np.zeros_like(c) else: def projection(a): # noqa return u_product(a, c) / denominator * c projection.__doc__ = docstring return projection
[ "def", "u_projection", "(", "a", ")", ":", "c", "=", "a", "denominator", "=", "u_product", "(", "c", ",", "c", ")", "docstring", "=", "\"\"\"\n Orthogonal projection over a :math:`U`-centered distance matrix.\n\n This function was returned by :code:`u_projection`. The com...
r""" Return the orthogonal projection function over :math:`a`. The function returned computes the orthogonal projection over :math:`a` in the Hilbert space of :math:`U`-centered distance matrices. The projection of a matrix :math:`B` over a matrix :math:`A` is defined as .. math:: \text{proj}_A(B) = \begin{cases} \frac{\langle A, B \rangle}{\langle A, A \rangle} A, & \text{if} \langle A, A \rangle \neq 0, \\ 0, & \text{if} \langle A, A \rangle = 0. \end{cases} where :math:`\langle {}\cdot{}, {}\cdot{} \rangle` is the scalar product in the Hilbert space of :math:`U`-centered distance matrices, given by the function :py:func:`u_product`. Parameters ---------- a: array_like :math:`U`-centered distance matrix. Returns ------- callable Function that receives a :math:`U`-centered distance matrix and computes its orthogonal projection over :math:`a`. See Also -------- u_complementary_projection u_centered Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> proj_a = dcor.u_projection(u_a) >>> proj_a(u_a) array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> proj_a(u_b) array([[-0. , 2.66666667, -1.33333333, -1.33333333], [ 2.66666667, -0. , -1.33333333, -1.33333333], [-1.33333333, -1.33333333, -0. , 2.66666667], [-1.33333333, -1.33333333, 2.66666667, -0. ]]) The function gives the correct result if :math:`\\langle A, A \\rangle = 0`. >>> proj_null = dcor.u_projection(np.zeros((4, 4))) >>> proj_null(u_a) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]])
[ "r", "Return", "the", "orthogonal", "projection", "function", "over", ":", "math", ":", "a", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L370-L480
train
vnmabus/dcor
dcor/_dcor_internals.py
u_complementary_projection
def u_complementary_projection(a): r""" Return the orthogonal projection function over :math:`a^{\perp}`. The function returned computes the orthogonal projection over :math:`a^{\perp}` (the complementary projection over a) in the Hilbert space of :math:`U`-centered distance matrices. The projection of a matrix :math:`B` over a matrix :math:`A^{\perp}` is defined as .. math:: \text{proj}_{A^{\perp}}(B) = B - \text{proj}_A(B) Parameters ---------- a: array_like :math:`U`-centered distance matrix. Returns ------- callable Function that receives a :math:`U`-centered distance matrices and computes its orthogonal projection over :math:`a^{\perp}`. See Also -------- u_projection u_centered Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> proj_a = dcor.u_complementary_projection(u_a) >>> proj_a(u_a) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) >>> proj_a(u_b) array([[ 0.0000000e+00, -4.4408921e-16, 4.0000000e+00, -4.0000000e+00], [-4.4408921e-16, 0.0000000e+00, -4.0000000e+00, 4.0000000e+00], [ 4.0000000e+00, -4.0000000e+00, 0.0000000e+00, -4.4408921e-16], [-4.0000000e+00, 4.0000000e+00, -4.4408921e-16, 0.0000000e+00]]) >>> proj_null = dcor.u_complementary_projection(np.zeros((4, 4))) >>> proj_null(u_a) array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) """ proj = u_projection(a) def projection(a): """ Orthogonal projection over the complementary space. This function was returned by :code:`u_complementary_projection`. The complete usage information is in the documentation of :code:`u_complementary_projection`. See Also -------- u_complementary_projection """ return a - proj(a) return projection
python
def u_complementary_projection(a): r""" Return the orthogonal projection function over :math:`a^{\perp}`. The function returned computes the orthogonal projection over :math:`a^{\perp}` (the complementary projection over a) in the Hilbert space of :math:`U`-centered distance matrices. The projection of a matrix :math:`B` over a matrix :math:`A^{\perp}` is defined as .. math:: \text{proj}_{A^{\perp}}(B) = B - \text{proj}_A(B) Parameters ---------- a: array_like :math:`U`-centered distance matrix. Returns ------- callable Function that receives a :math:`U`-centered distance matrices and computes its orthogonal projection over :math:`a^{\perp}`. See Also -------- u_projection u_centered Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> proj_a = dcor.u_complementary_projection(u_a) >>> proj_a(u_a) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) >>> proj_a(u_b) array([[ 0.0000000e+00, -4.4408921e-16, 4.0000000e+00, -4.0000000e+00], [-4.4408921e-16, 0.0000000e+00, -4.0000000e+00, 4.0000000e+00], [ 4.0000000e+00, -4.0000000e+00, 0.0000000e+00, -4.4408921e-16], [-4.0000000e+00, 4.0000000e+00, -4.4408921e-16, 0.0000000e+00]]) >>> proj_null = dcor.u_complementary_projection(np.zeros((4, 4))) >>> proj_null(u_a) array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) """ proj = u_projection(a) def projection(a): """ Orthogonal projection over the complementary space. This function was returned by :code:`u_complementary_projection`. The complete usage information is in the documentation of :code:`u_complementary_projection`. See Also -------- u_complementary_projection """ return a - proj(a) return projection
[ "def", "u_complementary_projection", "(", "a", ")", ":", "proj", "=", "u_projection", "(", "a", ")", "def", "projection", "(", "a", ")", ":", "\"\"\"\n Orthogonal projection over the complementary space.\n\n This function was returned by :code:`u_complementary_proje...
r""" Return the orthogonal projection function over :math:`a^{\perp}`. The function returned computes the orthogonal projection over :math:`a^{\perp}` (the complementary projection over a) in the Hilbert space of :math:`U`-centered distance matrices. The projection of a matrix :math:`B` over a matrix :math:`A^{\perp}` is defined as .. math:: \text{proj}_{A^{\perp}}(B) = B - \text{proj}_A(B) Parameters ---------- a: array_like :math:`U`-centered distance matrix. Returns ------- callable Function that receives a :math:`U`-centered distance matrices and computes its orthogonal projection over :math:`a^{\perp}`. See Also -------- u_projection u_centered Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[ 0., 3., 11., 6.], ... [ 3., 0., 8., 3.], ... [ 11., 8., 0., 5.], ... [ 6., 3., 5., 0.]]) >>> b = np.array([[ 0., 13., 11., 3.], ... [ 13., 0., 2., 10.], ... [ 11., 2., 0., 8.], ... [ 3., 10., 8., 0.]]) >>> u_a = dcor.u_centered(a) >>> u_a array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]]) >>> u_b = dcor.u_centered(b) >>> u_b array([[ 0. , 2.66666667, 2.66666667, -5.33333333], [ 2.66666667, 0. , -5.33333333, 2.66666667], [ 2.66666667, -5.33333333, 0. , 2.66666667], [-5.33333333, 2.66666667, 2.66666667, 0. ]]) >>> proj_a = dcor.u_complementary_projection(u_a) >>> proj_a(u_a) array([[0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.], [0., 0., 0., 0.]]) >>> proj_a(u_b) array([[ 0.0000000e+00, -4.4408921e-16, 4.0000000e+00, -4.0000000e+00], [-4.4408921e-16, 0.0000000e+00, -4.0000000e+00, 4.0000000e+00], [ 4.0000000e+00, -4.0000000e+00, 0.0000000e+00, -4.4408921e-16], [-4.0000000e+00, 4.0000000e+00, -4.4408921e-16, 0.0000000e+00]]) >>> proj_null = dcor.u_complementary_projection(np.zeros((4, 4))) >>> proj_null(u_a) array([[ 0., -2., 1., 1.], [-2., 0., 1., 1.], [ 1., 1., 0., -2.], [ 1., 1., -2., 0.]])
[ "r", "Return", "the", "orthogonal", "projection", "function", "over", ":", "math", ":", "a^", "{", "\\", "perp", "}", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L483-L573
train
vnmabus/dcor
dcor/_dcor_internals.py
_distance_matrix_generic
def _distance_matrix_generic(x, centering, exponent=1): """Compute a centered distance matrix given a matrix.""" _check_valid_dcov_exponent(exponent) x = _transform_to_2d(x) # Calculate distance matrices a = distances.pairwise_distances(x, exponent=exponent) # Double centering a = centering(a, out=a) return a
python
def _distance_matrix_generic(x, centering, exponent=1): """Compute a centered distance matrix given a matrix.""" _check_valid_dcov_exponent(exponent) x = _transform_to_2d(x) # Calculate distance matrices a = distances.pairwise_distances(x, exponent=exponent) # Double centering a = centering(a, out=a) return a
[ "def", "_distance_matrix_generic", "(", "x", ",", "centering", ",", "exponent", "=", "1", ")", ":", "_check_valid_dcov_exponent", "(", "exponent", ")", "x", "=", "_transform_to_2d", "(", "x", ")", "# Calculate distance matrices", "a", "=", "distances", ".", "pai...
Compute a centered distance matrix given a matrix.
[ "Compute", "a", "centered", "distance", "matrix", "given", "a", "matrix", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L576-L588
train
vnmabus/dcor
dcor/_dcor_internals.py
_af_inv_scaled
def _af_inv_scaled(x): """Scale a random vector for using the affinely invariant measures""" x = _transform_to_2d(x) cov_matrix = np.atleast_2d(np.cov(x, rowvar=False)) cov_matrix_power = _mat_sqrt_inv(cov_matrix) return x.dot(cov_matrix_power)
python
def _af_inv_scaled(x): """Scale a random vector for using the affinely invariant measures""" x = _transform_to_2d(x) cov_matrix = np.atleast_2d(np.cov(x, rowvar=False)) cov_matrix_power = _mat_sqrt_inv(cov_matrix) return x.dot(cov_matrix_power)
[ "def", "_af_inv_scaled", "(", "x", ")", ":", "x", "=", "_transform_to_2d", "(", "x", ")", "cov_matrix", "=", "np", ".", "atleast_2d", "(", "np", ".", "cov", "(", "x", ",", "rowvar", "=", "False", ")", ")", "cov_matrix_power", "=", "_mat_sqrt_inv", "(",...
Scale a random vector for using the affinely invariant measures
[ "Scale", "a", "random", "vector", "for", "using", "the", "affinely", "invariant", "measures" ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor_internals.py#L615-L623
train
vnmabus/dcor
dcor/_partial_dcor.py
partial_distance_covariance
def partial_distance_covariance(x, y, z): """ Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Random vector with respect to which the partial distance covariance is computed. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the partial distance covariance. See Also -------- partial_distance_correlation Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> c = np.array([[1, 3, 4], ... [5, 7, 8], ... [9, 11, 15], ... [13, 15, 16]]) >>> dcor.partial_distance_covariance(a, a, c) # doctest: +ELLIPSIS 0.0024298... >>> dcor.partial_distance_covariance(a, b, c) 0.0347030... >>> dcor.partial_distance_covariance(b, b, c) 0.4956241... """ a = _u_distance_matrix(x) b = _u_distance_matrix(y) c = _u_distance_matrix(z) proj = u_complementary_projection(c) return u_product(proj(a), proj(b))
python
def partial_distance_covariance(x, y, z): """ Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Random vector with respect to which the partial distance covariance is computed. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the partial distance covariance. See Also -------- partial_distance_correlation Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> c = np.array([[1, 3, 4], ... [5, 7, 8], ... [9, 11, 15], ... [13, 15, 16]]) >>> dcor.partial_distance_covariance(a, a, c) # doctest: +ELLIPSIS 0.0024298... >>> dcor.partial_distance_covariance(a, b, c) 0.0347030... >>> dcor.partial_distance_covariance(b, b, c) 0.4956241... """ a = _u_distance_matrix(x) b = _u_distance_matrix(y) c = _u_distance_matrix(z) proj = u_complementary_projection(c) return u_product(proj(a), proj(b))
[ "def", "partial_distance_covariance", "(", "x", ",", "y", ",", "z", ")", ":", "a", "=", "_u_distance_matrix", "(", "x", ")", "b", "=", "_u_distance_matrix", "(", "y", ")", "c", "=", "_u_distance_matrix", "(", "z", ")", "proj", "=", "u_complementary_project...
Partial distance covariance estimator. Compute the estimator for the partial distance covariance of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Random vector with respect to which the partial distance covariance is computed. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the partial distance covariance. See Also -------- partial_distance_correlation Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... [13, 14, 15, 16]]) >>> b = np.array([[1], [0], [0], [1]]) >>> c = np.array([[1, 3, 4], ... [5, 7, 8], ... [9, 11, 15], ... [13, 15, 16]]) >>> dcor.partial_distance_covariance(a, a, c) # doctest: +ELLIPSIS 0.0024298... >>> dcor.partial_distance_covariance(a, b, c) 0.0347030... >>> dcor.partial_distance_covariance(b, b, c) 0.4956241...
[ "Partial", "distance", "covariance", "estimator", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_partial_dcor.py#L13-L70
train
vnmabus/dcor
dcor/_partial_dcor.py
partial_distance_correlation
def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals """ Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Random vector with respect to which the partial distance correlation is computed. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the partial distance correlation. See Also -------- partial_distance_covariance Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1], [1], [2], [2], [3]]) >>> b = np.array([[1], [2], [1], [2], [1]]) >>> c = np.array([[1], [2], [2], [1], [2]]) >>> dcor.partial_distance_correlation(a, a, c) 1.0 >>> dcor.partial_distance_correlation(a, b, c) # doctest: +ELLIPSIS -0.5... >>> dcor.partial_distance_correlation(b, b, c) 1.0 >>> dcor.partial_distance_correlation(a, c, c) 0.0 """ a = _u_distance_matrix(x) b = _u_distance_matrix(y) c = _u_distance_matrix(z) aa = u_product(a, a) bb = u_product(b, b) cc = u_product(c, c) ab = u_product(a, b) ac = u_product(a, c) bc = u_product(b, c) denom_sqr = aa * bb r_xy = ab / _sqrt(denom_sqr) if denom_sqr != 0 else denom_sqr r_xy = np.clip(r_xy, -1, 1) denom_sqr = aa * cc r_xz = ac / _sqrt(denom_sqr) if denom_sqr != 0 else denom_sqr r_xz = np.clip(r_xz, -1, 1) denom_sqr = bb * cc r_yz = bc / _sqrt(denom_sqr) if denom_sqr != 0 else denom_sqr r_yz = np.clip(r_yz, -1, 1) denom = _sqrt(1 - r_xz ** 2) * _sqrt(1 - r_yz ** 2) return (r_xy - r_xz * r_yz) / denom if denom != 0 else denom
python
def partial_distance_correlation(x, y, z): # pylint:disable=too-many-locals """ Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Random vector with respect to which the partial distance correlation is computed. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the partial distance correlation. See Also -------- partial_distance_covariance Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1], [1], [2], [2], [3]]) >>> b = np.array([[1], [2], [1], [2], [1]]) >>> c = np.array([[1], [2], [2], [1], [2]]) >>> dcor.partial_distance_correlation(a, a, c) 1.0 >>> dcor.partial_distance_correlation(a, b, c) # doctest: +ELLIPSIS -0.5... >>> dcor.partial_distance_correlation(b, b, c) 1.0 >>> dcor.partial_distance_correlation(a, c, c) 0.0 """ a = _u_distance_matrix(x) b = _u_distance_matrix(y) c = _u_distance_matrix(z) aa = u_product(a, a) bb = u_product(b, b) cc = u_product(c, c) ab = u_product(a, b) ac = u_product(a, c) bc = u_product(b, c) denom_sqr = aa * bb r_xy = ab / _sqrt(denom_sqr) if denom_sqr != 0 else denom_sqr r_xy = np.clip(r_xy, -1, 1) denom_sqr = aa * cc r_xz = ac / _sqrt(denom_sqr) if denom_sqr != 0 else denom_sqr r_xz = np.clip(r_xz, -1, 1) denom_sqr = bb * cc r_yz = bc / _sqrt(denom_sqr) if denom_sqr != 0 else denom_sqr r_yz = np.clip(r_yz, -1, 1) denom = _sqrt(1 - r_xz ** 2) * _sqrt(1 - r_yz ** 2) return (r_xy - r_xz * r_yz) / denom if denom != 0 else denom
[ "def", "partial_distance_correlation", "(", "x", ",", "y", ",", "z", ")", ":", "# pylint:disable=too-many-locals", "a", "=", "_u_distance_matrix", "(", "x", ")", "b", "=", "_u_distance_matrix", "(", "y", ")", "c", "=", "_u_distance_matrix", "(", "z", ")", "a...
Partial distance correlation estimator. Compute the estimator for the partial distance correlation of the random vectors corresponding to :math:`x` and :math:`y` with respect to the random variable corresponding to :math:`z`. Parameters ---------- x: array_like First random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. y: array_like Second random vector. The columns correspond with the individual random variables while the rows are individual instances of the random vector. z: array_like Random vector with respect to which the partial distance correlation is computed. The columns correspond with the individual random variables while the rows are individual instances of the random vector. Returns ------- numpy scalar Value of the estimator of the partial distance correlation. See Also -------- partial_distance_covariance Examples -------- >>> import numpy as np >>> import dcor >>> a = np.array([[1], [1], [2], [2], [3]]) >>> b = np.array([[1], [2], [1], [2], [1]]) >>> c = np.array([[1], [2], [2], [1], [2]]) >>> dcor.partial_distance_correlation(a, a, c) 1.0 >>> dcor.partial_distance_correlation(a, b, c) # doctest: +ELLIPSIS -0.5... >>> dcor.partial_distance_correlation(b, b, c) 1.0 >>> dcor.partial_distance_correlation(a, c, c) 0.0
[ "Partial", "distance", "correlation", "estimator", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_partial_dcor.py#L73-L145
train
vnmabus/dcor
dcor/_energy.py
_energy_distance_from_distance_matrices
def _energy_distance_from_distance_matrices( distance_xx, distance_yy, distance_xy): """Compute energy distance with precalculated distance matrices.""" return (2 * np.mean(distance_xy) - np.mean(distance_xx) - np.mean(distance_yy))
python
def _energy_distance_from_distance_matrices( distance_xx, distance_yy, distance_xy): """Compute energy distance with precalculated distance matrices.""" return (2 * np.mean(distance_xy) - np.mean(distance_xx) - np.mean(distance_yy))
[ "def", "_energy_distance_from_distance_matrices", "(", "distance_xx", ",", "distance_yy", ",", "distance_xy", ")", ":", "return", "(", "2", "*", "np", ".", "mean", "(", "distance_xy", ")", "-", "np", ".", "mean", "(", "distance_xx", ")", "-", "np", ".", "m...
Compute energy distance with precalculated distance matrices.
[ "Compute", "energy", "distance", "with", "precalculated", "distance", "matrices", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_energy.py#L24-L28
train
vnmabus/dcor
dcor/_energy.py
_energy_distance_imp
def _energy_distance_imp(x, y, exponent=1): """ Real implementation of :func:`energy_distance`. This function is used to make parameter ``exponent`` keyword-only in Python 2. """ x = _transform_to_2d(x) y = _transform_to_2d(y) _check_valid_energy_exponent(exponent) distance_xx = distances.pairwise_distances(x, exponent=exponent) distance_yy = distances.pairwise_distances(y, exponent=exponent) distance_xy = distances.pairwise_distances(x, y, exponent=exponent) return _energy_distance_from_distance_matrices(distance_xx=distance_xx, distance_yy=distance_yy, distance_xy=distance_xy)
python
def _energy_distance_imp(x, y, exponent=1): """ Real implementation of :func:`energy_distance`. This function is used to make parameter ``exponent`` keyword-only in Python 2. """ x = _transform_to_2d(x) y = _transform_to_2d(y) _check_valid_energy_exponent(exponent) distance_xx = distances.pairwise_distances(x, exponent=exponent) distance_yy = distances.pairwise_distances(y, exponent=exponent) distance_xy = distances.pairwise_distances(x, y, exponent=exponent) return _energy_distance_from_distance_matrices(distance_xx=distance_xx, distance_yy=distance_yy, distance_xy=distance_xy)
[ "def", "_energy_distance_imp", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "x", "=", "_transform_to_2d", "(", "x", ")", "y", "=", "_transform_to_2d", "(", "y", ")", "_check_valid_energy_exponent", "(", "exponent", ")", "distance_xx", "=", "dis...
Real implementation of :func:`energy_distance`. This function is used to make parameter ``exponent`` keyword-only in Python 2.
[ "Real", "implementation", "of", ":", "func", ":", "energy_distance", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_energy.py#L31-L50
train
vnmabus/dcor
dcor/_dcor.py
_distance_covariance_sqr_naive
def _distance_covariance_sqr_naive(x, y, exponent=1): """ Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _distance_matrix(x, exponent=exponent) b = _distance_matrix(y, exponent=exponent) return mean_product(a, b)
python
def _distance_covariance_sqr_naive(x, y, exponent=1): """ Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _distance_matrix(x, exponent=exponent) b = _distance_matrix(y, exponent=exponent) return mean_product(a, b)
[ "def", "_distance_covariance_sqr_naive", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "a", "=", "_distance_matrix", "(", "x", ",", "exponent", "=", "exponent", ")", "b", "=", "_distance_matrix", "(", "y", ",", "exponent", "=", "exponent", ")"...
Naive biased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm.
[ "Naive", "biased", "estimator", "for", "distance", "covariance", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L34-L44
train
vnmabus/dcor
dcor/_dcor.py
_u_distance_covariance_sqr_naive
def _u_distance_covariance_sqr_naive(x, y, exponent=1): """ Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _u_distance_matrix(x, exponent=exponent) b = _u_distance_matrix(y, exponent=exponent) return u_product(a, b)
python
def _u_distance_covariance_sqr_naive(x, y, exponent=1): """ Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm. """ a = _u_distance_matrix(x, exponent=exponent) b = _u_distance_matrix(y, exponent=exponent) return u_product(a, b)
[ "def", "_u_distance_covariance_sqr_naive", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "a", "=", "_u_distance_matrix", "(", "x", ",", "exponent", "=", "exponent", ")", "b", "=", "_u_distance_matrix", "(", "y", ",", "exponent", "=", "exponent",...
Naive unbiased estimator for distance covariance. Computes the unbiased estimator for distance covariance between two matrices, using an :math:`O(N^2)` algorithm.
[ "Naive", "unbiased", "estimator", "for", "distance", "covariance", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L47-L57
train
vnmabus/dcor
dcor/_dcor.py
_distance_sqr_stats_naive_generic
def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product, exponent=1): """Compute generic squared stats.""" a = matrix_centered(x, exponent=exponent) b = matrix_centered(y, exponent=exponent) covariance_xy_sqr = product(a, b) variance_x_sqr = product(a, a) variance_y_sqr = product(b, b) denominator_sqr = np.absolute(variance_x_sqr * variance_y_sqr) denominator = _sqrt(denominator_sqr) # Comparisons using a tolerance can change results if the # covariance has a similar order of magnitude if denominator == 0.0: correlation_xy_sqr = 0.0 else: correlation_xy_sqr = covariance_xy_sqr / denominator return Stats(covariance_xy=covariance_xy_sqr, correlation_xy=correlation_xy_sqr, variance_x=variance_x_sqr, variance_y=variance_y_sqr)
python
def _distance_sqr_stats_naive_generic(x, y, matrix_centered, product, exponent=1): """Compute generic squared stats.""" a = matrix_centered(x, exponent=exponent) b = matrix_centered(y, exponent=exponent) covariance_xy_sqr = product(a, b) variance_x_sqr = product(a, a) variance_y_sqr = product(b, b) denominator_sqr = np.absolute(variance_x_sqr * variance_y_sqr) denominator = _sqrt(denominator_sqr) # Comparisons using a tolerance can change results if the # covariance has a similar order of magnitude if denominator == 0.0: correlation_xy_sqr = 0.0 else: correlation_xy_sqr = covariance_xy_sqr / denominator return Stats(covariance_xy=covariance_xy_sqr, correlation_xy=correlation_xy_sqr, variance_x=variance_x_sqr, variance_y=variance_y_sqr)
[ "def", "_distance_sqr_stats_naive_generic", "(", "x", ",", "y", ",", "matrix_centered", ",", "product", ",", "exponent", "=", "1", ")", ":", "a", "=", "matrix_centered", "(", "x", ",", "exponent", "=", "exponent", ")", "b", "=", "matrix_centered", "(", "y"...
Compute generic squared stats.
[ "Compute", "generic", "squared", "stats", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L60-L83
train
vnmabus/dcor
dcor/_dcor.py
_distance_correlation_sqr_naive
def _distance_correlation_sqr_naive(x, y, exponent=1): """Biased distance correlation estimator between two matrices.""" return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix, product=mean_product, exponent=exponent).correlation_xy
python
def _distance_correlation_sqr_naive(x, y, exponent=1): """Biased distance correlation estimator between two matrices.""" return _distance_sqr_stats_naive_generic( x, y, matrix_centered=_distance_matrix, product=mean_product, exponent=exponent).correlation_xy
[ "def", "_distance_correlation_sqr_naive", "(", "x", ",", "y", ",", "exponent", "=", "1", ")", ":", "return", "_distance_sqr_stats_naive_generic", "(", "x", ",", "y", ",", "matrix_centered", "=", "_distance_matrix", ",", "product", "=", "mean_product", ",", "expo...
Biased distance correlation estimator between two matrices.
[ "Biased", "distance", "correlation", "estimator", "between", "two", "matrices", "." ]
b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d
https://github.com/vnmabus/dcor/blob/b0ff1273c0a52efdabdfdadefc7ff2a49def7e8d/dcor/_dcor.py#L86-L92
train