repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
Frojd/Fabrik
fabrik/hooks.py
hook
def hook(name=None, priority=-1): """ Decorator """ def _hook(hook_func): return register_hook(name, hook_func=hook_func, priority=priority) return _hook
python
def hook(name=None, priority=-1): """ Decorator """ def _hook(hook_func): return register_hook(name, hook_func=hook_func, priority=priority) return _hook
[ "def", "hook", "(", "name", "=", "None", ",", "priority", "=", "-", "1", ")", ":", "def", "_hook", "(", "hook_func", ")", ":", "return", "register_hook", "(", "name", ",", "hook_func", "=", "hook_func", ",", "priority", "=", "priority", ")", "return", ...
Decorator
[ "Decorator" ]
train
https://github.com/Frojd/Fabrik/blob/9f2edbba97a7fd236b72a9b3010f6e912ab5c001/fabrik/hooks.py#L16-L24
frnsys/broca
broca/knowledge/doc2vec.py
train_doc2vec
def train_doc2vec(paths, out='data/model.d2v', tokenizer=word_tokenize, sentences=False, **kwargs): """ Train a doc2vec model on a list of files. """ kwargs = { 'size': 400, 'window': 8, 'min_count': 2, 'workers': 8 }.update(kwargs) n = 0 for path in paths: print('Counting lines for {0}...'.format(path)) n += sum(1 for line in open(path, 'r')) print('Processing {0} lines...'.format(n)) print('Training doc2vec model...') m = Doc2Vec(_doc2vec_doc_stream(paths, n, tokenizer=tokenizer, sentences=sentences), **kwargs) print('Saving...') m.save(out)
python
def train_doc2vec(paths, out='data/model.d2v', tokenizer=word_tokenize, sentences=False, **kwargs): """ Train a doc2vec model on a list of files. """ kwargs = { 'size': 400, 'window': 8, 'min_count': 2, 'workers': 8 }.update(kwargs) n = 0 for path in paths: print('Counting lines for {0}...'.format(path)) n += sum(1 for line in open(path, 'r')) print('Processing {0} lines...'.format(n)) print('Training doc2vec model...') m = Doc2Vec(_doc2vec_doc_stream(paths, n, tokenizer=tokenizer, sentences=sentences), **kwargs) print('Saving...') m.save(out)
[ "def", "train_doc2vec", "(", "paths", ",", "out", "=", "'data/model.d2v'", ",", "tokenizer", "=", "word_tokenize", ",", "sentences", "=", "False", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "{", "'size'", ":", "400", ",", "'window'", ":", "8", "...
Train a doc2vec model on a list of files.
[ "Train", "a", "doc2vec", "model", "on", "a", "list", "of", "files", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/doc2vec.py#L6-L27
frnsys/broca
broca/knowledge/doc2vec.py
_doc2vec_doc_stream
def _doc2vec_doc_stream(paths, n, tokenizer=word_tokenize, sentences=True): """ Generator to feed sentences to the dov2vec model. """ i = 0 p = Progress() for path in paths: with open(path, 'r') as f: for line in f: i += 1 p.print_progress(i/n) # We do minimal pre-processing here so the model can learn # punctuation line = line.lower() if sentences: for sent in sent_tokenize(line): tokens = tokenizer(sent) yield LabeledSentence(tokens, ['SENT_{}'.format(i)]) else: tokens = tokenizer(line) yield LabeledSentence(tokens, ['SENT_{}'.format(i)])
python
def _doc2vec_doc_stream(paths, n, tokenizer=word_tokenize, sentences=True): """ Generator to feed sentences to the dov2vec model. """ i = 0 p = Progress() for path in paths: with open(path, 'r') as f: for line in f: i += 1 p.print_progress(i/n) # We do minimal pre-processing here so the model can learn # punctuation line = line.lower() if sentences: for sent in sent_tokenize(line): tokens = tokenizer(sent) yield LabeledSentence(tokens, ['SENT_{}'.format(i)]) else: tokens = tokenizer(line) yield LabeledSentence(tokens, ['SENT_{}'.format(i)])
[ "def", "_doc2vec_doc_stream", "(", "paths", ",", "n", ",", "tokenizer", "=", "word_tokenize", ",", "sentences", "=", "True", ")", ":", "i", "=", "0", "p", "=", "Progress", "(", ")", "for", "path", "in", "paths", ":", "with", "open", "(", "path", ",",...
Generator to feed sentences to the dov2vec model.
[ "Generator", "to", "feed", "sentences", "to", "the", "dov2vec", "model", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/doc2vec.py#L30-L52
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.open
def open(self): """Open the device.""" self._serial.port = self._port self._serial.baudrate = self._baud self._serial.timeout = self._timeout self._serial.open() self._serial.flushInput() self._serial.flushOutput()
python
def open(self): """Open the device.""" self._serial.port = self._port self._serial.baudrate = self._baud self._serial.timeout = self._timeout self._serial.open() self._serial.flushInput() self._serial.flushOutput()
[ "def", "open", "(", "self", ")", ":", "self", ".", "_serial", ".", "port", "=", "self", ".", "_port", "self", ".", "_serial", ".", "baudrate", "=", "self", ".", "_baud", "self", ".", "_serial", ".", "timeout", "=", "self", ".", "_timeout", "self", ...
Open the device.
[ "Open", "the", "device", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L61-L68
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse._parse_info
def _parse_info(line): """ The output can be: - [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)] - [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)] """ re_info = re.compile( r'\[(?P<name>\w+).(?P<ver>.*) ' + r'\((?P<rfm1name>\w+) (\w+):(?P<rfm1freq>\d+) ' + r'(?P<rfm1mode>.*)\)\]') info = { 'name': None, 'version': None, 'rfm1name': None, 'rfm1frequency': None, 'rfm1datarate': None, 'rfm1toggleinterval': None, 'rfm1togglemask': None, } match = re_info.match(line) if match: info['name'] = match.group('name') info['version'] = match.group('ver') info['rfm1name'] = match.group('rfm1name') info['rfm1frequency'] = match.group('rfm1freq') values = match.group('rfm1mode').split(':') if values[0] == 'r': info['rfm1datarate'] = values[1] elif values[0] == 't': toggle = values[1].split('~') info['rfm1toggleinterval'] = toggle[0] info['rfm1togglemask'] = toggle[1] return info
python
def _parse_info(line): """ The output can be: - [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)] - [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)] """ re_info = re.compile( r'\[(?P<name>\w+).(?P<ver>.*) ' + r'\((?P<rfm1name>\w+) (\w+):(?P<rfm1freq>\d+) ' + r'(?P<rfm1mode>.*)\)\]') info = { 'name': None, 'version': None, 'rfm1name': None, 'rfm1frequency': None, 'rfm1datarate': None, 'rfm1toggleinterval': None, 'rfm1togglemask': None, } match = re_info.match(line) if match: info['name'] = match.group('name') info['version'] = match.group('ver') info['rfm1name'] = match.group('rfm1name') info['rfm1frequency'] = match.group('rfm1freq') values = match.group('rfm1mode').split(':') if values[0] == 'r': info['rfm1datarate'] = values[1] elif values[0] == 't': toggle = values[1].split('~') info['rfm1toggleinterval'] = toggle[0] info['rfm1togglemask'] = toggle[1] return info
[ "def", "_parse_info", "(", "line", ")", ":", "re_info", "=", "re", ".", "compile", "(", "r'\\[(?P<name>\\w+).(?P<ver>.*) '", "+", "r'\\((?P<rfm1name>\\w+) (\\w+):(?P<rfm1freq>\\d+) '", "+", "r'(?P<rfm1mode>.*)\\)\\]'", ")", "info", "=", "{", "'name'", ":", "None", ","...
The output can be: - [LaCrosseITPlusReader.10.1s (RFM12B f:0 r:17241)] - [LaCrosseITPlusReader.10.1s (RFM12B f:0 t:10~3)]
[ "The", "output", "can", "be", ":", "-", "[", "LaCrosseITPlusReader", ".", "10", ".", "1s", "(", "RFM12B", "f", ":", "0", "r", ":", "17241", ")", "]", "-", "[", "LaCrosseITPlusReader", ".", "10", ".", "1s", "(", "RFM12B", "f", ":", "0", "t", ":", ...
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L84-L118
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.get_info
def get_info(self): """Get current configuration info from 'v' command.""" re_info = re.compile(r'\[.*\]') self._write_cmd('v') while True: line = self._serial.readline() try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') match = re_info.match(line) if match: return self._parse_info(line)
python
def get_info(self): """Get current configuration info from 'v' command.""" re_info = re.compile(r'\[.*\]') self._write_cmd('v') while True: line = self._serial.readline() try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') match = re_info.match(line) if match: return self._parse_info(line)
[ "def", "get_info", "(", "self", ")", ":", "re_info", "=", "re", ".", "compile", "(", "r'\\[.*\\]'", ")", "self", ".", "_write_cmd", "(", "'v'", ")", "while", "True", ":", "line", "=", "self", ".", "_serial", ".", "readline", "(", ")", "try", ":", "...
Get current configuration info from 'v' command.
[ "Get", "current", "configuration", "info", "from", "v", "command", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L120-L134
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.set_frequency
def set_frequency(self, frequency, rfm=1): """Set frequency in kHz. The frequency can be set in 5kHz steps. """ cmds = {1: 'f', 2: 'F'} self._write_cmd('{}{}'.format(frequency, cmds[rfm]))
python
def set_frequency(self, frequency, rfm=1): """Set frequency in kHz. The frequency can be set in 5kHz steps. """ cmds = {1: 'f', 2: 'F'} self._write_cmd('{}{}'.format(frequency, cmds[rfm]))
[ "def", "set_frequency", "(", "self", ",", "frequency", ",", "rfm", "=", "1", ")", ":", "cmds", "=", "{", "1", ":", "'f'", ",", "2", ":", "'F'", "}", "self", ".", "_write_cmd", "(", "'{}{}'", ".", "format", "(", "frequency", ",", "cmds", "[", "rfm...
Set frequency in kHz. The frequency can be set in 5kHz steps.
[ "Set", "frequency", "in", "kHz", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L143-L149
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.set_datarate
def set_datarate(self, rate, rfm=1): """Set datarate (baudrate).""" cmds = {1: 'r', 2: 'R'} self._write_cmd('{}{}'.format(rate, cmds[rfm]))
python
def set_datarate(self, rate, rfm=1): """Set datarate (baudrate).""" cmds = {1: 'r', 2: 'R'} self._write_cmd('{}{}'.format(rate, cmds[rfm]))
[ "def", "set_datarate", "(", "self", ",", "rate", ",", "rfm", "=", "1", ")", ":", "cmds", "=", "{", "1", ":", "'r'", ",", "2", ":", "'R'", "}", "self", ".", "_write_cmd", "(", "'{}{}'", ".", "format", "(", "rate", ",", "cmds", "[", "rfm", "]", ...
Set datarate (baudrate).
[ "Set", "datarate", "(", "baudrate", ")", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L151-L154
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.set_toggle_interval
def set_toggle_interval(self, interval, rfm=1): """Set the toggle interval.""" cmds = {1: 't', 2: 'T'} self._write_cmd('{}{}'.format(interval, cmds[rfm]))
python
def set_toggle_interval(self, interval, rfm=1): """Set the toggle interval.""" cmds = {1: 't', 2: 'T'} self._write_cmd('{}{}'.format(interval, cmds[rfm]))
[ "def", "set_toggle_interval", "(", "self", ",", "interval", ",", "rfm", "=", "1", ")", ":", "cmds", "=", "{", "1", ":", "'t'", ",", "2", ":", "'T'", "}", "self", ".", "_write_cmd", "(", "'{}{}'", ".", "format", "(", "interval", ",", "cmds", "[", ...
Set the toggle interval.
[ "Set", "the", "toggle", "interval", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L156-L159
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.set_toggle_mask
def set_toggle_mask(self, mode_mask, rfm=1): """Set toggle baudrate mask. The baudrate mask values are: 1: 17.241 kbps 2 : 9.579 kbps 4 : 8.842 kbps These values can be or'ed. """ cmds = {1: 'm', 2: 'M'} self._write_cmd('{}{}'.format(mode_mask, cmds[rfm]))
python
def set_toggle_mask(self, mode_mask, rfm=1): """Set toggle baudrate mask. The baudrate mask values are: 1: 17.241 kbps 2 : 9.579 kbps 4 : 8.842 kbps These values can be or'ed. """ cmds = {1: 'm', 2: 'M'} self._write_cmd('{}{}'.format(mode_mask, cmds[rfm]))
[ "def", "set_toggle_mask", "(", "self", ",", "mode_mask", ",", "rfm", "=", "1", ")", ":", "cmds", "=", "{", "1", ":", "'m'", ",", "2", ":", "'M'", "}", "self", ".", "_write_cmd", "(", "'{}{}'", ".", "format", "(", "mode_mask", ",", "cmds", "[", "r...
Set toggle baudrate mask. The baudrate mask values are: 1: 17.241 kbps 2 : 9.579 kbps 4 : 8.842 kbps These values can be or'ed.
[ "Set", "toggle", "baudrate", "mask", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L161-L171
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse._refresh
def _refresh(self): """Background refreshing thread.""" while not self._stopevent.isSet(): line = self._serial.readline() #this is for python2/python3 compatibility. Is there a better way? try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') if LaCrosseSensor.re_reading.match(line): sensor = LaCrosseSensor(line) self.sensors[sensor.sensorid] = sensor if self._callback: self._callback(sensor, self._callback_data) if sensor.sensorid in self._registry: for cbs in self._registry[sensor.sensorid]: cbs[0](sensor, cbs[1])
python
def _refresh(self): """Background refreshing thread.""" while not self._stopevent.isSet(): line = self._serial.readline() #this is for python2/python3 compatibility. Is there a better way? try: line = line.encode().decode('utf-8') except AttributeError: line = line.decode('utf-8') if LaCrosseSensor.re_reading.match(line): sensor = LaCrosseSensor(line) self.sensors[sensor.sensorid] = sensor if self._callback: self._callback(sensor, self._callback_data) if sensor.sensorid in self._registry: for cbs in self._registry[sensor.sensorid]: cbs[0](sensor, cbs[1])
[ "def", "_refresh", "(", "self", ")", ":", "while", "not", "self", ".", "_stopevent", ".", "isSet", "(", ")", ":", "line", "=", "self", ".", "_serial", ".", "readline", "(", ")", "#this is for python2/python3 compatibility. Is there a better way?", "try", ":", ...
Background refreshing thread.
[ "Background", "refreshing", "thread", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L187-L207
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.register_callback
def register_callback(self, sensorid, callback, user_data=None): """Register a callback for the specified sensor id.""" if sensorid not in self._registry: self._registry[sensorid] = list() self._registry[sensorid].append((callback, user_data))
python
def register_callback(self, sensorid, callback, user_data=None): """Register a callback for the specified sensor id.""" if sensorid not in self._registry: self._registry[sensorid] = list() self._registry[sensorid].append((callback, user_data))
[ "def", "register_callback", "(", "self", ",", "sensorid", ",", "callback", ",", "user_data", "=", "None", ")", ":", "if", "sensorid", "not", "in", "self", ".", "_registry", ":", "self", ".", "_registry", "[", "sensorid", "]", "=", "list", "(", ")", "se...
Register a callback for the specified sensor id.
[ "Register", "a", "callback", "for", "the", "specified", "sensor", "id", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L209-L213
hthiery/python-lacrosse
pylacrosse/lacrosse.py
LaCrosse.register_all
def register_all(self, callback, user_data=None): """Register a callback for all sensors.""" self._callback = callback self._callback_data = user_data
python
def register_all(self, callback, user_data=None): """Register a callback for all sensors.""" self._callback = callback self._callback_data = user_data
[ "def", "register_all", "(", "self", ",", "callback", ",", "user_data", "=", "None", ")", ":", "self", ".", "_callback", "=", "callback", "self", ".", "_callback_data", "=", "user_data" ]
Register a callback for all sensors.
[ "Register", "a", "callback", "for", "all", "sensors", "." ]
train
https://github.com/hthiery/python-lacrosse/blob/d588e68f12b3343e736ff986e5f994777b122fda/pylacrosse/lacrosse.py#L215-L218
apetrynet/pyfilemail
pyfilemail/transfer.py
not_completed
def not_completed(f): """Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in """ @wraps(f) def check_if_complete(cls, *args, **kwargs): if cls.is_complete: raise FMBaseError('Transfer already completed.') return f(cls, *args, **kwargs) return check_if_complete
python
def not_completed(f): """Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in """ @wraps(f) def check_if_complete(cls, *args, **kwargs): if cls.is_complete: raise FMBaseError('Transfer already completed.') return f(cls, *args, **kwargs) return check_if_complete
[ "def", "not_completed", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "check_if_complete", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "cls", ".", "is_complete", ":", "raise", "FMBaseError", "(", "'Transfer already ...
Decorator function to check if user is loged in. :raises: :class:`FMBaseError` if not logged in
[ "Decorator", "function", "to", "check", "if", "user", "is", "loged", "in", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L20-L33
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer._initialize
def _initialize(self): """Initialize transfer.""" payload = { 'apikey': self.session.cookies.get('apikey'), 'source': self.session.cookies.get('source') } if self.fm_user.logged_in: payload['logintoken'] = self.session.cookies.get('logintoken') payload.update(self.transfer_info) method, url = get_URL('init') res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: for key in ['transferid', 'transferkey', 'transferurl']: self.transfer_info[key] = res.json().get(key) else: hellraiser(res)
python
def _initialize(self): """Initialize transfer.""" payload = { 'apikey': self.session.cookies.get('apikey'), 'source': self.session.cookies.get('source') } if self.fm_user.logged_in: payload['logintoken'] = self.session.cookies.get('logintoken') payload.update(self.transfer_info) method, url = get_URL('init') res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: for key in ['transferid', 'transferkey', 'transferurl']: self.transfer_info[key] = res.json().get(key) else: hellraiser(res)
[ "def", "_initialize", "(", "self", ")", ":", "payload", "=", "{", "'apikey'", ":", "self", ".", "session", ".", "cookies", ".", "get", "(", "'apikey'", ")", ",", "'source'", ":", "self", ".", "session", ".", "cookies", ".", "get", "(", "'source'", ")...
Initialize transfer.
[ "Initialize", "transfer", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L111-L133
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer._parse_recipients
def _parse_recipients(self, to): """Make sure we have a "," separated list of recipients :param to: Recipient(s) :type to: (str, list, :class:`pyfilemail.Contact`, :class:`pyfilemail.Group` ) :rtype: ``str`` """ if to is None: return None if isinstance(to, list): recipients = [] for recipient in to: if isinstance(recipient, dict): if 'contactgroupname' in recipient: recipients.append(recipient['contactgroupname']) else: recipients.append(recipient.get('email')) else: recipients.append(recipient) elif isinstance(to, basestring): if ',' in to: recipients = to.strip().split(',') else: recipients = [to] return ', '.join(recipients)
python
def _parse_recipients(self, to): """Make sure we have a "," separated list of recipients :param to: Recipient(s) :type to: (str, list, :class:`pyfilemail.Contact`, :class:`pyfilemail.Group` ) :rtype: ``str`` """ if to is None: return None if isinstance(to, list): recipients = [] for recipient in to: if isinstance(recipient, dict): if 'contactgroupname' in recipient: recipients.append(recipient['contactgroupname']) else: recipients.append(recipient.get('email')) else: recipients.append(recipient) elif isinstance(to, basestring): if ',' in to: recipients = to.strip().split(',') else: recipients = [to] return ', '.join(recipients)
[ "def", "_parse_recipients", "(", "self", ",", "to", ")", ":", "if", "to", "is", "None", ":", "return", "None", "if", "isinstance", "(", "to", ",", "list", ")", ":", "recipients", "=", "[", "]", "for", "recipient", "in", "to", ":", "if", "isinstance",...
Make sure we have a "," separated list of recipients :param to: Recipient(s) :type to: (str, list, :class:`pyfilemail.Contact`, :class:`pyfilemail.Group` ) :rtype: ``str``
[ "Make", "sure", "we", "have", "a", "separated", "list", "of", "recipients" ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L143-L179
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.add_files
def add_files(self, files): """Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list """ if isinstance(files, basestring): files = [files] zip_file = None if self.zip_: zip_filename = self._get_zip_filename() zip_file = ZipFile(zip_filename, 'w') for filename in files: if os.path.isdir(filename): for dirname, subdirs, filelist in os.walk(filename): if dirname: if self.zip_: zip_file.write(dirname) for fname in filelist: filepath = os.path.join(dirname, fname) if self.zip_: zip_file.write(filepath) else: fmfile = self.get_file_specs(filepath, keep_folders=True) if fmfile['totalsize'] > 0: self._files.append(fmfile) else: if self.zip_: zip_file.write(filename) else: fmfile = self.get_file_specs(filename) self._files.append(fmfile) if self.zip_: zip_file.close() filename = zip_filename fmfile = self.get_file_specs(filename) self._files.append(fmfile)
python
def add_files(self, files): """Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list """ if isinstance(files, basestring): files = [files] zip_file = None if self.zip_: zip_filename = self._get_zip_filename() zip_file = ZipFile(zip_filename, 'w') for filename in files: if os.path.isdir(filename): for dirname, subdirs, filelist in os.walk(filename): if dirname: if self.zip_: zip_file.write(dirname) for fname in filelist: filepath = os.path.join(dirname, fname) if self.zip_: zip_file.write(filepath) else: fmfile = self.get_file_specs(filepath, keep_folders=True) if fmfile['totalsize'] > 0: self._files.append(fmfile) else: if self.zip_: zip_file.write(filename) else: fmfile = self.get_file_specs(filename) self._files.append(fmfile) if self.zip_: zip_file.close() filename = zip_filename fmfile = self.get_file_specs(filename) self._files.append(fmfile)
[ "def", "add_files", "(", "self", ",", "files", ")", ":", "if", "isinstance", "(", "files", ",", "basestring", ")", ":", "files", "=", "[", "files", "]", "zip_file", "=", "None", "if", "self", ".", "zip_", ":", "zip_filename", "=", "self", ".", "_get_...
Add files and/or folders to transfer. If :class:`Transfer.compress` attribute is set to ``True``, files will get packed into a zip file before sending. :param files: Files or folders to send :type files: str, list
[ "Add", "files", "and", "/", "or", "folders", "to", "transfer", ".", "If", ":", "class", ":", "Transfer", ".", "compress", "attribute", "is", "set", "to", "True", "files", "will", "get", "packed", "into", "a", "zip", "file", "before", "sending", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L181-L228
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.get_file_specs
def get_file_specs(self, filepath, keep_folders=False): """Gather information on files needed for valid transfer. :param filepath: Path to file in question :param keep_folders: Whether or not to maintain folder structure :type keep_folders: bool :type filepath: str, unicode :rtype: ``dict`` """ path, filename = os.path.split(filepath) fileid = str(uuid4()).replace('-', '') if self.checksum: with open(filepath, 'rb') as f: md5hash = md5(f.read()).digest().encode('base64')[:-1] else: md5hash = None specs = { 'transferid': self.transfer_id, 'transferkey': self.transfer_info['transferkey'], 'fileid': fileid, 'filepath': filepath, 'thefilename': keep_folders and filepath or filename, 'totalsize': os.path.getsize(filepath), 'md5': md5hash, 'content-type': guess_type(filepath)[0] } return specs
python
def get_file_specs(self, filepath, keep_folders=False): """Gather information on files needed for valid transfer. :param filepath: Path to file in question :param keep_folders: Whether or not to maintain folder structure :type keep_folders: bool :type filepath: str, unicode :rtype: ``dict`` """ path, filename = os.path.split(filepath) fileid = str(uuid4()).replace('-', '') if self.checksum: with open(filepath, 'rb') as f: md5hash = md5(f.read()).digest().encode('base64')[:-1] else: md5hash = None specs = { 'transferid': self.transfer_id, 'transferkey': self.transfer_info['transferkey'], 'fileid': fileid, 'filepath': filepath, 'thefilename': keep_folders and filepath or filename, 'totalsize': os.path.getsize(filepath), 'md5': md5hash, 'content-type': guess_type(filepath)[0] } return specs
[ "def", "get_file_specs", "(", "self", ",", "filepath", ",", "keep_folders", "=", "False", ")", ":", "path", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "filepath", ")", "fileid", "=", "str", "(", "uuid4", "(", ")", ")", ".", "replace"...
Gather information on files needed for valid transfer. :param filepath: Path to file in question :param keep_folders: Whether or not to maintain folder structure :type keep_folders: bool :type filepath: str, unicode :rtype: ``dict``
[ "Gather", "information", "on", "files", "needed", "for", "valid", "transfer", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L239-L270
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.get_files
def get_files(self): """Get information on file in transfer from Filemail. :rtype: ``list`` of ``dict`` objects with info on files """ method, url = get_URL('get') payload = { 'apikey': self.session.cookies.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: transfer_data = res.json()['transfer'] files = transfer_data['files'] for file_data in files: self._files.append(file_data) return self.files hellraiser(res)
python
def get_files(self): """Get information on file in transfer from Filemail. :rtype: ``list`` of ``dict`` objects with info on files """ method, url = get_URL('get') payload = { 'apikey': self.session.cookies.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: transfer_data = res.json()['transfer'] files = transfer_data['files'] for file_data in files: self._files.append(file_data) return self.files hellraiser(res)
[ "def", "get_files", "(", "self", ")", ":", "method", ",", "url", "=", "get_URL", "(", "'get'", ")", "payload", "=", "{", "'apikey'", ":", "self", ".", "session", ".", "cookies", ".", "get", "(", "'apikey'", ")", ",", "'logintoken'", ":", "self", ".",...
Get information on file in transfer from Filemail. :rtype: ``list`` of ``dict`` objects with info on files
[ "Get", "information", "on", "file", "in", "transfer", "from", "Filemail", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L272-L296
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer._get_zip_filename
def _get_zip_filename(self): """Create a filename for zip file when :class:Transfer.compress is set to ``True`` :rtype: str """ date = datetime.datetime.now().strftime('%Y_%m_%d-%H%M%S') zip_file = 'filemail_transfer_{date}.zip'.format(date=date) return zip_file
python
def _get_zip_filename(self): """Create a filename for zip file when :class:Transfer.compress is set to ``True`` :rtype: str """ date = datetime.datetime.now().strftime('%Y_%m_%d-%H%M%S') zip_file = 'filemail_transfer_{date}.zip'.format(date=date) return zip_file
[ "def", "_get_zip_filename", "(", "self", ")", ":", "date", "=", "datetime", ".", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y_%m_%d-%H%M%S'", ")", "zip_file", "=", "'filemail_transfer_{date}.zip'", ".", "format", "(", "date", "=", "date", ")"...
Create a filename for zip file when :class:Transfer.compress is set to ``True`` :rtype: str
[ "Create", "a", "filename", "for", "zip", "file", "when", ":", "class", ":", "Transfer", ".", "compress", "is", "set", "to", "True" ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L298-L308
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.send
def send(self, auto_complete=True, callback=None): """Begin uploading file(s) and sending email(s). If `auto_complete` is set to ``False`` you will have to call the :func:`Transfer.complete` function at a later stage. :param auto_complete: Whether or not to mark transfer as complete and send emails to recipient(s) :param callback: Callback function which will receive total file size and bytes read as arguments :type auto_complete: ``bool`` :type callback: ``func`` """ tot = len(self.files) url = self.transfer_info['transferurl'] for index, fmfile in enumerate(self.files): msg = 'Uploading: "{filename}" ({cur}/{tot})' logger.debug( msg.format( filename=fmfile['thefilename'], cur=index + 1, tot=tot) ) with open(fmfile['filepath'], 'rb') as file_obj: fields = { fmfile['thefilename']: ( 'filename', file_obj, fmfile['content-type'] ) } def pg_callback(monitor): if pm.COMMANDLINE: bar.show(monitor.bytes_read) elif callback is not None: callback(fmfile['totalsize'], monitor.bytes_read) m_encoder = encoder.MultipartEncoder(fields=fields) monitor = encoder.MultipartEncoderMonitor(m_encoder, pg_callback ) label = fmfile['thefilename'] + ': ' if pm.COMMANDLINE: bar = ProgressBar(label=label, expected_size=fmfile['totalsize']) headers = {'Content-Type': m_encoder.content_type} res = self.session.post(url, params=fmfile, data=monitor, headers=headers) if res.status_code != 200: hellraiser(res) #logger.info('\r') if auto_complete: return self.complete() return res
python
def send(self, auto_complete=True, callback=None): """Begin uploading file(s) and sending email(s). If `auto_complete` is set to ``False`` you will have to call the :func:`Transfer.complete` function at a later stage. :param auto_complete: Whether or not to mark transfer as complete and send emails to recipient(s) :param callback: Callback function which will receive total file size and bytes read as arguments :type auto_complete: ``bool`` :type callback: ``func`` """ tot = len(self.files) url = self.transfer_info['transferurl'] for index, fmfile in enumerate(self.files): msg = 'Uploading: "{filename}" ({cur}/{tot})' logger.debug( msg.format( filename=fmfile['thefilename'], cur=index + 1, tot=tot) ) with open(fmfile['filepath'], 'rb') as file_obj: fields = { fmfile['thefilename']: ( 'filename', file_obj, fmfile['content-type'] ) } def pg_callback(monitor): if pm.COMMANDLINE: bar.show(monitor.bytes_read) elif callback is not None: callback(fmfile['totalsize'], monitor.bytes_read) m_encoder = encoder.MultipartEncoder(fields=fields) monitor = encoder.MultipartEncoderMonitor(m_encoder, pg_callback ) label = fmfile['thefilename'] + ': ' if pm.COMMANDLINE: bar = ProgressBar(label=label, expected_size=fmfile['totalsize']) headers = {'Content-Type': m_encoder.content_type} res = self.session.post(url, params=fmfile, data=monitor, headers=headers) if res.status_code != 200: hellraiser(res) #logger.info('\r') if auto_complete: return self.complete() return res
[ "def", "send", "(", "self", ",", "auto_complete", "=", "True", ",", "callback", "=", "None", ")", ":", "tot", "=", "len", "(", "self", ".", "files", ")", "url", "=", "self", ".", "transfer_info", "[", "'transferurl'", "]", "for", "index", ",", "fmfil...
Begin uploading file(s) and sending email(s). If `auto_complete` is set to ``False`` you will have to call the :func:`Transfer.complete` function at a later stage. :param auto_complete: Whether or not to mark transfer as complete and send emails to recipient(s) :param callback: Callback function which will receive total file size and bytes read as arguments :type auto_complete: ``bool`` :type callback: ``func``
[ "Begin", "uploading", "file", "(", "s", ")", "and", "sending", "email", "(", "s", ")", ".", "If", "auto_complete", "is", "set", "to", "False", "you", "will", "have", "to", "call", "the", ":", "func", ":", "Transfer", ".", "complete", "function", "at", ...
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L311-L377
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.is_complete
def is_complete(self): """:rtype: ``bool`` ``True`` if transfer is complete""" if 'status' in self.transfer_info: self._complete = self.transfer_info['status'] == 'STATUS_COMPLETE' return self._complete
python
def is_complete(self): """:rtype: ``bool`` ``True`` if transfer is complete""" if 'status' in self.transfer_info: self._complete = self.transfer_info['status'] == 'STATUS_COMPLETE' return self._complete
[ "def", "is_complete", "(", "self", ")", ":", "if", "'status'", "in", "self", ".", "transfer_info", ":", "self", ".", "_complete", "=", "self", ".", "transfer_info", "[", "'status'", "]", "==", "'STATUS_COMPLETE'", "return", "self", ".", "_complete" ]
:rtype: ``bool`` ``True`` if transfer is complete
[ ":", "rtype", ":", "bool", "True", "if", "transfer", "is", "complete" ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L400-L406
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.forward
def forward(self, to): """Forward prior transfer to new recipient(s). :param to: new recipients to a previous transfer. Use ``list`` or comma seperatde ``str`` or ``unicode`` list :type to: ``list`` or ``str`` or ``unicode`` :rtype: ``bool`` """ method, url = get_URL('forward') payload = { 'apikey': self.session.cookies.get('apikey'), 'transferid': self.transfer_id, 'transferkey': self.transfer_info.get('transferkey'), 'to': self._parse_recipients(to) } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: return True hellraiser(res)
python
def forward(self, to): """Forward prior transfer to new recipient(s). :param to: new recipients to a previous transfer. Use ``list`` or comma seperatde ``str`` or ``unicode`` list :type to: ``list`` or ``str`` or ``unicode`` :rtype: ``bool`` """ method, url = get_URL('forward') payload = { 'apikey': self.session.cookies.get('apikey'), 'transferid': self.transfer_id, 'transferkey': self.transfer_info.get('transferkey'), 'to': self._parse_recipients(to) } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: return True hellraiser(res)
[ "def", "forward", "(", "self", ",", "to", ")", ":", "method", ",", "url", "=", "get_URL", "(", "'forward'", ")", "payload", "=", "{", "'apikey'", ":", "self", ".", "session", ".", "cookies", ".", "get", "(", "'apikey'", ")", ",", "'transferid'", ":",...
Forward prior transfer to new recipient(s). :param to: new recipients to a previous transfer. Use ``list`` or comma seperatde ``str`` or ``unicode`` list :type to: ``list`` or ``str`` or ``unicode`` :rtype: ``bool``
[ "Forward", "prior", "transfer", "to", "new", "recipient", "(", "s", ")", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L421-L445
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.share
def share(self, to, sender=None, message=None): """Share transfer with new message to new people. :param to: receiver(s) :param sender: Alternate email address as sender :param message: Meggase to new recipients :type to: ``list`` or ``str`` or ``unicode`` :type sender: ``str`` or ``unicode`` :type message: ``str`` or ``unicode`` :rtyep: ``bool`` """ method, url = get_URL('share') payload = { 'apikey': self.session.cookies.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, 'to': self._parse_recipients(to), 'from': sender or self.fm_user.username, 'message': message or '' } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: return True hellraiser(res)
python
def share(self, to, sender=None, message=None): """Share transfer with new message to new people. :param to: receiver(s) :param sender: Alternate email address as sender :param message: Meggase to new recipients :type to: ``list`` or ``str`` or ``unicode`` :type sender: ``str`` or ``unicode`` :type message: ``str`` or ``unicode`` :rtyep: ``bool`` """ method, url = get_URL('share') payload = { 'apikey': self.session.cookies.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, 'to': self._parse_recipients(to), 'from': sender or self.fm_user.username, 'message': message or '' } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: return True hellraiser(res)
[ "def", "share", "(", "self", ",", "to", ",", "sender", "=", "None", ",", "message", "=", "None", ")", ":", "method", ",", "url", "=", "get_URL", "(", "'share'", ")", "payload", "=", "{", "'apikey'", ":", "self", ".", "session", ".", "cookies", ".",...
Share transfer with new message to new people. :param to: receiver(s) :param sender: Alternate email address as sender :param message: Meggase to new recipients :type to: ``list`` or ``str`` or ``unicode`` :type sender: ``str`` or ``unicode`` :type message: ``str`` or ``unicode`` :rtyep: ``bool``
[ "Share", "transfer", "with", "new", "message", "to", "new", "people", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L448-L476
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.cancel
def cancel(self): """Cancel the current transfer. :rtype: ``bool`` """ method, url = get_URL('cancel') payload = { 'apikey': self.config.get('apikey'), 'transferid': self.transfer_id, 'transferkey': self.transfer_info.get('transferkey') } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: self._complete = True return True hellraiser(res)
python
def cancel(self): """Cancel the current transfer. :rtype: ``bool`` """ method, url = get_URL('cancel') payload = { 'apikey': self.config.get('apikey'), 'transferid': self.transfer_id, 'transferkey': self.transfer_info.get('transferkey') } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: self._complete = True return True hellraiser(res)
[ "def", "cancel", "(", "self", ")", ":", "method", ",", "url", "=", "get_URL", "(", "'cancel'", ")", "payload", "=", "{", "'apikey'", ":", "self", ".", "config", ".", "get", "(", "'apikey'", ")", ",", "'transferid'", ":", "self", ".", "transfer_id", "...
Cancel the current transfer. :rtype: ``bool``
[ "Cancel", "the", "current", "transfer", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L478-L498
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.rename_file
def rename_file(self, fmfile, newname): """Rename file in transfer. :param fmfile: file data from filemail containing fileid :param newname: new file name :type fmfile: ``dict`` :type newname: ``str`` or ``unicode`` :rtype: ``bool`` """ if not isinstance(fmfile, dict): raise FMBaseError('fmfile must be a <dict>') method, url = get_URL('file_rename') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'fileid': fmfile.get('fileid'), 'filename': newname } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: self._complete = True return True hellraiser(res)
python
def rename_file(self, fmfile, newname): """Rename file in transfer. :param fmfile: file data from filemail containing fileid :param newname: new file name :type fmfile: ``dict`` :type newname: ``str`` or ``unicode`` :rtype: ``bool`` """ if not isinstance(fmfile, dict): raise FMBaseError('fmfile must be a <dict>') method, url = get_URL('file_rename') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'fileid': fmfile.get('fileid'), 'filename': newname } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: self._complete = True return True hellraiser(res)
[ "def", "rename_file", "(", "self", ",", "fmfile", ",", "newname", ")", ":", "if", "not", "isinstance", "(", "fmfile", ",", "dict", ")", ":", "raise", "FMBaseError", "(", "'fmfile must be a <dict>'", ")", "method", ",", "url", "=", "get_URL", "(", "'file_re...
Rename file in transfer. :param fmfile: file data from filemail containing fileid :param newname: new file name :type fmfile: ``dict`` :type newname: ``str`` or ``unicode`` :rtype: ``bool``
[ "Rename", "file", "in", "transfer", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L523-L550
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.delete_file
def delete_file(self, fmfile): """Delete file from transfer. :param fmfile: file data from filemail containing fileid :type fmfile: ``dict`` :rtype: ``bool`` """ if not isinstance(fmfile, dict): raise FMFileError('fmfile must be a <dict>') method, url = get_URL('file_delete') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'fileid': fmfile.get('fileid') } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: self._complete = True return True hellraiser(res)
python
def delete_file(self, fmfile): """Delete file from transfer. :param fmfile: file data from filemail containing fileid :type fmfile: ``dict`` :rtype: ``bool`` """ if not isinstance(fmfile, dict): raise FMFileError('fmfile must be a <dict>') method, url = get_URL('file_delete') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'fileid': fmfile.get('fileid') } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: self._complete = True return True hellraiser(res)
[ "def", "delete_file", "(", "self", ",", "fmfile", ")", ":", "if", "not", "isinstance", "(", "fmfile", ",", "dict", ")", ":", "raise", "FMFileError", "(", "'fmfile must be a <dict>'", ")", "method", ",", "url", "=", "get_URL", "(", "'file_delete'", ")", "pa...
Delete file from transfer. :param fmfile: file data from filemail containing fileid :type fmfile: ``dict`` :rtype: ``bool``
[ "Delete", "file", "from", "transfer", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L553-L578
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.update
def update(self, message=None, subject=None, days=None, downloads=None, notify=None): """Update properties for a transfer. :param message: updated message to recipient(s) :param subject: updated subject for trasfer :param days: updated amount of days transfer is available :param downloads: update amount of downloads allowed for transfer :param notify: update whether to notifiy on downloads or not :type message: ``str`` or ``unicode`` :type subject: ``str`` or ``unicode`` :type days: ``int`` :type downloads: ``int`` :type notify: ``bool`` :rtype: ``bool`` """ method, url = get_URL('update') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, } data = { 'message': message or self.transfer_info.get('message'), 'message': subject or self.transfer_info.get('subject'), 'days': days or self.transfer_info.get('days'), 'downloads': downloads or self.transfer_info.get('downloads'), 'notify': notify or self.transfer_info.get('notify') } payload.update(data) res = getattr(self.session, method)(url, params=payload) if res.status_code: self.transfer_info.update(data) return True hellraiser(res)
python
def update(self, message=None, subject=None, days=None, downloads=None, notify=None): """Update properties for a transfer. :param message: updated message to recipient(s) :param subject: updated subject for trasfer :param days: updated amount of days transfer is available :param downloads: update amount of downloads allowed for transfer :param notify: update whether to notifiy on downloads or not :type message: ``str`` or ``unicode`` :type subject: ``str`` or ``unicode`` :type days: ``int`` :type downloads: ``int`` :type notify: ``bool`` :rtype: ``bool`` """ method, url = get_URL('update') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id, } data = { 'message': message or self.transfer_info.get('message'), 'message': subject or self.transfer_info.get('subject'), 'days': days or self.transfer_info.get('days'), 'downloads': downloads or self.transfer_info.get('downloads'), 'notify': notify or self.transfer_info.get('notify') } payload.update(data) res = getattr(self.session, method)(url, params=payload) if res.status_code: self.transfer_info.update(data) return True hellraiser(res)
[ "def", "update", "(", "self", ",", "message", "=", "None", ",", "subject", "=", "None", ",", "days", "=", "None", ",", "downloads", "=", "None", ",", "notify", "=", "None", ")", ":", "method", ",", "url", "=", "get_URL", "(", "'update'", ")", "payl...
Update properties for a transfer. :param message: updated message to recipient(s) :param subject: updated subject for trasfer :param days: updated amount of days transfer is available :param downloads: update amount of downloads allowed for transfer :param notify: update whether to notifiy on downloads or not :type message: ``str`` or ``unicode`` :type subject: ``str`` or ``unicode`` :type days: ``int`` :type downloads: ``int`` :type notify: ``bool`` :rtype: ``bool``
[ "Update", "properties", "for", "a", "transfer", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L581-L626
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.download
def download(self, files=None, destination=None, overwrite=False, callback=None): """Download file or files. :param files: file or files to download :param destination: destination path (defaults to users home directory) :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arguments :type files: ``list`` of ``dict`` with file data from filemail :type destination: ``str`` or ``unicode`` :type overwrite: ``bool`` :type callback: ``func`` """ if files is None: files = self.files elif not isinstance(files, list): files = [files] if destination is None: destination = os.path.expanduser('~') for f in files: if not isinstance(f, dict): raise FMBaseError('File must be a <dict> with file data') self._download(f, destination, overwrite, callback)
python
def download(self, files=None, destination=None, overwrite=False, callback=None): """Download file or files. :param files: file or files to download :param destination: destination path (defaults to users home directory) :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arguments :type files: ``list`` of ``dict`` with file data from filemail :type destination: ``str`` or ``unicode`` :type overwrite: ``bool`` :type callback: ``func`` """ if files is None: files = self.files elif not isinstance(files, list): files = [files] if destination is None: destination = os.path.expanduser('~') for f in files: if not isinstance(f, dict): raise FMBaseError('File must be a <dict> with file data') self._download(f, destination, overwrite, callback)
[ "def", "download", "(", "self", ",", "files", "=", "None", ",", "destination", "=", "None", ",", "overwrite", "=", "False", ",", "callback", "=", "None", ")", ":", "if", "files", "is", "None", ":", "files", "=", "self", ".", "files", "elif", "not", ...
Download file or files. :param files: file or files to download :param destination: destination path (defaults to users home directory) :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arguments :type files: ``list`` of ``dict`` with file data from filemail :type destination: ``str`` or ``unicode`` :type overwrite: ``bool`` :type callback: ``func``
[ "Download", "file", "or", "files", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L628-L660
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer._download
def _download(self, fmfile, destination, overwrite, callback): """The actual downloader streaming content from Filemail. :param fmfile: to download :param destination: destination path :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arguments :type fmfile: ``dict`` :type destination: ``str`` or ``unicode`` :type overwrite: ``bool`` :type callback: ``func`` """ fullpath = os.path.join(destination, fmfile.get('filename')) path, filename = os.path.split(fullpath) if os.path.exists(fullpath): msg = 'Skipping existing file: {filename}' logger.info(msg.format(filename=filename)) return filesize = fmfile.get('filesize') if not os.path.exists(path): os.makedirs(path) url = fmfile.get('downloadurl') stream = self.session.get(url, stream=True) def pg_callback(bytes_written): if pm.COMMANDLINE: bar.show(bytes_written) elif callback is not None: callback(filesize, bytes_written) if pm.COMMANDLINE: label = fmfile['filename'] + ': ' bar = ProgressBar(label=label, expected_size=filesize) bytes_written = 0 with open(fullpath, 'wb') as f: for chunk in stream.iter_content(chunk_size=1024 * 1024): if not chunk: break f.write(chunk) bytes_written += len(chunk) # Callback pg_callback(bytes_written)
python
def _download(self, fmfile, destination, overwrite, callback): """The actual downloader streaming content from Filemail. :param fmfile: to download :param destination: destination path :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arguments :type fmfile: ``dict`` :type destination: ``str`` or ``unicode`` :type overwrite: ``bool`` :type callback: ``func`` """ fullpath = os.path.join(destination, fmfile.get('filename')) path, filename = os.path.split(fullpath) if os.path.exists(fullpath): msg = 'Skipping existing file: {filename}' logger.info(msg.format(filename=filename)) return filesize = fmfile.get('filesize') if not os.path.exists(path): os.makedirs(path) url = fmfile.get('downloadurl') stream = self.session.get(url, stream=True) def pg_callback(bytes_written): if pm.COMMANDLINE: bar.show(bytes_written) elif callback is not None: callback(filesize, bytes_written) if pm.COMMANDLINE: label = fmfile['filename'] + ': ' bar = ProgressBar(label=label, expected_size=filesize) bytes_written = 0 with open(fullpath, 'wb') as f: for chunk in stream.iter_content(chunk_size=1024 * 1024): if not chunk: break f.write(chunk) bytes_written += len(chunk) # Callback pg_callback(bytes_written)
[ "def", "_download", "(", "self", ",", "fmfile", ",", "destination", ",", "overwrite", ",", "callback", ")", ":", "fullpath", "=", "os", ".", "path", ".", "join", "(", "destination", ",", "fmfile", ".", "get", "(", "'filename'", ")", ")", "path", ",", ...
The actual downloader streaming content from Filemail. :param fmfile: to download :param destination: destination path :param overwrite: replace existing files? :param callback: callback function that will receive total file size and written bytes as arguments :type fmfile: ``dict`` :type destination: ``str`` or ``unicode`` :type overwrite: ``bool`` :type callback: ``func``
[ "The", "actual", "downloader", "streaming", "content", "from", "Filemail", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L662-L713
apetrynet/pyfilemail
pyfilemail/transfer.py
Transfer.compress
def compress(self): """Compress files on the server side after transfer complete and make zip available for download. :rtype: ``bool`` """ method, url = get_URL('compress') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: return True hellraiser(res)
python
def compress(self): """Compress files on the server side after transfer complete and make zip available for download. :rtype: ``bool`` """ method, url = get_URL('compress') payload = { 'apikey': self.config.get('apikey'), 'logintoken': self.session.cookies.get('logintoken'), 'transferid': self.transfer_id } res = getattr(self.session, method)(url, params=payload) if res.status_code == 200: return True hellraiser(res)
[ "def", "compress", "(", "self", ")", ":", "method", ",", "url", "=", "get_URL", "(", "'compress'", ")", "payload", "=", "{", "'apikey'", ":", "self", ".", "config", ".", "get", "(", "'apikey'", ")", ",", "'logintoken'", ":", "self", ".", "session", "...
Compress files on the server side after transfer complete and make zip available for download. :rtype: ``bool``
[ "Compress", "files", "on", "the", "server", "side", "after", "transfer", "complete", "and", "make", "zip", "available", "for", "download", "." ]
train
https://github.com/apetrynet/pyfilemail/blob/eb81b0e69ff42f4335d5298833e4769b750bf397/pyfilemail/transfer.py#L716-L736
patarapolw/memorable-password
memorable_password/sentence.py
ToSentence.from_pin
def from_pin(self, pin, timeout=5): """ Generate a sentence from PIN :param str pin: a string of digits :param float timeout: total time in seconds :return dict: { 'sentence': sentence corresponding to the PIN, 'overlap': overlapping positions, starting for 0 } >>> ToSentence().from_pin('3492') [("Helva's", False), ('masking', True), ('was', False), ('not', False), ('without', False), ('real', True), (',', False), ('pretty', True), ('novels', True)] """ return self.keyword_parse.from_initials_list([self.mnemonic.reality_to_starter('major_system', number) for number in pin], timeout)
python
def from_pin(self, pin, timeout=5): """ Generate a sentence from PIN :param str pin: a string of digits :param float timeout: total time in seconds :return dict: { 'sentence': sentence corresponding to the PIN, 'overlap': overlapping positions, starting for 0 } >>> ToSentence().from_pin('3492') [("Helva's", False), ('masking', True), ('was', False), ('not', False), ('without', False), ('real', True), (',', False), ('pretty', True), ('novels', True)] """ return self.keyword_parse.from_initials_list([self.mnemonic.reality_to_starter('major_system', number) for number in pin], timeout)
[ "def", "from_pin", "(", "self", ",", "pin", ",", "timeout", "=", "5", ")", ":", "return", "self", ".", "keyword_parse", ".", "from_initials_list", "(", "[", "self", ".", "mnemonic", ".", "reality_to_starter", "(", "'major_system'", ",", "number", ")", "for...
Generate a sentence from PIN :param str pin: a string of digits :param float timeout: total time in seconds :return dict: { 'sentence': sentence corresponding to the PIN, 'overlap': overlapping positions, starting for 0 } >>> ToSentence().from_pin('3492') [("Helva's", False), ('masking', True), ('was', False), ('not', False), ('without', False), ('real', True), (',', False), ('pretty', True), ('novels', True)]
[ "Generate", "a", "sentence", "from", "PIN" ]
train
https://github.com/patarapolw/memorable-password/blob/f53a2afa4104238e1770dfd4d85710bc00719302/memorable_password/sentence.py#L13-L29
patarapolw/memorable-password
memorable_password/sentence.py
ToSentence.from_keywords
def from_keywords(self, keyword_list, strictness=2, timeout=3): """ Generate a sentence from initial_list. :param list keyword_list: a list of keywords to be included in the sentence. :param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching :param float timeout: timeout of this function :return list of tuple: >>> ToSentence().from_keywords(['gains', 'grew', 'pass', 'greene', 'escort', 'illinois']) [('The', False), ('gains', True), ('of', False), ('Bienville', False), ('upon', False), ('grew', True), ('liberal', False), ('pass', True), ('to', False), ('the', False), ('Indians', False), (',', False), ('in', False), ('greene', True), ('to', False), ('drive', False), ('back', False), ('the', False), ('Carolina', False), ('escort', True), (',', False), ('was', False), ('probably', False), ('a', False), ('illinois', True)] """ return self.keyword_parse.from_keyword_list(keyword_list, strictness, timeout)
python
def from_keywords(self, keyword_list, strictness=2, timeout=3): """ Generate a sentence from initial_list. :param list keyword_list: a list of keywords to be included in the sentence. :param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching :param float timeout: timeout of this function :return list of tuple: >>> ToSentence().from_keywords(['gains', 'grew', 'pass', 'greene', 'escort', 'illinois']) [('The', False), ('gains', True), ('of', False), ('Bienville', False), ('upon', False), ('grew', True), ('liberal', False), ('pass', True), ('to', False), ('the', False), ('Indians', False), (',', False), ('in', False), ('greene', True), ('to', False), ('drive', False), ('back', False), ('the', False), ('Carolina', False), ('escort', True), (',', False), ('was', False), ('probably', False), ('a', False), ('illinois', True)] """ return self.keyword_parse.from_keyword_list(keyword_list, strictness, timeout)
[ "def", "from_keywords", "(", "self", ",", "keyword_list", ",", "strictness", "=", "2", ",", "timeout", "=", "3", ")", ":", "return", "self", ".", "keyword_parse", ".", "from_keyword_list", "(", "keyword_list", ",", "strictness", ",", "timeout", ")" ]
Generate a sentence from initial_list. :param list keyword_list: a list of keywords to be included in the sentence. :param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching :param float timeout: timeout of this function :return list of tuple: >>> ToSentence().from_keywords(['gains', 'grew', 'pass', 'greene', 'escort', 'illinois']) [('The', False), ('gains', True), ('of', False), ('Bienville', False), ('upon', False), ('grew', True), ('liberal', False), ('pass', True), ('to', False), ('the', False), ('Indians', False), (',', False), ('in', False), ('greene', True), ('to', False), ('drive', False), ('back', False), ('the', False), ('Carolina', False), ('escort', True), (',', False), ('was', False), ('probably', False), ('a', False), ('illinois', True)]
[ "Generate", "a", "sentence", "from", "initial_list", "." ]
train
https://github.com/patarapolw/memorable-password/blob/f53a2afa4104238e1770dfd4d85710bc00719302/memorable_password/sentence.py#L44-L56
uta-smile/smile-python
smile/flags.py
_define_helper
def _define_helper(flag_name, default_value, docstring, flagtype, required): """Registers 'flag_name' with 'default_value' and 'docstring'.""" option_name = flag_name if required else "--%s" % flag_name get_context_parser().add_argument( option_name, default=default_value, help=docstring, type=flagtype)
python
def _define_helper(flag_name, default_value, docstring, flagtype, required): """Registers 'flag_name' with 'default_value' and 'docstring'.""" option_name = flag_name if required else "--%s" % flag_name get_context_parser().add_argument( option_name, default=default_value, help=docstring, type=flagtype)
[ "def", "_define_helper", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "flagtype", ",", "required", ")", ":", "option_name", "=", "flag_name", "if", "required", "else", "\"--%s\"", "%", "flag_name", "get_context_parser", "(", ")", ".", "add_argu...
Registers 'flag_name' with 'default_value' and 'docstring'.
[ "Registers", "flag_name", "with", "default_value", "and", "docstring", "." ]
train
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L121-L125
uta-smile/smile-python
smile/flags.py
DEFINE_string
def DEFINE_string(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'string'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a string. docstring: A helpful message explaining the use of the flag. """ _define_helper(flag_name, default_value, docstring, str, required)
python
def DEFINE_string(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'string'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a string. docstring: A helpful message explaining the use of the flag. """ _define_helper(flag_name, default_value, docstring, str, required)
[ "def", "DEFINE_string", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "required", "=", "False", ")", ":", "# pylint: disable=invalid-name", "_define_helper", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "str", ",", "required", ")...
Defines a flag of type 'string'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a string. docstring: A helpful message explaining the use of the flag.
[ "Defines", "a", "flag", "of", "type", "string", ".", "Args", ":", "flag_name", ":", "The", "name", "of", "the", "flag", "as", "a", "string", ".", "default_value", ":", "The", "default", "value", "the", "flag", "should", "take", "as", "a", "string", "."...
train
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L132-L139
uta-smile/smile-python
smile/flags.py
DEFINE_integer
def DEFINE_integer(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'int'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as an int. docstring: A helpful message explaining the use of the flag. """ _define_helper(flag_name, default_value, docstring, int, required)
python
def DEFINE_integer(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'int'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as an int. docstring: A helpful message explaining the use of the flag. """ _define_helper(flag_name, default_value, docstring, int, required)
[ "def", "DEFINE_integer", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "required", "=", "False", ")", ":", "# pylint: disable=invalid-name", "_define_helper", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "int", ",", "required", "...
Defines a flag of type 'int'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as an int. docstring: A helpful message explaining the use of the flag.
[ "Defines", "a", "flag", "of", "type", "int", ".", "Args", ":", "flag_name", ":", "The", "name", "of", "the", "flag", "as", "a", "string", ".", "default_value", ":", "The", "default", "value", "the", "flag", "should", "take", "as", "an", "int", ".", "...
train
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L142-L149
uta-smile/smile-python
smile/flags.py
DEFINE_boolean
def DEFINE_boolean(flag_name, default_value, docstring): # pylint: disable=invalid-name """Defines a flag of type 'boolean'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a boolean. docstring: A helpful message explaining the use of the flag. """ # Register a custom function for 'bool' so --flag=True works. def str2bool(bool_str): """Return a boolean value from a give string.""" return bool_str.lower() in ('true', 't', '1') get_context_parser().add_argument( '--' + flag_name, nargs='?', const=True, help=docstring, default=default_value, type=str2bool) # Add negated version, stay consistent with argparse with regard to # dashes in flag names. get_context_parser().add_argument( '--no' + flag_name, action='store_false', dest=flag_name.replace('-', '_'))
python
def DEFINE_boolean(flag_name, default_value, docstring): # pylint: disable=invalid-name """Defines a flag of type 'boolean'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a boolean. docstring: A helpful message explaining the use of the flag. """ # Register a custom function for 'bool' so --flag=True works. def str2bool(bool_str): """Return a boolean value from a give string.""" return bool_str.lower() in ('true', 't', '1') get_context_parser().add_argument( '--' + flag_name, nargs='?', const=True, help=docstring, default=default_value, type=str2bool) # Add negated version, stay consistent with argparse with regard to # dashes in flag names. get_context_parser().add_argument( '--no' + flag_name, action='store_false', dest=flag_name.replace('-', '_'))
[ "def", "DEFINE_boolean", "(", "flag_name", ",", "default_value", ",", "docstring", ")", ":", "# pylint: disable=invalid-name", "# Register a custom function for 'bool' so --flag=True works.", "def", "str2bool", "(", "bool_str", ")", ":", "\"\"\"Return a boolean value from a give ...
Defines a flag of type 'boolean'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a boolean. docstring: A helpful message explaining the use of the flag.
[ "Defines", "a", "flag", "of", "type", "boolean", ".", "Args", ":", "flag_name", ":", "The", "name", "of", "the", "flag", "as", "a", "string", ".", "default_value", ":", "The", "default", "value", "the", "flag", "should", "take", "as", "a", "boolean", "...
train
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L152-L178
uta-smile/smile-python
smile/flags.py
DEFINE_float
def DEFINE_float(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'float'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a float. docstring: A helpful message explaining the use of the flag. """ _define_helper(flag_name, default_value, docstring, float, required)
python
def DEFINE_float(flag_name, default_value, docstring, required=False): # pylint: disable=invalid-name """Defines a flag of type 'float'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a float. docstring: A helpful message explaining the use of the flag. """ _define_helper(flag_name, default_value, docstring, float, required)
[ "def", "DEFINE_float", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "required", "=", "False", ")", ":", "# pylint: disable=invalid-name", "_define_helper", "(", "flag_name", ",", "default_value", ",", "docstring", ",", "float", ",", "required", "...
Defines a flag of type 'float'. Args: flag_name: The name of the flag as a string. default_value: The default value the flag should take as a float. docstring: A helpful message explaining the use of the flag.
[ "Defines", "a", "flag", "of", "type", "float", ".", "Args", ":", "flag_name", ":", "The", "name", "of", "the", "flag", "as", "a", "string", ".", "default_value", ":", "The", "default", "value", "the", "flag", "should", "take", "as", "a", "float", ".", ...
train
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L186-L193
uta-smile/smile-python
smile/flags.py
NamedParser._get_subparsers
def _get_subparsers(self, dest): """Get named subparsers.""" if not self._subparsers: self._subparsers = self.parser.add_subparsers(dest=dest) elif self._subparsers.dest != dest: raise KeyError( "Subparser names mismatch. You can only create one subcommand.") return self._subparsers
python
def _get_subparsers(self, dest): """Get named subparsers.""" if not self._subparsers: self._subparsers = self.parser.add_subparsers(dest=dest) elif self._subparsers.dest != dest: raise KeyError( "Subparser names mismatch. You can only create one subcommand.") return self._subparsers
[ "def", "_get_subparsers", "(", "self", ",", "dest", ")", ":", "if", "not", "self", ".", "_subparsers", ":", "self", ".", "_subparsers", "=", "self", ".", "parser", ".", "add_subparsers", "(", "dest", "=", "dest", ")", "elif", "self", ".", "_subparsers", ...
Get named subparsers.
[ "Get", "named", "subparsers", "." ]
train
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L21-L28
uta-smile/smile-python
smile/flags.py
NamedParser.get_subparser
def get_subparser(self, name, dest="subcommand", **kwargs): """Get or create subparser.""" if name not in self.children: # Create the subparser. subparsers = self._get_subparsers(dest) parser = subparsers.add_parser(name, **kwargs) self.children[name] = NamedParser(name, parser) return self.children[name]
python
def get_subparser(self, name, dest="subcommand", **kwargs): """Get or create subparser.""" if name not in self.children: # Create the subparser. subparsers = self._get_subparsers(dest) parser = subparsers.add_parser(name, **kwargs) self.children[name] = NamedParser(name, parser) return self.children[name]
[ "def", "get_subparser", "(", "self", ",", "name", ",", "dest", "=", "\"subcommand\"", ",", "*", "*", "kwargs", ")", ":", "if", "name", "not", "in", "self", ".", "children", ":", "# Create the subparser.", "subparsers", "=", "self", ".", "_get_subparsers", ...
Get or create subparser.
[ "Get", "or", "create", "subparser", "." ]
train
https://github.com/uta-smile/smile-python/blob/8918d1bb9ef76922ef976f6e3a10578b3a0af1c8/smile/flags.py#L30-L37
gbiggs/rtctree
rtctree/utils.py
build_attr_string
def build_attr_string(attrs, supported=True): '''Build a string that will turn any ANSI shell output the desired colour. attrs should be a list of keys into the term_attributes table. ''' if not supported: return '' if type(attrs) == str: attrs = [attrs] result = '\033[' for attr in attrs: result += term_attributes[attr] + ';' return result[:-1] + 'm'
python
def build_attr_string(attrs, supported=True): '''Build a string that will turn any ANSI shell output the desired colour. attrs should be a list of keys into the term_attributes table. ''' if not supported: return '' if type(attrs) == str: attrs = [attrs] result = '\033[' for attr in attrs: result += term_attributes[attr] + ';' return result[:-1] + 'm'
[ "def", "build_attr_string", "(", "attrs", ",", "supported", "=", "True", ")", ":", "if", "not", "supported", ":", "return", "''", "if", "type", "(", "attrs", ")", "==", "str", ":", "attrs", "=", "[", "attrs", "]", "result", "=", "'\\033['", "for", "a...
Build a string that will turn any ANSI shell output the desired colour. attrs should be a list of keys into the term_attributes table.
[ "Build", "a", "string", "that", "will", "turn", "any", "ANSI", "shell", "output", "the", "desired", "colour", ".", "attrs", "should", "be", "a", "list", "of", "keys", "into", "the", "term_attributes", "table", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/utils.py#L64-L78
gbiggs/rtctree
rtctree/utils.py
get_num_columns_and_rows
def get_num_columns_and_rows(widths, gap_width, term_width): '''Given a list of string widths, a width of the minimum gap to place between them, and the maximum width of the output (such as a terminal width), calculate the number of columns and rows, and the width of each column, for the optimal layout. ''' def calc_longest_width(widths, gap_width, ncols): longest = 0 rows = [widths[s:s + ncols] for s in range(0, len(widths), ncols)] col_widths = rows[0] # Column widths start at the first row widths for r in rows: for ii, c in enumerate(r): if c > col_widths[ii]: col_widths[ii] = c length = sum(col_widths) + gap_width * (ncols - 1) if length > longest: longest = length return longest, col_widths def calc_num_rows(num_items, cols): div, mod = divmod(num_items, cols) return div + (mod != 0) # Start with one row ncols = len(widths) # Calculate the width of the longest row as the longest set of item widths # ncols long and gap widths (gap_width * ncols - 1) that fits within the # terminal width. while ncols > 0: longest_width, col_widths = calc_longest_width(widths, gap_width, ncols) if longest_width < term_width: # This number of columns fits return calc_num_rows(len(widths), ncols), ncols, col_widths else: # This number of columns doesn't fit, so try one less ncols -= 1 # If got here, it all has to go in one column return len(widths), 1, 0
python
def get_num_columns_and_rows(widths, gap_width, term_width): '''Given a list of string widths, a width of the minimum gap to place between them, and the maximum width of the output (such as a terminal width), calculate the number of columns and rows, and the width of each column, for the optimal layout. ''' def calc_longest_width(widths, gap_width, ncols): longest = 0 rows = [widths[s:s + ncols] for s in range(0, len(widths), ncols)] col_widths = rows[0] # Column widths start at the first row widths for r in rows: for ii, c in enumerate(r): if c > col_widths[ii]: col_widths[ii] = c length = sum(col_widths) + gap_width * (ncols - 1) if length > longest: longest = length return longest, col_widths def calc_num_rows(num_items, cols): div, mod = divmod(num_items, cols) return div + (mod != 0) # Start with one row ncols = len(widths) # Calculate the width of the longest row as the longest set of item widths # ncols long and gap widths (gap_width * ncols - 1) that fits within the # terminal width. while ncols > 0: longest_width, col_widths = calc_longest_width(widths, gap_width, ncols) if longest_width < term_width: # This number of columns fits return calc_num_rows(len(widths), ncols), ncols, col_widths else: # This number of columns doesn't fit, so try one less ncols -= 1 # If got here, it all has to go in one column return len(widths), 1, 0
[ "def", "get_num_columns_and_rows", "(", "widths", ",", "gap_width", ",", "term_width", ")", ":", "def", "calc_longest_width", "(", "widths", ",", "gap_width", ",", "ncols", ")", ":", "longest", "=", "0", "rows", "=", "[", "widths", "[", "s", ":", "s", "+...
Given a list of string widths, a width of the minimum gap to place between them, and the maximum width of the output (such as a terminal width), calculate the number of columns and rows, and the width of each column, for the optimal layout.
[ "Given", "a", "list", "of", "string", "widths", "a", "width", "of", "the", "minimum", "gap", "to", "place", "between", "them", "and", "the", "maximum", "width", "of", "the", "output", "(", "such", "as", "a", "terminal", "width", ")", "calculate", "the", ...
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/utils.py#L87-L125
gbiggs/rtctree
rtctree/utils.py
get_terminal_size
def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: import struct, fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '0000')) except ImportError: return None except IOError as e: return None return cr[1], cr[0] cr = read_terminal_size_by_ioctl(0) or \ read_terminal_size_by_ioctl(1) or \ read_terminal_size_by_ioctl(2) if not cr: try: import os fd = os.open(os.ctermid(), os.O_RDONLY) cr = read_terminal_size_by_ioctl(fd) os.close(fd) except: pass if not cr: import os cr = [80, 25] # 25 rows, 80 columns is the default value if os.getenv('ROWS'): cr[1] = int(os.getenv('ROWS')) if os.getenv('COLUMNS'): cr[0] = int(os.getenv('COLUMNS')) return cr[1], cr[0]
python
def get_terminal_size(): '''Finds the width of the terminal, or returns a suitable default value.''' def read_terminal_size_by_ioctl(fd): try: import struct, fcntl, termios cr = struct.unpack('hh', fcntl.ioctl(1, termios.TIOCGWINSZ, '0000')) except ImportError: return None except IOError as e: return None return cr[1], cr[0] cr = read_terminal_size_by_ioctl(0) or \ read_terminal_size_by_ioctl(1) or \ read_terminal_size_by_ioctl(2) if not cr: try: import os fd = os.open(os.ctermid(), os.O_RDONLY) cr = read_terminal_size_by_ioctl(fd) os.close(fd) except: pass if not cr: import os cr = [80, 25] # 25 rows, 80 columns is the default value if os.getenv('ROWS'): cr[1] = int(os.getenv('ROWS')) if os.getenv('COLUMNS'): cr[0] = int(os.getenv('COLUMNS')) return cr[1], cr[0]
[ "def", "get_terminal_size", "(", ")", ":", "def", "read_terminal_size_by_ioctl", "(", "fd", ")", ":", "try", ":", "import", "struct", ",", "fcntl", ",", "termios", "cr", "=", "struct", ".", "unpack", "(", "'hh'", ",", "fcntl", ".", "ioctl", "(", "1", "...
Finds the width of the terminal, or returns a suitable default value.
[ "Finds", "the", "width", "of", "the", "terminal", "or", "returns", "a", "suitable", "default", "value", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/utils.py#L128-L160
gbiggs/rtctree
rtctree/utils.py
dict_to_nvlist
def dict_to_nvlist(dict): '''Convert a dictionary into a CORBA namevalue list.''' result = [] for item in list(dict.keys()): result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item]))) return result
python
def dict_to_nvlist(dict): '''Convert a dictionary into a CORBA namevalue list.''' result = [] for item in list(dict.keys()): result.append(SDOPackage.NameValue(item, omniORB.any.to_any(dict[item]))) return result
[ "def", "dict_to_nvlist", "(", "dict", ")", ":", "result", "=", "[", "]", "for", "item", "in", "list", "(", "dict", ".", "keys", "(", ")", ")", ":", "result", ".", "append", "(", "SDOPackage", ".", "NameValue", "(", "item", ",", "omniORB", ".", "any...
Convert a dictionary into a CORBA namevalue list.
[ "Convert", "a", "dictionary", "into", "a", "CORBA", "namevalue", "list", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/utils.py#L163-L168
gbiggs/rtctree
rtctree/utils.py
nvlist_to_dict
def nvlist_to_dict(nvlist): '''Convert a CORBA namevalue list into a dictionary.''' result = {} for item in nvlist : result[item.name] = item.value.value() return result
python
def nvlist_to_dict(nvlist): '''Convert a CORBA namevalue list into a dictionary.''' result = {} for item in nvlist : result[item.name] = item.value.value() return result
[ "def", "nvlist_to_dict", "(", "nvlist", ")", ":", "result", "=", "{", "}", "for", "item", "in", "nvlist", ":", "result", "[", "item", ".", "name", "]", "=", "item", ".", "value", ".", "value", "(", ")", "return", "result" ]
Convert a CORBA namevalue list into a dictionary.
[ "Convert", "a", "CORBA", "namevalue", "list", "into", "a", "dictionary", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/utils.py#L171-L176
gbiggs/rtctree
rtctree/utils.py
filtered
def filtered(path, filter): '''Check if a path is removed by a filter. Check if a path is in the provided set of paths, @ref filter. If none of the paths in filter begin with @ref path, then True is returned to indicate that the path is filtered out. If @ref path is longer than the filter, and starts with the filter, it is considered unfiltered (all paths below a filter are unfiltered). An empty filter ([]) is treated as not filtering any. ''' if not filter: return False for p in filter: if len(path) > len(p): if path[:len(p)] == p: return False else: if p[:len(path)] == path: return False return True
python
def filtered(path, filter): '''Check if a path is removed by a filter. Check if a path is in the provided set of paths, @ref filter. If none of the paths in filter begin with @ref path, then True is returned to indicate that the path is filtered out. If @ref path is longer than the filter, and starts with the filter, it is considered unfiltered (all paths below a filter are unfiltered). An empty filter ([]) is treated as not filtering any. ''' if not filter: return False for p in filter: if len(path) > len(p): if path[:len(p)] == p: return False else: if p[:len(path)] == path: return False return True
[ "def", "filtered", "(", "path", ",", "filter", ")", ":", "if", "not", "filter", ":", "return", "False", "for", "p", "in", "filter", ":", "if", "len", "(", "path", ")", ">", "len", "(", "p", ")", ":", "if", "path", "[", ":", "len", "(", "p", "...
Check if a path is removed by a filter. Check if a path is in the provided set of paths, @ref filter. If none of the paths in filter begin with @ref path, then True is returned to indicate that the path is filtered out. If @ref path is longer than the filter, and starts with the filter, it is considered unfiltered (all paths below a filter are unfiltered). An empty filter ([]) is treated as not filtering any.
[ "Check", "if", "a", "path", "is", "removed", "by", "a", "filter", ".", "Check", "if", "a", "path", "is", "in", "the", "provided", "set", "of", "paths" ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/utils.py#L179-L200
gbiggs/rtctree
rtctree/utils.py
trim_filter
def trim_filter(filter, levels=1): '''Trim @ref levels levels from the front of each path in @filter.''' trimmed = [f[levels:] for f in filter] return [f for f in trimmed if f]
python
def trim_filter(filter, levels=1): '''Trim @ref levels levels from the front of each path in @filter.''' trimmed = [f[levels:] for f in filter] return [f for f in trimmed if f]
[ "def", "trim_filter", "(", "filter", ",", "levels", "=", "1", ")", ":", "trimmed", "=", "[", "f", "[", "levels", ":", "]", "for", "f", "in", "filter", "]", "return", "[", "f", "for", "f", "in", "trimmed", "if", "f", "]" ]
Trim @ref levels levels from the front of each path in @filter.
[ "Trim" ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/utils.py#L203-L206
AutomatedTester/Bugsy
bugsy/bugsy.py
Bugsy.get
def get(self, bug_number): """ Get a bug from Bugzilla. If there is a login token created during object initialisation it will be part of the query string passed to Bugzilla :param bug_number: Bug Number that will be searched. If found will return a Bug object. >>> bugzilla = Bugsy() >>> bug = bugzilla.get(123456) """ bug = self.request( 'bug/%s' % bug_number, params={"include_fields": self. DEFAULT_SEARCH} ) return Bug(self, **bug['bugs'][0])
python
def get(self, bug_number): """ Get a bug from Bugzilla. If there is a login token created during object initialisation it will be part of the query string passed to Bugzilla :param bug_number: Bug Number that will be searched. If found will return a Bug object. >>> bugzilla = Bugsy() >>> bug = bugzilla.get(123456) """ bug = self.request( 'bug/%s' % bug_number, params={"include_fields": self. DEFAULT_SEARCH} ) return Bug(self, **bug['bugs'][0])
[ "def", "get", "(", "self", ",", "bug_number", ")", ":", "bug", "=", "self", ".", "request", "(", "'bug/%s'", "%", "bug_number", ",", "params", "=", "{", "\"include_fields\"", ":", "self", ".", "DEFAULT_SEARCH", "}", ")", "return", "Bug", "(", "self", "...
Get a bug from Bugzilla. If there is a login token created during object initialisation it will be part of the query string passed to Bugzilla :param bug_number: Bug Number that will be searched. If found will return a Bug object. >>> bugzilla = Bugsy() >>> bug = bugzilla.get(123456)
[ "Get", "a", "bug", "from", "Bugzilla", ".", "If", "there", "is", "a", "login", "token", "created", "during", "object", "initialisation", "it", "will", "be", "part", "of", "the", "query", "string", "passed", "to", "Bugzilla" ]
train
https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bugsy.py#L113-L129
AutomatedTester/Bugsy
bugsy/bugsy.py
Bugsy.put
def put(self, bug): """ This method allows you to create or update a bug on Bugzilla. You will have had to pass in a valid username and password to the object initialisation and recieved back a token. :param bug: A Bug object either created by hand or by using get() If there is no valid token then a BugsyException will be raised. If the object passed in is not a Bug then a BugsyException will be raised. >>> bugzilla = Bugsy() >>> bug = bugzilla.get(123456) >>> bug.summary = "I like cheese and sausages" >>> bugzilla.put(bug) """ if not self._have_auth: raise BugsyException("Unfortunately you can't put bugs in Bugzilla" " without credentials") if not isinstance(bug, Bug): raise BugsyException("Please pass in a Bug object when posting" " to Bugzilla") if not bug.id: result = self.request('bug', 'POST', json=bug.to_dict()) if 'error' not in result: bug._bug['id'] = result['id'] bug._bugsy = self try: bug._bug.pop('comment') except Exception: # If we don't have a `comment` we will error so let's just # swallow it. pass else: raise BugsyException(result['message']) else: result = self.request('bug/%s' % bug.id, 'PUT', json=bug.to_dict()) updated_bug = self.get(bug.id) return updated_bug
python
def put(self, bug): """ This method allows you to create or update a bug on Bugzilla. You will have had to pass in a valid username and password to the object initialisation and recieved back a token. :param bug: A Bug object either created by hand or by using get() If there is no valid token then a BugsyException will be raised. If the object passed in is not a Bug then a BugsyException will be raised. >>> bugzilla = Bugsy() >>> bug = bugzilla.get(123456) >>> bug.summary = "I like cheese and sausages" >>> bugzilla.put(bug) """ if not self._have_auth: raise BugsyException("Unfortunately you can't put bugs in Bugzilla" " without credentials") if not isinstance(bug, Bug): raise BugsyException("Please pass in a Bug object when posting" " to Bugzilla") if not bug.id: result = self.request('bug', 'POST', json=bug.to_dict()) if 'error' not in result: bug._bug['id'] = result['id'] bug._bugsy = self try: bug._bug.pop('comment') except Exception: # If we don't have a `comment` we will error so let's just # swallow it. pass else: raise BugsyException(result['message']) else: result = self.request('bug/%s' % bug.id, 'PUT', json=bug.to_dict()) updated_bug = self.get(bug.id) return updated_bug
[ "def", "put", "(", "self", ",", "bug", ")", ":", "if", "not", "self", ".", "_have_auth", ":", "raise", "BugsyException", "(", "\"Unfortunately you can't put bugs in Bugzilla\"", "\" without credentials\"", ")", "if", "not", "isinstance", "(", "bug", ",", "Bug", ...
This method allows you to create or update a bug on Bugzilla. You will have had to pass in a valid username and password to the object initialisation and recieved back a token. :param bug: A Bug object either created by hand or by using get() If there is no valid token then a BugsyException will be raised. If the object passed in is not a Bug then a BugsyException will be raised. >>> bugzilla = Bugsy() >>> bug = bugzilla.get(123456) >>> bug.summary = "I like cheese and sausages" >>> bugzilla.put(bug)
[ "This", "method", "allows", "you", "to", "create", "or", "update", "a", "bug", "on", "Bugzilla", ".", "You", "will", "have", "had", "to", "pass", "in", "a", "valid", "username", "and", "password", "to", "the", "object", "initialisation", "and", "recieved",...
train
https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bugsy.py#L131-L174
AutomatedTester/Bugsy
bugsy/bugsy.py
Bugsy.request
def request(self, path, method='GET', headers=None, **kwargs): """Perform a HTTP request. Given a relative Bugzilla URL path, an optional request method, and arguments suitable for requests.Request(), perform a HTTP request. """ headers = {} if headers is None else headers.copy() headers["User-Agent"] = "Bugsy" kwargs['headers'] = headers url = '%s/%s' % (self.bugzilla_url, path) return self._handle_errors(self.session.request(method, url, **kwargs))
python
def request(self, path, method='GET', headers=None, **kwargs): """Perform a HTTP request. Given a relative Bugzilla URL path, an optional request method, and arguments suitable for requests.Request(), perform a HTTP request. """ headers = {} if headers is None else headers.copy() headers["User-Agent"] = "Bugsy" kwargs['headers'] = headers url = '%s/%s' % (self.bugzilla_url, path) return self._handle_errors(self.session.request(method, url, **kwargs))
[ "def", "request", "(", "self", ",", "path", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "{", "}", "if", "headers", "is", "None", "else", "headers", ".", "copy", "(", ")", "headers", ...
Perform a HTTP request. Given a relative Bugzilla URL path, an optional request method, and arguments suitable for requests.Request(), perform a HTTP request.
[ "Perform", "a", "HTTP", "request", "." ]
train
https://github.com/AutomatedTester/Bugsy/blob/ac14df84e744a148e81aeaae20a144bc5f3cebf1/bugsy/bugsy.py#L180-L191
frnsys/broca
broca/cluster/parameter.py
estimate_eps
def estimate_eps(dist_mat, n_closest=5): """ Estimates possible eps values (to be used with DBSCAN) for a given distance matrix by looking at the largest distance "jumps" amongst the `n_closest` distances for each item. Tip: the value for `n_closest` is important - set it too large and you may only get really large distances which are uninformative. Set it too small and you may get premature cutoffs (i.e. select jumps which are really not that big). TO DO this could be fancier by calculating support for particular eps values, e.g. 80% are around 4.2 or w/e """ dist_mat = dist_mat.copy() # To ignore i == j distances dist_mat[np.where(dist_mat == 0)] = np.inf estimates = [] for i in range(dist_mat.shape[0]): # Indices of the n closest distances row = dist_mat[i] dists = sorted(np.partition(row, n_closest)[:n_closest]) difs = [(x, y, (y - x)) for x, y in zip(dists, dists[1:])] eps_candidate, _, jump = max(difs, key=lambda x: x[2]) estimates.append(eps_candidate) return sorted(estimates)
python
def estimate_eps(dist_mat, n_closest=5): """ Estimates possible eps values (to be used with DBSCAN) for a given distance matrix by looking at the largest distance "jumps" amongst the `n_closest` distances for each item. Tip: the value for `n_closest` is important - set it too large and you may only get really large distances which are uninformative. Set it too small and you may get premature cutoffs (i.e. select jumps which are really not that big). TO DO this could be fancier by calculating support for particular eps values, e.g. 80% are around 4.2 or w/e """ dist_mat = dist_mat.copy() # To ignore i == j distances dist_mat[np.where(dist_mat == 0)] = np.inf estimates = [] for i in range(dist_mat.shape[0]): # Indices of the n closest distances row = dist_mat[i] dists = sorted(np.partition(row, n_closest)[:n_closest]) difs = [(x, y, (y - x)) for x, y in zip(dists, dists[1:])] eps_candidate, _, jump = max(difs, key=lambda x: x[2]) estimates.append(eps_candidate) return sorted(estimates)
[ "def", "estimate_eps", "(", "dist_mat", ",", "n_closest", "=", "5", ")", ":", "dist_mat", "=", "dist_mat", ".", "copy", "(", ")", "# To ignore i == j distances", "dist_mat", "[", "np", ".", "where", "(", "dist_mat", "==", "0", ")", "]", "=", "np", ".", ...
Estimates possible eps values (to be used with DBSCAN) for a given distance matrix by looking at the largest distance "jumps" amongst the `n_closest` distances for each item. Tip: the value for `n_closest` is important - set it too large and you may only get really large distances which are uninformative. Set it too small and you may get premature cutoffs (i.e. select jumps which are really not that big). TO DO this could be fancier by calculating support for particular eps values, e.g. 80% are around 4.2 or w/e
[ "Estimates", "possible", "eps", "values", "(", "to", "be", "used", "with", "DBSCAN", ")", "for", "a", "given", "distance", "matrix", "by", "looking", "at", "the", "largest", "distance", "jumps", "amongst", "the", "n_closest", "distances", "for", "each", "ite...
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/cluster/parameter.py#L5-L32
frnsys/broca
broca/cluster/parameter.py
estimate_k
def estimate_k(X, max_k): """ Estimate k for K-Means. Adapted from <https://datasciencelab.wordpress.com/2014/01/21/selection-of-k-in-k-means-clustering-reloaded/> """ ks = range(1, max_k) fs = np.zeros(len(ks)) # Special case K=1 fs[0], Sk = _fK(1) # Rest of Ks for k in ks[1:]: fs[k-1], Sk = _fK(k, Skm1=Sk) return np.argmin(fs) + 1
python
def estimate_k(X, max_k): """ Estimate k for K-Means. Adapted from <https://datasciencelab.wordpress.com/2014/01/21/selection-of-k-in-k-means-clustering-reloaded/> """ ks = range(1, max_k) fs = np.zeros(len(ks)) # Special case K=1 fs[0], Sk = _fK(1) # Rest of Ks for k in ks[1:]: fs[k-1], Sk = _fK(k, Skm1=Sk) return np.argmin(fs) + 1
[ "def", "estimate_k", "(", "X", ",", "max_k", ")", ":", "ks", "=", "range", "(", "1", ",", "max_k", ")", "fs", "=", "np", ".", "zeros", "(", "len", "(", "ks", ")", ")", "# Special case K=1", "fs", "[", "0", "]", ",", "Sk", "=", "_fK", "(", "1"...
Estimate k for K-Means. Adapted from <https://datasciencelab.wordpress.com/2014/01/21/selection-of-k-in-k-means-clustering-reloaded/>
[ "Estimate", "k", "for", "K", "-", "Means", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/cluster/parameter.py#L35-L51
darkfeline/animanager
animanager/db/query/select.py
_clean_fields
def _clean_fields(allowed_fields: dict, fields: FieldsParam) -> Iterable[str]: """Clean lookup fields and check for errors.""" if fields == ALL: fields = allowed_fields.keys() else: fields = tuple(fields) unknown_fields = set(fields) - allowed_fields.keys() if unknown_fields: raise ValueError('Unknown fields: {}'.format(unknown_fields)) return fields
python
def _clean_fields(allowed_fields: dict, fields: FieldsParam) -> Iterable[str]: """Clean lookup fields and check for errors.""" if fields == ALL: fields = allowed_fields.keys() else: fields = tuple(fields) unknown_fields = set(fields) - allowed_fields.keys() if unknown_fields: raise ValueError('Unknown fields: {}'.format(unknown_fields)) return fields
[ "def", "_clean_fields", "(", "allowed_fields", ":", "dict", ",", "fields", ":", "FieldsParam", ")", "->", "Iterable", "[", "str", "]", ":", "if", "fields", "==", "ALL", ":", "fields", "=", "allowed_fields", ".", "keys", "(", ")", "else", ":", "fields", ...
Clean lookup fields and check for errors.
[ "Clean", "lookup", "fields", "and", "check", "for", "errors", "." ]
train
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/db/query/select.py#L56-L65
darkfeline/animanager
animanager/db/query/select.py
select
def select( db, where_query: str, where_params: SQLParams, fields: FieldsParam = ALL, episode_fields: FieldsParam = (), ) -> Iterator[Anime]: """Perform an arbitrary SQL SELECT WHERE on the anime table. By nature of "arbitrary query", this is vulnerable to injection, use only trusted values for `where_query`. This will "lazily" fetch the requested fields as needed. For example, episodes (which require a separate query per anime) will only be fetched if `episode_fields` is provided. Anime status will be cached only if status fields are requested. :param str where_query: SELECT WHERE query :param where_params: parameters for WHERE query :param fields: anime fields to get. If :const:`ALL`, get all fields. Default is :const:`ALL`. :param episode_fields: episode fields to get. If :const:`ALL`, get all fields. If empty, don't get episodes. `fields` must contain 'aid' to get episodes. :param bool force_status: whether to force status calculation. :returns: iterator of Anime """ logger.debug( 'select(%r, %r, %r, %r, %r)', db, where_query, where_params, fields, episode_fields) fields = _clean_fields(ANIME_FIELDS, fields) if not fields: raise ValueError('Fields cannot be empty') if set(fields) & STATUS_FIELDS.keys(): cur = db.cursor().execute( ANIME_QUERY.format('aid', where_query), where_params) for row in cur: cache_status(db, row[0]) if 'aid' in fields: episode_fields = _clean_fields(EPISODE_FIELDS, episode_fields) else: episode_fields = () with db: anime_query = ANIME_QUERY.format( ','.join(ANIME_FIELDS[field] for field in fields), where_query, ) anime_rows = db.cursor().execute(anime_query, where_params) for row in anime_rows: anime = Anime(**{ field: value for field, value in zip(fields, row)}) if episode_fields: episode_query = 'SELECT {} FROM episode WHERE aid=?' episode_query = episode_query.format( ','.join(EPISODE_FIELDS[field] for field in episode_fields)) episode_rows = db.cursor().execute(episode_query, (anime.aid,)) episodes = [ Episode(**{ field: value for field, value in zip(episode_fields, row)}) for row in episode_rows] anime.episodes = episodes yield anime
python
def select( db, where_query: str, where_params: SQLParams, fields: FieldsParam = ALL, episode_fields: FieldsParam = (), ) -> Iterator[Anime]: """Perform an arbitrary SQL SELECT WHERE on the anime table. By nature of "arbitrary query", this is vulnerable to injection, use only trusted values for `where_query`. This will "lazily" fetch the requested fields as needed. For example, episodes (which require a separate query per anime) will only be fetched if `episode_fields` is provided. Anime status will be cached only if status fields are requested. :param str where_query: SELECT WHERE query :param where_params: parameters for WHERE query :param fields: anime fields to get. If :const:`ALL`, get all fields. Default is :const:`ALL`. :param episode_fields: episode fields to get. If :const:`ALL`, get all fields. If empty, don't get episodes. `fields` must contain 'aid' to get episodes. :param bool force_status: whether to force status calculation. :returns: iterator of Anime """ logger.debug( 'select(%r, %r, %r, %r, %r)', db, where_query, where_params, fields, episode_fields) fields = _clean_fields(ANIME_FIELDS, fields) if not fields: raise ValueError('Fields cannot be empty') if set(fields) & STATUS_FIELDS.keys(): cur = db.cursor().execute( ANIME_QUERY.format('aid', where_query), where_params) for row in cur: cache_status(db, row[0]) if 'aid' in fields: episode_fields = _clean_fields(EPISODE_FIELDS, episode_fields) else: episode_fields = () with db: anime_query = ANIME_QUERY.format( ','.join(ANIME_FIELDS[field] for field in fields), where_query, ) anime_rows = db.cursor().execute(anime_query, where_params) for row in anime_rows: anime = Anime(**{ field: value for field, value in zip(fields, row)}) if episode_fields: episode_query = 'SELECT {} FROM episode WHERE aid=?' episode_query = episode_query.format( ','.join(EPISODE_FIELDS[field] for field in episode_fields)) episode_rows = db.cursor().execute(episode_query, (anime.aid,)) episodes = [ Episode(**{ field: value for field, value in zip(episode_fields, row)}) for row in episode_rows] anime.episodes = episodes yield anime
[ "def", "select", "(", "db", ",", "where_query", ":", "str", ",", "where_params", ":", "SQLParams", ",", "fields", ":", "FieldsParam", "=", "ALL", ",", "episode_fields", ":", "FieldsParam", "=", "(", ")", ",", ")", "->", "Iterator", "[", "Anime", "]", "...
Perform an arbitrary SQL SELECT WHERE on the anime table. By nature of "arbitrary query", this is vulnerable to injection, use only trusted values for `where_query`. This will "lazily" fetch the requested fields as needed. For example, episodes (which require a separate query per anime) will only be fetched if `episode_fields` is provided. Anime status will be cached only if status fields are requested. :param str where_query: SELECT WHERE query :param where_params: parameters for WHERE query :param fields: anime fields to get. If :const:`ALL`, get all fields. Default is :const:`ALL`. :param episode_fields: episode fields to get. If :const:`ALL`, get all fields. If empty, don't get episodes. `fields` must contain 'aid' to get episodes. :param bool force_status: whether to force status calculation. :returns: iterator of Anime
[ "Perform", "an", "arbitrary", "SQL", "SELECT", "WHERE", "on", "the", "anime", "table", "." ]
train
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/db/query/select.py#L76-L147
darkfeline/animanager
animanager/db/query/select.py
lookup
def lookup( db, aid: int, fields: FieldsParam = ALL, episode_fields: FieldsParam = (), ) -> Anime: """Look up information for a single anime. :param fields: anime fields to get. If ``None``, get all fields. :param episode_fields: episode fields to get. If ``None``, get all fields. If empty, don't get episodes. """ return next(select( db, 'aid=?', (aid,), fields=fields, episode_fields=episode_fields, ))
python
def lookup( db, aid: int, fields: FieldsParam = ALL, episode_fields: FieldsParam = (), ) -> Anime: """Look up information for a single anime. :param fields: anime fields to get. If ``None``, get all fields. :param episode_fields: episode fields to get. If ``None``, get all fields. If empty, don't get episodes. """ return next(select( db, 'aid=?', (aid,), fields=fields, episode_fields=episode_fields, ))
[ "def", "lookup", "(", "db", ",", "aid", ":", "int", ",", "fields", ":", "FieldsParam", "=", "ALL", ",", "episode_fields", ":", "FieldsParam", "=", "(", ")", ",", ")", "->", "Anime", ":", "return", "next", "(", "select", "(", "db", ",", "'aid=?'", "...
Look up information for a single anime. :param fields: anime fields to get. If ``None``, get all fields. :param episode_fields: episode fields to get. If ``None``, get all fields. If empty, don't get episodes.
[ "Look", "up", "information", "for", "a", "single", "anime", "." ]
train
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/db/query/select.py#L150-L169
coordt/django-alphabetfilter
alphafilter/templatetags/alphafilter.py
_get_default_letters
def _get_default_letters(model_admin=None): """ Returns the set of letters defined in the configuration variable DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or list and returns a set. If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET attribute and use it instead. """ from django.conf import settings import string default_ltrs = string.digits + string.ascii_uppercase default_letters = getattr(settings, 'DEFAULT_ALPHABET', default_ltrs) if model_admin and hasattr(model_admin, 'DEFAULT_ALPHABET'): default_letters = model_admin.DEFAULT_ALPHABET if callable(default_letters): return set(default_letters()) elif isinstance(default_letters, str): return set([x for x in default_letters]) elif isinstance(default_letters, str): return set([x for x in default_letters.decode('utf8')]) elif isinstance(default_letters, (tuple, list)): return set(default_letters)
python
def _get_default_letters(model_admin=None): """ Returns the set of letters defined in the configuration variable DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or list and returns a set. If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET attribute and use it instead. """ from django.conf import settings import string default_ltrs = string.digits + string.ascii_uppercase default_letters = getattr(settings, 'DEFAULT_ALPHABET', default_ltrs) if model_admin and hasattr(model_admin, 'DEFAULT_ALPHABET'): default_letters = model_admin.DEFAULT_ALPHABET if callable(default_letters): return set(default_letters()) elif isinstance(default_letters, str): return set([x for x in default_letters]) elif isinstance(default_letters, str): return set([x for x in default_letters.decode('utf8')]) elif isinstance(default_letters, (tuple, list)): return set(default_letters)
[ "def", "_get_default_letters", "(", "model_admin", "=", "None", ")", ":", "from", "django", ".", "conf", "import", "settings", "import", "string", "default_ltrs", "=", "string", ".", "digits", "+", "string", ".", "ascii_uppercase", "default_letters", "=", "getat...
Returns the set of letters defined in the configuration variable DEFAULT_ALPHABET. DEFAULT_ALPHABET can be a callable, string, tuple, or list and returns a set. If a ModelAdmin class is passed, it will look for a DEFAULT_ALPHABET attribute and use it instead.
[ "Returns", "the", "set", "of", "letters", "defined", "in", "the", "configuration", "variable", "DEFAULT_ALPHABET", ".", "DEFAULT_ALPHABET", "can", "be", "a", "callable", "string", "tuple", "or", "list", "and", "returns", "a", "set", "." ]
train
https://github.com/coordt/django-alphabetfilter/blob/a7bc21c0ea985c2021a4668241bf643c615c6c1f/alphafilter/templatetags/alphafilter.py#L13-L35
coordt/django-alphabetfilter
alphafilter/templatetags/alphafilter.py
_get_available_letters
def _get_available_letters(field_name, queryset): """ Makes a query to the database to return the first character of each value of the field and table passed in. Returns a set that represents the letters that exist in the database. """ if django.VERSION[1] <= 4: result = queryset.values(field_name).annotate( fl=FirstLetter(field_name) ).values('fl').distinct() return set([res['fl'] for res in result if res['fl'] is not None]) else: from django.db import connection qn = connection.ops.quote_name db_table = queryset.model._meta.db_table sql = "SELECT DISTINCT UPPER(SUBSTR(%s, 1, 1)) as letter FROM %s" % (qn(field_name), qn(db_table)) cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() or () return set([row[0] for row in rows if row[0] is not None])
python
def _get_available_letters(field_name, queryset): """ Makes a query to the database to return the first character of each value of the field and table passed in. Returns a set that represents the letters that exist in the database. """ if django.VERSION[1] <= 4: result = queryset.values(field_name).annotate( fl=FirstLetter(field_name) ).values('fl').distinct() return set([res['fl'] for res in result if res['fl'] is not None]) else: from django.db import connection qn = connection.ops.quote_name db_table = queryset.model._meta.db_table sql = "SELECT DISTINCT UPPER(SUBSTR(%s, 1, 1)) as letter FROM %s" % (qn(field_name), qn(db_table)) cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() or () return set([row[0] for row in rows if row[0] is not None])
[ "def", "_get_available_letters", "(", "field_name", ",", "queryset", ")", ":", "if", "django", ".", "VERSION", "[", "1", "]", "<=", "4", ":", "result", "=", "queryset", ".", "values", "(", "field_name", ")", ".", "annotate", "(", "fl", "=", "FirstLetter"...
Makes a query to the database to return the first character of each value of the field and table passed in. Returns a set that represents the letters that exist in the database.
[ "Makes", "a", "query", "to", "the", "database", "to", "return", "the", "first", "character", "of", "each", "value", "of", "the", "field", "and", "table", "passed", "in", "." ]
train
https://github.com/coordt/django-alphabetfilter/blob/a7bc21c0ea985c2021a4668241bf643c615c6c1f/alphafilter/templatetags/alphafilter.py#L38-L58
coordt/django-alphabetfilter
alphafilter/templatetags/alphafilter.py
alphabet
def alphabet(cl): """ The inclusion tag that renders the admin/alphabet.html template in the admin. Accepts a ChangeList object, which is custom to the admin. """ if not getattr(cl.model_admin, 'alphabet_filter', False): return field_name = cl.model_admin.alphabet_filter alpha_field = '%s__istartswith' % field_name alpha_lookup = cl.params.get(alpha_field, '') letters_used = _get_available_letters(field_name, cl.model.objects.all()) all_letters = list(_get_default_letters(cl.model_admin) | letters_used) all_letters.sort() choices = [{ 'link': cl.get_query_string({alpha_field: letter}), 'title': letter, 'active': letter == alpha_lookup, 'has_entries': letter in letters_used, } for letter in all_letters] all_letters = [{ 'link': cl.get_query_string(None, [alpha_field]), 'title': _('All'), 'active': '' == alpha_lookup, 'has_entries': True }, ] return {'choices': all_letters + choices}
python
def alphabet(cl): """ The inclusion tag that renders the admin/alphabet.html template in the admin. Accepts a ChangeList object, which is custom to the admin. """ if not getattr(cl.model_admin, 'alphabet_filter', False): return field_name = cl.model_admin.alphabet_filter alpha_field = '%s__istartswith' % field_name alpha_lookup = cl.params.get(alpha_field, '') letters_used = _get_available_letters(field_name, cl.model.objects.all()) all_letters = list(_get_default_letters(cl.model_admin) | letters_used) all_letters.sort() choices = [{ 'link': cl.get_query_string({alpha_field: letter}), 'title': letter, 'active': letter == alpha_lookup, 'has_entries': letter in letters_used, } for letter in all_letters] all_letters = [{ 'link': cl.get_query_string(None, [alpha_field]), 'title': _('All'), 'active': '' == alpha_lookup, 'has_entries': True }, ] return {'choices': all_letters + choices}
[ "def", "alphabet", "(", "cl", ")", ":", "if", "not", "getattr", "(", "cl", ".", "model_admin", ",", "'alphabet_filter'", ",", "False", ")", ":", "return", "field_name", "=", "cl", ".", "model_admin", ".", "alphabet_filter", "alpha_field", "=", "'%s__istartsw...
The inclusion tag that renders the admin/alphabet.html template in the admin. Accepts a ChangeList object, which is custom to the admin.
[ "The", "inclusion", "tag", "that", "renders", "the", "admin", "/", "alphabet", ".", "html", "template", "in", "the", "admin", ".", "Accepts", "a", "ChangeList", "object", "which", "is", "custom", "to", "the", "admin", "." ]
train
https://github.com/coordt/django-alphabetfilter/blob/a7bc21c0ea985c2021a4668241bf643c615c6c1f/alphafilter/templatetags/alphafilter.py#L61-L87
coordt/django-alphabetfilter
alphafilter/templatetags/alphafilter.py
qs_alphabet_filter
def qs_alphabet_filter(parser, token): """ The parser/tokenizer for the queryset alphabet filter. {% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %} {% qs_alphabet_filter objects lastname myapp/template.html %} The template name is optional and uses alphafilter/alphabet.html if not specified """ bits = token.split_contents() if len(bits) == 3: return AlphabetFilterNode(bits[1], bits[2]) elif len(bits) == 4: if "=" in bits[3]: key, val = bits[3].split('=') return AlphabetFilterNode(bits[1], bits[2], strip_params=val) else: return AlphabetFilterNode(bits[1], bits[2], template_name=bits[3]) elif len(bits) == 5: key, val = bits[4].split('=') return AlphabetFilterNode(bits[1], bits[2], bits[3], bits[4]) else: raise TemplateSyntaxError("%s is called with a queryset and field " "name, and optionally a template." % bits[0])
python
def qs_alphabet_filter(parser, token): """ The parser/tokenizer for the queryset alphabet filter. {% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %} {% qs_alphabet_filter objects lastname myapp/template.html %} The template name is optional and uses alphafilter/alphabet.html if not specified """ bits = token.split_contents() if len(bits) == 3: return AlphabetFilterNode(bits[1], bits[2]) elif len(bits) == 4: if "=" in bits[3]: key, val = bits[3].split('=') return AlphabetFilterNode(bits[1], bits[2], strip_params=val) else: return AlphabetFilterNode(bits[1], bits[2], template_name=bits[3]) elif len(bits) == 5: key, val = bits[4].split('=') return AlphabetFilterNode(bits[1], bits[2], bits[3], bits[4]) else: raise TemplateSyntaxError("%s is called with a queryset and field " "name, and optionally a template." % bits[0])
[ "def", "qs_alphabet_filter", "(", "parser", ",", "token", ")", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "if", "len", "(", "bits", ")", "==", "3", ":", "return", "AlphabetFilterNode", "(", "bits", "[", "1", "]", ",", "bits", "[", "2...
The parser/tokenizer for the queryset alphabet filter. {% qs_alphabet_filter <queryset> <field name> [<template name>] [strip_params=comma,delim,list] %} {% qs_alphabet_filter objects lastname myapp/template.html %} The template name is optional and uses alphafilter/alphabet.html if not specified
[ "The", "parser", "/", "tokenizer", "for", "the", "queryset", "alphabet", "filter", "." ]
train
https://github.com/coordt/django-alphabetfilter/blob/a7bc21c0ea985c2021a4668241bf643c615c6c1f/alphafilter/templatetags/alphafilter.py#L177-L202
wglass/lighthouse
lighthouse/pluggable.py
Pluggable.get_installed_classes
def get_installed_classes(cls): """ Iterates over installed plugins associated with the `entry_point` and returns a dictionary of viable ones keyed off of their names. A viable installed plugin is one that is both loadable *and* a subclass of the Pluggable subclass in question. """ installed_classes = {} for entry_point in pkg_resources.iter_entry_points(cls.entry_point): try: plugin = entry_point.load() except ImportError as e: logger.error( "Could not load plugin %s: %s", entry_point.name, str(e) ) continue if not issubclass(plugin, cls): logger.error( "Could not load plugin %s:" + " %s class is not subclass of %s", entry_point.name, plugin.__class__.__name__, cls.__name__ ) continue if not plugin.validate_dependencies(): logger.error( "Could not load plugin %s:" + " %s class dependencies not met", entry_point.name, plugin.__name__ ) continue installed_classes[entry_point.name] = plugin return installed_classes
python
def get_installed_classes(cls): """ Iterates over installed plugins associated with the `entry_point` and returns a dictionary of viable ones keyed off of their names. A viable installed plugin is one that is both loadable *and* a subclass of the Pluggable subclass in question. """ installed_classes = {} for entry_point in pkg_resources.iter_entry_points(cls.entry_point): try: plugin = entry_point.load() except ImportError as e: logger.error( "Could not load plugin %s: %s", entry_point.name, str(e) ) continue if not issubclass(plugin, cls): logger.error( "Could not load plugin %s:" + " %s class is not subclass of %s", entry_point.name, plugin.__class__.__name__, cls.__name__ ) continue if not plugin.validate_dependencies(): logger.error( "Could not load plugin %s:" + " %s class dependencies not met", entry_point.name, plugin.__name__ ) continue installed_classes[entry_point.name] = plugin return installed_classes
[ "def", "get_installed_classes", "(", "cls", ")", ":", "installed_classes", "=", "{", "}", "for", "entry_point", "in", "pkg_resources", ".", "iter_entry_points", "(", "cls", ".", "entry_point", ")", ":", "try", ":", "plugin", "=", "entry_point", ".", "load", ...
Iterates over installed plugins associated with the `entry_point` and returns a dictionary of viable ones keyed off of their names. A viable installed plugin is one that is both loadable *and* a subclass of the Pluggable subclass in question.
[ "Iterates", "over", "installed", "plugins", "associated", "with", "the", "entry_point", "and", "returns", "a", "dictionary", "of", "viable", "ones", "keyed", "off", "of", "their", "names", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/pluggable.py#L36-L72
wglass/lighthouse
lighthouse/pluggable.py
Pluggable.from_config
def from_config(cls, name, config): """ Behaves like the base Configurable class's `from_config()` except this makes sure that the `Pluggable` subclass with the given name is actually a properly installed plugin first. """ installed_classes = cls.get_installed_classes() if name not in installed_classes: raise ValueError("Unknown/unavailable %s" % cls.__name__.lower()) pluggable_class = installed_classes[name] pluggable_class.validate_config(config) instance = pluggable_class() if not instance.name: instance.name = name instance.apply_config(config) return instance
python
def from_config(cls, name, config): """ Behaves like the base Configurable class's `from_config()` except this makes sure that the `Pluggable` subclass with the given name is actually a properly installed plugin first. """ installed_classes = cls.get_installed_classes() if name not in installed_classes: raise ValueError("Unknown/unavailable %s" % cls.__name__.lower()) pluggable_class = installed_classes[name] pluggable_class.validate_config(config) instance = pluggable_class() if not instance.name: instance.name = name instance.apply_config(config) return instance
[ "def", "from_config", "(", "cls", ",", "name", ",", "config", ")", ":", "installed_classes", "=", "cls", ".", "get_installed_classes", "(", ")", "if", "name", "not", "in", "installed_classes", ":", "raise", "ValueError", "(", "\"Unknown/unavailable %s\"", "%", ...
Behaves like the base Configurable class's `from_config()` except this makes sure that the `Pluggable` subclass with the given name is actually a properly installed plugin first.
[ "Behaves", "like", "the", "base", "Configurable", "class", "s", "from_config", "()", "except", "this", "makes", "sure", "that", "the", "Pluggable", "subclass", "with", "the", "given", "name", "is", "actually", "a", "properly", "installed", "plugin", "first", "...
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/pluggable.py#L75-L95
wglass/lighthouse
lighthouse/configs/handler.py
ConfigFileChangeHandler.file_name
def file_name(self, event): """ Helper method for determining the basename of the affected file. """ name = os.path.basename(event.src_path) name = name.replace(".yaml", "") name = name.replace(".yml", "") return name
python
def file_name(self, event): """ Helper method for determining the basename of the affected file. """ name = os.path.basename(event.src_path) name = name.replace(".yaml", "") name = name.replace(".yml", "") return name
[ "def", "file_name", "(", "self", ",", "event", ")", ":", "name", "=", "os", ".", "path", ".", "basename", "(", "event", ".", "src_path", ")", "name", "=", "name", ".", "replace", "(", "\".yaml\"", ",", "\"\"", ")", "name", "=", "name", ".", "replac...
Helper method for determining the basename of the affected file.
[ "Helper", "method", "for", "determining", "the", "basename", "of", "the", "affected", "file", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/configs/handler.py#L35-L43
wglass/lighthouse
lighthouse/configs/handler.py
ConfigFileChangeHandler.on_created
def on_created(self, event): """ Newly created config file handler. Parses the file's yaml contents and creates a new instance of the target_class with the results. Fires the on_add callback with the new instance. """ if os.path.isdir(event.src_path): return logger.debug("File created: %s", event.src_path) name = self.file_name(event) try: result = self.target_class.from_config( name, yaml.load(open(event.src_path)) ) except Exception as e: logger.exception( "Error when loading new config file %s: %s", event.src_path, str(e) ) return if not result: return self.on_add(self.target_class, name, result)
python
def on_created(self, event): """ Newly created config file handler. Parses the file's yaml contents and creates a new instance of the target_class with the results. Fires the on_add callback with the new instance. """ if os.path.isdir(event.src_path): return logger.debug("File created: %s", event.src_path) name = self.file_name(event) try: result = self.target_class.from_config( name, yaml.load(open(event.src_path)) ) except Exception as e: logger.exception( "Error when loading new config file %s: %s", event.src_path, str(e) ) return if not result: return self.on_add(self.target_class, name, result)
[ "def", "on_created", "(", "self", ",", "event", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "event", ".", "src_path", ")", ":", "return", "logger", ".", "debug", "(", "\"File created: %s\"", ",", "event", ".", "src_path", ")", "name", "=", ...
Newly created config file handler. Parses the file's yaml contents and creates a new instance of the target_class with the results. Fires the on_add callback with the new instance.
[ "Newly", "created", "config", "file", "handler", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/configs/handler.py#L45-L74
wglass/lighthouse
lighthouse/configs/handler.py
ConfigFileChangeHandler.on_modified
def on_modified(self, event): """ Modified config file handler. If a config file is modified, the yaml contents are parsed and the new results are validated by the target class. Once validated, the new config is passed to the on_update callback. """ if os.path.isdir(event.src_path): return logger.debug("file modified: %s", event.src_path) name = self.file_name(event) try: config = yaml.load(open(event.src_path)) self.target_class.from_config(name, config) except Exception: logger.exception( "Error when loading updated config file %s", event.src_path, ) return self.on_update(self.target_class, name, config)
python
def on_modified(self, event): """ Modified config file handler. If a config file is modified, the yaml contents are parsed and the new results are validated by the target class. Once validated, the new config is passed to the on_update callback. """ if os.path.isdir(event.src_path): return logger.debug("file modified: %s", event.src_path) name = self.file_name(event) try: config = yaml.load(open(event.src_path)) self.target_class.from_config(name, config) except Exception: logger.exception( "Error when loading updated config file %s", event.src_path, ) return self.on_update(self.target_class, name, config)
[ "def", "on_modified", "(", "self", ",", "event", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "event", ".", "src_path", ")", ":", "return", "logger", ".", "debug", "(", "\"file modified: %s\"", ",", "event", ".", "src_path", ")", "name", "=", ...
Modified config file handler. If a config file is modified, the yaml contents are parsed and the new results are validated by the target class. Once validated, the new config is passed to the on_update callback.
[ "Modified", "config", "file", "handler", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/configs/handler.py#L76-L100
wglass/lighthouse
lighthouse/configs/handler.py
ConfigFileChangeHandler.on_deleted
def on_deleted(self, event): """ Deleted config file handler. Simply fires the on_delete callback with the name of the deleted item. """ logger.debug("file removed: %s", event.src_path) name = self.file_name(event) self.on_delete(self.target_class, name)
python
def on_deleted(self, event): """ Deleted config file handler. Simply fires the on_delete callback with the name of the deleted item. """ logger.debug("file removed: %s", event.src_path) name = self.file_name(event) self.on_delete(self.target_class, name)
[ "def", "on_deleted", "(", "self", ",", "event", ")", ":", "logger", ".", "debug", "(", "\"file removed: %s\"", ",", "event", ".", "src_path", ")", "name", "=", "self", ".", "file_name", "(", "event", ")", "self", ".", "on_delete", "(", "self", ".", "ta...
Deleted config file handler. Simply fires the on_delete callback with the name of the deleted item.
[ "Deleted", "config", "file", "handler", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/configs/handler.py#L102-L111
wglass/lighthouse
lighthouse/configs/handler.py
ConfigFileChangeHandler.on_moved
def on_moved(self, event): """ A move event is just proxied to an on_deleted call followed by an on_created call. """ self.on_deleted(events.FileDeletedEvent(event.src_path)) self.on_created(events.FileCreatedEvent(event.dest_path))
python
def on_moved(self, event): """ A move event is just proxied to an on_deleted call followed by an on_created call. """ self.on_deleted(events.FileDeletedEvent(event.src_path)) self.on_created(events.FileCreatedEvent(event.dest_path))
[ "def", "on_moved", "(", "self", ",", "event", ")", ":", "self", ".", "on_deleted", "(", "events", ".", "FileDeletedEvent", "(", "event", ".", "src_path", ")", ")", "self", ".", "on_created", "(", "events", ".", "FileCreatedEvent", "(", "event", ".", "des...
A move event is just proxied to an on_deleted call followed by an on_created call.
[ "A", "move", "event", "is", "just", "proxied", "to", "an", "on_deleted", "call", "followed", "by", "an", "on_created", "call", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/configs/handler.py#L113-L119
darkfeline/animanager
animanager/commands/asearch.py
command
def command(state, args): """Search AniDB.""" args = parser.parse_args(args[1:]) if not args.query: print('Must supply query.') return search_query = _compile_re_query(args.query) results = state.titles.search(search_query) results = [(anime.aid, anime.main_title) for anime in results] state.results['anidb'].set(results) state.results['anidb'].print()
python
def command(state, args): """Search AniDB.""" args = parser.parse_args(args[1:]) if not args.query: print('Must supply query.') return search_query = _compile_re_query(args.query) results = state.titles.search(search_query) results = [(anime.aid, anime.main_title) for anime in results] state.results['anidb'].set(results) state.results['anidb'].print()
[ "def", "command", "(", "state", ",", "args", ")", ":", "args", "=", "parser", ".", "parse_args", "(", "args", "[", "1", ":", "]", ")", "if", "not", "args", ".", "query", ":", "print", "(", "'Must supply query.'", ")", "return", "search_query", "=", "...
Search AniDB.
[ "Search", "AniDB", "." ]
train
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/commands/asearch.py#L24-L34
devries/bottle-session
bottle_session.py
Session.regenerate
def regenerate(self): """Regenerate the session id. This function creates a new session id and stores all information associated with the current id in that new id. It then destroys the old session id. This is useful for preventing session fixation attacks and should be done whenever someone uses a login to obtain additional authorizaiton. """ oldhash = self.session_hash self.new_session_id() try: self.rdb.rename(oldhash,self.session_hash) self.rdb.expire(self.session_hash,self.ttl) except: pass
python
def regenerate(self): """Regenerate the session id. This function creates a new session id and stores all information associated with the current id in that new id. It then destroys the old session id. This is useful for preventing session fixation attacks and should be done whenever someone uses a login to obtain additional authorizaiton. """ oldhash = self.session_hash self.new_session_id() try: self.rdb.rename(oldhash,self.session_hash) self.rdb.expire(self.session_hash,self.ttl) except: pass
[ "def", "regenerate", "(", "self", ")", ":", "oldhash", "=", "self", ".", "session_hash", "self", ".", "new_session_id", "(", ")", "try", ":", "self", ".", "rdb", ".", "rename", "(", "oldhash", ",", "self", ".", "session_hash", ")", "self", ".", "rdb", ...
Regenerate the session id. This function creates a new session id and stores all information associated with the current id in that new id. It then destroys the old session id. This is useful for preventing session fixation attacks and should be done whenever someone uses a login to obtain additional authorizaiton.
[ "Regenerate", "the", "session", "id", "." ]
train
https://github.com/devries/bottle-session/blob/aaa33eecbf977d6b2ad7d3835d2176f40b3231e5/bottle_session.py#L169-L185
devries/bottle-session
bottle_session.py
Session.get
def get(self,key,default=None): """Get a value from the dictionary. Args: key (str): The dictionary key. default (any): The default to return if the key is not in the dictionary. Defaults to None. Returns: str or any: The dictionary value or the default if the key is not in the dictionary. """ retval = self.__getitem__(key) if not retval: retval = default return retval
python
def get(self,key,default=None): """Get a value from the dictionary. Args: key (str): The dictionary key. default (any): The default to return if the key is not in the dictionary. Defaults to None. Returns: str or any: The dictionary value or the default if the key is not in the dictionary. """ retval = self.__getitem__(key) if not retval: retval = default return retval
[ "def", "get", "(", "self", ",", "key", ",", "default", "=", "None", ")", ":", "retval", "=", "self", ".", "__getitem__", "(", "key", ")", "if", "not", "retval", ":", "retval", "=", "default", "return", "retval" ]
Get a value from the dictionary. Args: key (str): The dictionary key. default (any): The default to return if the key is not in the dictionary. Defaults to None. Returns: str or any: The dictionary value or the default if the key is not in the dictionary.
[ "Get", "a", "value", "from", "the", "dictionary", "." ]
train
https://github.com/devries/bottle-session/blob/aaa33eecbf977d6b2ad7d3835d2176f40b3231e5/bottle_session.py#L254-L271
devries/bottle-session
bottle_session.py
Session.items
def items(self): """Return a list of all the key, value pair tuples in the dictionary. Returns: list of tuples: [(key1,value1),(key2,value2),...,(keyN,valueN)] """ all_items = [(k.decode('utf-8'),v.decode('utf-8')) for k,v in self.rdb.hgetall(self.session_hash).items()] return all_items
python
def items(self): """Return a list of all the key, value pair tuples in the dictionary. Returns: list of tuples: [(key1,value1),(key2,value2),...,(keyN,valueN)] """ all_items = [(k.decode('utf-8'),v.decode('utf-8')) for k,v in self.rdb.hgetall(self.session_hash).items()] return all_items
[ "def", "items", "(", "self", ")", ":", "all_items", "=", "[", "(", "k", ".", "decode", "(", "'utf-8'", ")", ",", "v", ".", "decode", "(", "'utf-8'", ")", ")", "for", "k", ",", "v", "in", "self", ".", "rdb", ".", "hgetall", "(", "self", ".", "...
Return a list of all the key, value pair tuples in the dictionary. Returns: list of tuples: [(key1,value1),(key2,value2),...,(keyN,valueN)]
[ "Return", "a", "list", "of", "all", "the", "key", "value", "pair", "tuples", "in", "the", "dictionary", "." ]
train
https://github.com/devries/bottle-session/blob/aaa33eecbf977d6b2ad7d3835d2176f40b3231e5/bottle_session.py#L284-L291
devries/bottle-session
bottle_session.py
Session.keys
def keys(self): """Return a list of all keys in the dictionary. Returns: list of str: [key1,key2,...,keyN] """ all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_keys
python
def keys(self): """Return a list of all keys in the dictionary. Returns: list of str: [key1,key2,...,keyN] """ all_keys = [k.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_keys
[ "def", "keys", "(", "self", ")", ":", "all_keys", "=", "[", "k", ".", "decode", "(", "'utf-8'", ")", "for", "k", ",", "v", "in", "self", ".", "rdb", ".", "hgetall", "(", "self", ".", "session_hash", ")", ".", "items", "(", ")", "]", "return", "...
Return a list of all keys in the dictionary. Returns: list of str: [key1,key2,...,keyN]
[ "Return", "a", "list", "of", "all", "keys", "in", "the", "dictionary", "." ]
train
https://github.com/devries/bottle-session/blob/aaa33eecbf977d6b2ad7d3835d2176f40b3231e5/bottle_session.py#L293-L300
devries/bottle-session
bottle_session.py
Session.values
def values(self): """Returns a list of all values in the dictionary. Returns: list of str: [value1,value2,...,valueN] """ all_values = [v.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_values
python
def values(self): """Returns a list of all values in the dictionary. Returns: list of str: [value1,value2,...,valueN] """ all_values = [v.decode('utf-8') for k,v in self.rdb.hgetall(self.session_hash).items()] return all_values
[ "def", "values", "(", "self", ")", ":", "all_values", "=", "[", "v", ".", "decode", "(", "'utf-8'", ")", "for", "k", ",", "v", "in", "self", ".", "rdb", ".", "hgetall", "(", "self", ".", "session_hash", ")", ".", "items", "(", ")", "]", "return",...
Returns a list of all values in the dictionary. Returns: list of str: [value1,value2,...,valueN]
[ "Returns", "a", "list", "of", "all", "values", "in", "the", "dictionary", "." ]
train
https://github.com/devries/bottle-session/blob/aaa33eecbf977d6b2ad7d3835d2176f40b3231e5/bottle_session.py#L302-L309
rdireen/spherepy
spherepy/sbessel.py
sbessely
def sbessely(x, N): """Returns a vector of spherical bessel functions yn: x: The argument. N: values of n will run from 0 to N-1. """ out = np.zeros(N, dtype=np.float64) out[0] = -np.cos(x) / x out[1] = -np.cos(x) / (x ** 2) - np.sin(x) / x for n in xrange(2, N): out[n] = ((2.0 * n - 1.0) / x) * out[n - 1] - out[n - 2] return out
python
def sbessely(x, N): """Returns a vector of spherical bessel functions yn: x: The argument. N: values of n will run from 0 to N-1. """ out = np.zeros(N, dtype=np.float64) out[0] = -np.cos(x) / x out[1] = -np.cos(x) / (x ** 2) - np.sin(x) / x for n in xrange(2, N): out[n] = ((2.0 * n - 1.0) / x) * out[n - 1] - out[n - 2] return out
[ "def", "sbessely", "(", "x", ",", "N", ")", ":", "out", "=", "np", ".", "zeros", "(", "N", ",", "dtype", "=", "np", ".", "float64", ")", "out", "[", "0", "]", "=", "-", "np", ".", "cos", "(", "x", ")", "/", "x", "out", "[", "1", "]", "=...
Returns a vector of spherical bessel functions yn: x: The argument. N: values of n will run from 0 to N-1.
[ "Returns", "a", "vector", "of", "spherical", "bessel", "functions", "yn", ":", "x", ":", "The", "argument", ".", "N", ":", "values", "of", "n", "will", "run", "from", "0", "to", "N", "-", "1", "." ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/sbessel.py#L49-L65
rdireen/spherepy
spherepy/sbessel.py
sbesselj
def sbesselj(x, N): """Returns a vector of spherical bessel functions jn: x: The argument. N: values of n will run from 0 to N-1. """ nmax = N - 1; out = np.zeros(N, dtype=np.float64) z = x ** 2 out[0] = np.sin(x) / x j1 = np.sin(x) / z - np.cos(x) / x u = 1 v = x / (2.0 * nmax + 1.0) w = v n = nmax while(np.abs(v / w) > 1e-20): n = n + 1 u = 1 / (1 - z * u / (4.0 * n ** 2 - 1.0)) v *= u - 1 w += v out[nmax] = w for n in xrange(nmax - 1, 0, -1): out[n] = 1.0 / ((2.0 * n + 1.0) / x - out[n + 1]) if(np.abs(out[0]) >= np.abs(j1)): out[1] *= out[0] else: out[1] = j1 for n in xrange(1, nmax): out[n + 1] *= out[n] return out
python
def sbesselj(x, N): """Returns a vector of spherical bessel functions jn: x: The argument. N: values of n will run from 0 to N-1. """ nmax = N - 1; out = np.zeros(N, dtype=np.float64) z = x ** 2 out[0] = np.sin(x) / x j1 = np.sin(x) / z - np.cos(x) / x u = 1 v = x / (2.0 * nmax + 1.0) w = v n = nmax while(np.abs(v / w) > 1e-20): n = n + 1 u = 1 / (1 - z * u / (4.0 * n ** 2 - 1.0)) v *= u - 1 w += v out[nmax] = w for n in xrange(nmax - 1, 0, -1): out[n] = 1.0 / ((2.0 * n + 1.0) / x - out[n + 1]) if(np.abs(out[0]) >= np.abs(j1)): out[1] *= out[0] else: out[1] = j1 for n in xrange(1, nmax): out[n + 1] *= out[n] return out
[ "def", "sbesselj", "(", "x", ",", "N", ")", ":", "nmax", "=", "N", "-", "1", "out", "=", "np", ".", "zeros", "(", "N", ",", "dtype", "=", "np", ".", "float64", ")", "z", "=", "x", "**", "2", "out", "[", "0", "]", "=", "np", ".", "sin", ...
Returns a vector of spherical bessel functions jn: x: The argument. N: values of n will run from 0 to N-1.
[ "Returns", "a", "vector", "of", "spherical", "bessel", "functions", "jn", ":", "x", ":", "The", "argument", ".", "N", ":", "values", "of", "n", "will", "run", "from", "0", "to", "N", "-", "1", "." ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/sbessel.py#L67-L106
rdireen/spherepy
spherepy/sbessel.py
sbesselh1
def sbesselh1(x, N): "Spherical Hankel of the first kind" jn = sbesselj(x, N) yn = sbessely(x, N) return jn + 1j * yn
python
def sbesselh1(x, N): "Spherical Hankel of the first kind" jn = sbesselj(x, N) yn = sbessely(x, N) return jn + 1j * yn
[ "def", "sbesselh1", "(", "x", ",", "N", ")", ":", "jn", "=", "sbesselj", "(", "x", ",", "N", ")", "yn", "=", "sbessely", "(", "x", ",", "N", ")", "return", "jn", "+", "1j", "*", "yn" ]
Spherical Hankel of the first kind
[ "Spherical", "Hankel", "of", "the", "first", "kind" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/sbessel.py#L108-L114
rdireen/spherepy
spherepy/sbessel.py
sbesselh2
def sbesselh2(x, N): "Spherical Hankel of the second kind" jn = sbesselj(x, N) yn = sbessely(x, N) return jn - 1j * yn
python
def sbesselh2(x, N): "Spherical Hankel of the second kind" jn = sbesselj(x, N) yn = sbessely(x, N) return jn - 1j * yn
[ "def", "sbesselh2", "(", "x", ",", "N", ")", ":", "jn", "=", "sbesselj", "(", "x", ",", "N", ")", "yn", "=", "sbessely", "(", "x", ",", "N", ")", "return", "jn", "-", "1j", "*", "yn" ]
Spherical Hankel of the second kind
[ "Spherical", "Hankel", "of", "the", "second", "kind" ]
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/sbessel.py#L116-L122
rdireen/spherepy
spherepy/sbessel.py
sbesselj_array
def sbesselj_array(xvec, N): """Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) show() """ first_time = True for x in xvec: a = sbesselj(x, N) if first_time: out = np.array([a]) first_time = False else: out = np.concatenate([out, [a]], axis=0) return out.T
python
def sbesselj_array(xvec, N): """Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) show() """ first_time = True for x in xvec: a = sbesselj(x, N) if first_time: out = np.array([a]) first_time = False else: out = np.concatenate([out, [a]], axis=0) return out.T
[ "def", "sbesselj_array", "(", "xvec", ",", "N", ")", ":", "first_time", "=", "True", "for", "x", "in", "xvec", ":", "a", "=", "sbesselj", "(", "x", ",", "N", ")", "if", "first_time", ":", "out", "=", "np", ".", "array", "(", "[", "a", "]", ")",...
Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) show()
[ "Outputs", "an", "array", "where", "each", "column", "is", "a", "vector", "of", "sbessel", "values", ".", "This", "is", "useful", "for", "plotting", "a", "set", "of", "Spherical", "Bessel", "Functions", ":", "A", "=", "sbessel", ".", "sbessely_array", "(",...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/sbessel.py#L128-L147
rdireen/spherepy
spherepy/sbessel.py
sbessely_array
def sbessely_array(xvec, N): """Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) ylim((-.4,.4)) show() """ first_time = True for x in xvec: a = sbessely(x, N) if first_time: out = np.array([a]) first_time = False else: out = np.concatenate([out, [a]], axis=0) return out.T
python
def sbessely_array(xvec, N): """Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) ylim((-.4,.4)) show() """ first_time = True for x in xvec: a = sbessely(x, N) if first_time: out = np.array([a]) first_time = False else: out = np.concatenate([out, [a]], axis=0) return out.T
[ "def", "sbessely_array", "(", "xvec", ",", "N", ")", ":", "first_time", "=", "True", "for", "x", "in", "xvec", ":", "a", "=", "sbessely", "(", "x", ",", "N", ")", "if", "first_time", ":", "out", "=", "np", ".", "array", "(", "[", "a", "]", ")",...
Outputs an array where each column is a vector of sbessel values. This is useful for plotting a set of Spherical Bessel Functions: A = sbessel.sbessely_array(np.linspace(.1,20,100),40) for sb in A: plot(sb) ylim((-.4,.4)) show()
[ "Outputs", "an", "array", "where", "each", "column", "is", "a", "vector", "of", "sbessel", "values", ".", "This", "is", "useful", "for", "plotting", "a", "set", "of", "Spherical", "Bessel", "Functions", ":", "A", "=", "sbessel", ".", "sbessely_array", "(",...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/sbessel.py#L149-L169
rdireen/spherepy
spherepy/sbessel.py
sbesselj_sum
def sbesselj_sum(z, N): """Tests the Spherical Bessel function jn using the sum: Inf sum (2*n+1) * jn(z)**2 = 1 n=0 z: The argument. N: Large N value that the sum runs too. Note that the sum only converges to 1 for large N value (i.e. N >> z). The routine returns the relative error of the assumption. """ b = sbesselj(z, N) vvv = 2.0 * np.array(range(0, N), dtype=np.float64) + 1.0 sm = np.sum(np.sort(vvv * (b ** 2))) return np.abs((sm - 1.0) / sm) + np.spacing(1)
python
def sbesselj_sum(z, N): """Tests the Spherical Bessel function jn using the sum: Inf sum (2*n+1) * jn(z)**2 = 1 n=0 z: The argument. N: Large N value that the sum runs too. Note that the sum only converges to 1 for large N value (i.e. N >> z). The routine returns the relative error of the assumption. """ b = sbesselj(z, N) vvv = 2.0 * np.array(range(0, N), dtype=np.float64) + 1.0 sm = np.sum(np.sort(vvv * (b ** 2))) return np.abs((sm - 1.0) / sm) + np.spacing(1)
[ "def", "sbesselj_sum", "(", "z", ",", "N", ")", ":", "b", "=", "sbesselj", "(", "z", ",", "N", ")", "vvv", "=", "2.0", "*", "np", ".", "array", "(", "range", "(", "0", ",", "N", ")", ",", "dtype", "=", "np", ".", "float64", ")", "+", "1.0",...
Tests the Spherical Bessel function jn using the sum: Inf sum (2*n+1) * jn(z)**2 = 1 n=0 z: The argument. N: Large N value that the sum runs too. Note that the sum only converges to 1 for large N value (i.e. N >> z). The routine returns the relative error of the assumption.
[ "Tests", "the", "Spherical", "Bessel", "function", "jn", "using", "the", "sum", ":", "Inf", "sum", "(", "2", "*", "n", "+", "1", ")", "*", "jn", "(", "z", ")", "**", "2", "=", "1", "n", "=", "0", "z", ":", "The", "argument", ".", "N", ":", ...
train
https://github.com/rdireen/spherepy/blob/241521401d4d76851d4a1a564a365cfab8e98496/spherepy/sbessel.py#L171-L190
frnsys/broca
broca/knowledge/util.py
merge
def merge(dicts): """ Merges a list of dicts, summing their values. (Parallelized wrapper around `_count`) """ chunks = [args for args in np.array_split(dicts, 20)] results = parallel(_count, chunks, n_jobs=-1) return _count(results)
python
def merge(dicts): """ Merges a list of dicts, summing their values. (Parallelized wrapper around `_count`) """ chunks = [args for args in np.array_split(dicts, 20)] results = parallel(_count, chunks, n_jobs=-1) return _count(results)
[ "def", "merge", "(", "dicts", ")", ":", "chunks", "=", "[", "args", "for", "args", "in", "np", ".", "array_split", "(", "dicts", ",", "20", ")", "]", "results", "=", "parallel", "(", "_count", ",", "chunks", ",", "n_jobs", "=", "-", "1", ")", "re...
Merges a list of dicts, summing their values. (Parallelized wrapper around `_count`)
[ "Merges", "a", "list", "of", "dicts", "summing", "their", "values", ".", "(", "Parallelized", "wrapper", "around", "_count", ")" ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/util.py#L8-L15
frnsys/broca
broca/knowledge/util.py
_count
def _count(dicts): """ Merge a list of dicts, summing their values. """ counts = defaultdict(int) for d in dicts: for k, v in d.items(): counts[k] += v return counts
python
def _count(dicts): """ Merge a list of dicts, summing their values. """ counts = defaultdict(int) for d in dicts: for k, v in d.items(): counts[k] += v return counts
[ "def", "_count", "(", "dicts", ")", ":", "counts", "=", "defaultdict", "(", "int", ")", "for", "d", "in", "dicts", ":", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "counts", "[", "k", "]", "+=", "v", "return", "counts" ]
Merge a list of dicts, summing their values.
[ "Merge", "a", "list", "of", "dicts", "summing", "their", "values", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/util.py#L18-L26
frnsys/broca
broca/knowledge/util.py
_chunks
def _chunks(iterable, n): """ Splits an iterable into chunks of size n. """ iterable = iter(iterable) while True: # store one line in memory, # chain it to an iterator on the rest of the chunk yield chain([next(iterable)], islice(iterable, n-1))
python
def _chunks(iterable, n): """ Splits an iterable into chunks of size n. """ iterable = iter(iterable) while True: # store one line in memory, # chain it to an iterator on the rest of the chunk yield chain([next(iterable)], islice(iterable, n-1))
[ "def", "_chunks", "(", "iterable", ",", "n", ")", ":", "iterable", "=", "iter", "(", "iterable", ")", "while", "True", ":", "# store one line in memory,", "# chain it to an iterator on the rest of the chunk", "yield", "chain", "(", "[", "next", "(", "iterable", ")...
Splits an iterable into chunks of size n.
[ "Splits", "an", "iterable", "into", "chunks", "of", "size", "n", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/util.py#L29-L37
frnsys/broca
broca/knowledge/util.py
split_file
def split_file(path, chunk_size=50000): """ Splits the specified file into smaller files. """ with open(path) as f: for i, lines in enumerate(_chunks(f, chunk_size)): file_split = '{}.{}'.format(os.path.basename(path), i) chunk_path = os.path.join('/tmp', file_split) with open(chunk_path, 'w') as f: f.writelines(lines) yield chunk_path
python
def split_file(path, chunk_size=50000): """ Splits the specified file into smaller files. """ with open(path) as f: for i, lines in enumerate(_chunks(f, chunk_size)): file_split = '{}.{}'.format(os.path.basename(path), i) chunk_path = os.path.join('/tmp', file_split) with open(chunk_path, 'w') as f: f.writelines(lines) yield chunk_path
[ "def", "split_file", "(", "path", ",", "chunk_size", "=", "50000", ")", ":", "with", "open", "(", "path", ")", "as", "f", ":", "for", "i", ",", "lines", "in", "enumerate", "(", "_chunks", "(", "f", ",", "chunk_size", ")", ")", ":", "file_split", "=...
Splits the specified file into smaller files.
[ "Splits", "the", "specified", "file", "into", "smaller", "files", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/util.py#L40-L50
frnsys/broca
broca/knowledge/util.py
doc_stream
def doc_stream(path): """ Generator to feed tokenized documents (treating each line as a document). """ with open(path, 'r') as f: for line in f: if line.strip(): yield line
python
def doc_stream(path): """ Generator to feed tokenized documents (treating each line as a document). """ with open(path, 'r') as f: for line in f: if line.strip(): yield line
[ "def", "doc_stream", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "for", "line", "in", "f", ":", "if", "line", ".", "strip", "(", ")", ":", "yield", "line" ]
Generator to feed tokenized documents (treating each line as a document).
[ "Generator", "to", "feed", "tokenized", "documents", "(", "treating", "each", "line", "as", "a", "document", ")", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/knowledge/util.py#L53-L60
wglass/lighthouse
lighthouse/haproxy/stanzas/stanza.py
Stanza.add_line
def add_line(self, line): """ Adds a given line string to the list of lines, validating the line first. """ if not self.is_valid_line(line): logger.warn( "Invalid line for %s section: '%s'", self.section_name, line ) return self.lines.append(line)
python
def add_line(self, line): """ Adds a given line string to the list of lines, validating the line first. """ if not self.is_valid_line(line): logger.warn( "Invalid line for %s section: '%s'", self.section_name, line ) return self.lines.append(line)
[ "def", "add_line", "(", "self", ",", "line", ")", ":", "if", "not", "self", ".", "is_valid_line", "(", "line", ")", ":", "logger", ".", "warn", "(", "\"Invalid line for %s section: '%s'\"", ",", "self", ".", "section_name", ",", "line", ")", "return", "sel...
Adds a given line string to the list of lines, validating the line first.
[ "Adds", "a", "given", "line", "string", "to", "the", "list", "of", "lines", "validating", "the", "line", "first", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/haproxy/stanzas/stanza.py#L36-L48
wglass/lighthouse
lighthouse/haproxy/stanzas/stanza.py
Stanza.is_valid_line
def is_valid_line(self, line): """ Validates a given line against the associated "section" (e.g. 'global' or 'frontend', etc.) of a stanza. If a line represents a directive that shouldn't be within the stanza it is rejected. See the `directives.json` file for a condensed look at valid directives based on section. """ adjusted_line = line.strip().lower() return any([ adjusted_line.startswith(directive) for directive in directives_by_section[self.section_name] ])
python
def is_valid_line(self, line): """ Validates a given line against the associated "section" (e.g. 'global' or 'frontend', etc.) of a stanza. If a line represents a directive that shouldn't be within the stanza it is rejected. See the `directives.json` file for a condensed look at valid directives based on section. """ adjusted_line = line.strip().lower() return any([ adjusted_line.startswith(directive) for directive in directives_by_section[self.section_name] ])
[ "def", "is_valid_line", "(", "self", ",", "line", ")", ":", "adjusted_line", "=", "line", ".", "strip", "(", ")", ".", "lower", "(", ")", "return", "any", "(", "[", "adjusted_line", ".", "startswith", "(", "directive", ")", "for", "directive", "in", "d...
Validates a given line against the associated "section" (e.g. 'global' or 'frontend', etc.) of a stanza. If a line represents a directive that shouldn't be within the stanza it is rejected. See the `directives.json` file for a condensed look at valid directives based on section.
[ "Validates", "a", "given", "line", "against", "the", "associated", "section", "(", "e", ".", "g", ".", "global", "or", "frontend", "etc", ".", ")", "of", "a", "stanza", "." ]
train
https://github.com/wglass/lighthouse/blob/f4ce6550895acc31e433ede0c05d366718a3ffe5/lighthouse/haproxy/stanzas/stanza.py#L50-L64
frnsys/broca
broca/tokenize/keyword/rake.py
load_stop_words
def load_stop_words(stop_word_file): """ Utility function to load stop words from a file and return as a list of words @param stop_word_file Path and file name of a file containing stop words. @return list A list of stop words. """ stop_words = [] for line in open(stop_word_file): if line.strip()[0:1] != "#": for word in line.split(): # in case more than one per line stop_words.append(word) return stop_words
python
def load_stop_words(stop_word_file): """ Utility function to load stop words from a file and return as a list of words @param stop_word_file Path and file name of a file containing stop words. @return list A list of stop words. """ stop_words = [] for line in open(stop_word_file): if line.strip()[0:1] != "#": for word in line.split(): # in case more than one per line stop_words.append(word) return stop_words
[ "def", "load_stop_words", "(", "stop_word_file", ")", ":", "stop_words", "=", "[", "]", "for", "line", "in", "open", "(", "stop_word_file", ")", ":", "if", "line", ".", "strip", "(", ")", "[", "0", ":", "1", "]", "!=", "\"#\"", ":", "for", "word", ...
Utility function to load stop words from a file and return as a list of words @param stop_word_file Path and file name of a file containing stop words. @return list A list of stop words.
[ "Utility", "function", "to", "load", "stop", "words", "from", "a", "file", "and", "return", "as", "a", "list", "of", "words" ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/tokenize/keyword/rake.py#L52-L63
frnsys/broca
broca/tokenize/keyword/rake.py
separate_words
def separate_words(text, min_word_return_size): """ Utility function to return a list of all words that are have a length greater than a specified number of characters. @param text The text that must be split in to words. @param min_word_return_size The minimum no of characters a word must have to be included. """ splitter = re.compile('[^a-zA-Z0-9_\\+\\-/]') words = [] for single_word in splitter.split(text): current_word = single_word.strip().lower() #leave numbers in phrase, but don't count as words, since they tend to invalidate scores of their phrases if len(current_word) > min_word_return_size and current_word != '' and not is_number(current_word): words.append(current_word) return words
python
def separate_words(text, min_word_return_size): """ Utility function to return a list of all words that are have a length greater than a specified number of characters. @param text The text that must be split in to words. @param min_word_return_size The minimum no of characters a word must have to be included. """ splitter = re.compile('[^a-zA-Z0-9_\\+\\-/]') words = [] for single_word in splitter.split(text): current_word = single_word.strip().lower() #leave numbers in phrase, but don't count as words, since they tend to invalidate scores of their phrases if len(current_word) > min_word_return_size and current_word != '' and not is_number(current_word): words.append(current_word) return words
[ "def", "separate_words", "(", "text", ",", "min_word_return_size", ")", ":", "splitter", "=", "re", ".", "compile", "(", "'[^a-zA-Z0-9_\\\\+\\\\-/]'", ")", "words", "=", "[", "]", "for", "single_word", "in", "splitter", ".", "split", "(", "text", ")", ":", ...
Utility function to return a list of all words that are have a length greater than a specified number of characters. @param text The text that must be split in to words. @param min_word_return_size The minimum no of characters a word must have to be included.
[ "Utility", "function", "to", "return", "a", "list", "of", "all", "words", "that", "are", "have", "a", "length", "greater", "than", "a", "specified", "number", "of", "characters", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/tokenize/keyword/rake.py#L66-L79
frnsys/broca
broca/tokenize/keyword/rake.py
split_sentences
def split_sentences(text): """ Utility function to return a list of sentences. @param text The text that must be split in to sentences. """ sentence_delimiters = re.compile(u'[\\[\\]\n.!?,;:\t\\-\\"\\(\\)\\\'\u2019\u2013]') sentences = sentence_delimiters.split(text) return sentences
python
def split_sentences(text): """ Utility function to return a list of sentences. @param text The text that must be split in to sentences. """ sentence_delimiters = re.compile(u'[\\[\\]\n.!?,;:\t\\-\\"\\(\\)\\\'\u2019\u2013]') sentences = sentence_delimiters.split(text) return sentences
[ "def", "split_sentences", "(", "text", ")", ":", "sentence_delimiters", "=", "re", ".", "compile", "(", "u'[\\\\[\\\\]\\n.!?,;:\\t\\\\-\\\\\"\\\\(\\\\)\\\\\\'\\u2019\\u2013]'", ")", "sentences", "=", "sentence_delimiters", ".", "split", "(", "text", ")", "return", "sent...
Utility function to return a list of sentences. @param text The text that must be split in to sentences.
[ "Utility", "function", "to", "return", "a", "list", "of", "sentences", "." ]
train
https://github.com/frnsys/broca/blob/7236dcf54edc0a4a54a55eb93be30800910667e7/broca/tokenize/keyword/rake.py#L82-L89
gkrsman/django-url-params
urlparams/redirect.py
param_redirect
def param_redirect(request, viewname, *args): """ Redirect and keep URL parameters if any. """ url = reverse(viewname, PARAMS_URL_CONF, args) params = request.GET.urlencode().split('&') if hasattr(request, 'cparam'): for k, v in request.cparam.items(): params.append('{0}={1}'.format(k, v)) new_params = '&'.join(x for x in params if x != '') if len(new_params) > 0: return HttpResponseRedirect('{0}?{1}'.format(url, new_params)) return HttpResponseRedirect(url)
python
def param_redirect(request, viewname, *args): """ Redirect and keep URL parameters if any. """ url = reverse(viewname, PARAMS_URL_CONF, args) params = request.GET.urlencode().split('&') if hasattr(request, 'cparam'): for k, v in request.cparam.items(): params.append('{0}={1}'.format(k, v)) new_params = '&'.join(x for x in params if x != '') if len(new_params) > 0: return HttpResponseRedirect('{0}?{1}'.format(url, new_params)) return HttpResponseRedirect(url)
[ "def", "param_redirect", "(", "request", ",", "viewname", ",", "*", "args", ")", ":", "url", "=", "reverse", "(", "viewname", ",", "PARAMS_URL_CONF", ",", "args", ")", "params", "=", "request", ".", "GET", ".", "urlencode", "(", ")", ".", "split", "(",...
Redirect and keep URL parameters if any.
[ "Redirect", "and", "keep", "URL", "parameters", "if", "any", "." ]
train
https://github.com/gkrsman/django-url-params/blob/d8ac56424e373331a1574f730a35d290ef6b2941/urlparams/redirect.py#L18-L30
Frojd/Fabrik
fabrik/ext/mysql.py
backup_db
def backup_db(release=None, limit=5): """ Backup database and associate it with current release """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mysql_db" in env, "Missing mysql_db in env" if not release: release = paths.get_current_release_name() max_versions = limit+1 if not release: return env.run("mkdir -p %s" % paths.get_backup_path("mysql")) backup_file = "mysql/%s.sql.gz" % release backup_path = paths.get_backup_path(backup_file) env.run("mysqldump -u %s -p%s -h %s %s | gzip -c > %s" % (env.mysql_user, env.mysql_password, env.mysql_host, env.mysql_db, backup_path)) # Remove older releases env.run("ls -dt %s/* | tail -n +%s | xargs rm -rf" % ( paths.get_backup_path("mysql"), max_versions) )
python
def backup_db(release=None, limit=5): """ Backup database and associate it with current release """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mysql_db" in env, "Missing mysql_db in env" if not release: release = paths.get_current_release_name() max_versions = limit+1 if not release: return env.run("mkdir -p %s" % paths.get_backup_path("mysql")) backup_file = "mysql/%s.sql.gz" % release backup_path = paths.get_backup_path(backup_file) env.run("mysqldump -u %s -p%s -h %s %s | gzip -c > %s" % (env.mysql_user, env.mysql_password, env.mysql_host, env.mysql_db, backup_path)) # Remove older releases env.run("ls -dt %s/* | tail -n +%s | xargs rm -rf" % ( paths.get_backup_path("mysql"), max_versions) )
[ "def", "backup_db", "(", "release", "=", "None", ",", "limit", "=", "5", ")", ":", "assert", "\"mysql_user\"", "in", "env", ",", "\"Missing mysqL_user in env\"", "assert", "\"mysql_password\"", "in", "env", ",", "\"Missing mysql_password in env\"", "assert", "\"mysq...
Backup database and associate it with current release
[ "Backup", "database", "and", "associate", "it", "with", "current", "release" ]
train
https://github.com/Frojd/Fabrik/blob/9f2edbba97a7fd236b72a9b3010f6e912ab5c001/fabrik/ext/mysql.py#L25-L56
Frojd/Fabrik
fabrik/ext/mysql.py
restore_db
def restore_db(release=None): """ Restores backup back to version, uses current version by default. """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mysql_db" in env, "Missing mysql_db in env" if not release: release = paths.get_current_release_name() if not release: raise Exception("Release %s was not found" % release) backup_file = "mysql/%s.sql.gz" % release backup_path = paths.get_backup_path(backup_file) if not env.exists(backup_path): raise Exception("Backup file %s not found" % backup_path) env.run("gunzip < %s | mysql -u %s -p%s -h %s %s" % (backup_path, env.mysql_user, env.mysql_password, env.mysql_host, env.mysql_db))
python
def restore_db(release=None): """ Restores backup back to version, uses current version by default. """ assert "mysql_user" in env, "Missing mysqL_user in env" assert "mysql_password" in env, "Missing mysql_password in env" assert "mysql_host" in env, "Missing mysql_host in env" assert "mysql_db" in env, "Missing mysql_db in env" if not release: release = paths.get_current_release_name() if not release: raise Exception("Release %s was not found" % release) backup_file = "mysql/%s.sql.gz" % release backup_path = paths.get_backup_path(backup_file) if not env.exists(backup_path): raise Exception("Backup file %s not found" % backup_path) env.run("gunzip < %s | mysql -u %s -p%s -h %s %s" % (backup_path, env.mysql_user, env.mysql_password, env.mysql_host, env.mysql_db))
[ "def", "restore_db", "(", "release", "=", "None", ")", ":", "assert", "\"mysql_user\"", "in", "env", ",", "\"Missing mysqL_user in env\"", "assert", "\"mysql_password\"", "in", "env", ",", "\"Missing mysql_password in env\"", "assert", "\"mysql_host\"", "in", "env", "...
Restores backup back to version, uses current version by default.
[ "Restores", "backup", "back", "to", "version", "uses", "current", "version", "by", "default", "." ]
train
https://github.com/Frojd/Fabrik/blob/9f2edbba97a7fd236b72a9b3010f6e912ab5c001/fabrik/ext/mysql.py#L60-L84
gbiggs/rtctree
rtctree/exec_context.py
ExecutionContext.kind_as_string
def kind_as_string(self, add_colour=True): '''Get the type of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing the kind of execution context this is. ''' with self._mutex: if self.kind == self.PERIODIC: result = 'Periodic', ['reset'] elif self.kind == self.EVENT_DRIVEN: result = 'Event-driven', ['reset'] elif self.kind == self.OTHER: result = 'Other', ['reset'] if add_colour: return utils.build_attr_string(result[1], supported=add_colour) + \ result[0] + utils.build_attr_string('reset', supported=add_colour) else: return result[0]
python
def kind_as_string(self, add_colour=True): '''Get the type of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing the kind of execution context this is. ''' with self._mutex: if self.kind == self.PERIODIC: result = 'Periodic', ['reset'] elif self.kind == self.EVENT_DRIVEN: result = 'Event-driven', ['reset'] elif self.kind == self.OTHER: result = 'Other', ['reset'] if add_colour: return utils.build_attr_string(result[1], supported=add_colour) + \ result[0] + utils.build_attr_string('reset', supported=add_colour) else: return result[0]
[ "def", "kind_as_string", "(", "self", ",", "add_colour", "=", "True", ")", ":", "with", "self", ".", "_mutex", ":", "if", "self", ".", "kind", "==", "self", ".", "PERIODIC", ":", "result", "=", "'Periodic'", ",", "[", "'reset'", "]", "elif", "self", ...
Get the type of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing the kind of execution context this is.
[ "Get", "the", "type", "of", "this", "context", "as", "an", "optionally", "coloured", "string", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/exec_context.py#L88-L106
gbiggs/rtctree
rtctree/exec_context.py
ExecutionContext.running_as_string
def running_as_string(self, add_colour=True): '''Get the state of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing this context's running state. ''' with self._mutex: if self.running: result = 'Running', ['bold', 'green'] else: result = 'Stopped', ['reset'] if add_colour: return utils.build_attr_string(result[1], supported=add_colour) + \ result[0] + utils.build_attr_string('reset', supported=add_colour) else: return result[0]
python
def running_as_string(self, add_colour=True): '''Get the state of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing this context's running state. ''' with self._mutex: if self.running: result = 'Running', ['bold', 'green'] else: result = 'Stopped', ['reset'] if add_colour: return utils.build_attr_string(result[1], supported=add_colour) + \ result[0] + utils.build_attr_string('reset', supported=add_colour) else: return result[0]
[ "def", "running_as_string", "(", "self", ",", "add_colour", "=", "True", ")", ":", "with", "self", ".", "_mutex", ":", "if", "self", ".", "running", ":", "result", "=", "'Running'", ",", "[", "'bold'", ",", "'green'", "]", "else", ":", "result", "=", ...
Get the state of this context as an optionally coloured string. @param add_colour If True, ANSI colour codes will be added. @return A string describing this context's running state.
[ "Get", "the", "state", "of", "this", "context", "as", "an", "optionally", "coloured", "string", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/exec_context.py#L117-L133
gbiggs/rtctree
rtctree/exec_context.py
ExecutionContext.kind
def kind(self): '''The kind of this execution context.''' with self._mutex: kind = self._obj.get_kind() if kind == RTC.PERIODIC: return self.PERIODIC elif kind == RTC.EVENT_DRIVEN: return self.EVENT_DRIVEN else: return self.OTHER
python
def kind(self): '''The kind of this execution context.''' with self._mutex: kind = self._obj.get_kind() if kind == RTC.PERIODIC: return self.PERIODIC elif kind == RTC.EVENT_DRIVEN: return self.EVENT_DRIVEN else: return self.OTHER
[ "def", "kind", "(", "self", ")", ":", "with", "self", ".", "_mutex", ":", "kind", "=", "self", ".", "_obj", ".", "get_kind", "(", ")", "if", "kind", "==", "RTC", ".", "PERIODIC", ":", "return", "self", ".", "PERIODIC", "elif", "kind", "==", "RTC", ...
The kind of this execution context.
[ "The", "kind", "of", "this", "execution", "context", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/exec_context.py#L152-L161
gbiggs/rtctree
rtctree/exec_context.py
ExecutionContext.owner_name
def owner_name(self): '''The name of the RTObject that owns this context.''' with self._mutex: if self._owner: return self._owner.get_component_profile().instance_name else: return ''
python
def owner_name(self): '''The name of the RTObject that owns this context.''' with self._mutex: if self._owner: return self._owner.get_component_profile().instance_name else: return ''
[ "def", "owner_name", "(", "self", ")", ":", "with", "self", ".", "_mutex", ":", "if", "self", ".", "_owner", ":", "return", "self", ".", "_owner", ".", "get_component_profile", "(", ")", ".", "instance_name", "else", ":", "return", "''" ]
The name of the RTObject that owns this context.
[ "The", "name", "of", "the", "RTObject", "that", "owns", "this", "context", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/exec_context.py#L175-L181
gbiggs/rtctree
rtctree/exec_context.py
ExecutionContext.participant_names
def participant_names(self): '''The names of the RTObjects participating in this context.''' with self._mutex: return [obj.get_component_profile().instance_name \ for obj in self._participants]
python
def participant_names(self): '''The names of the RTObjects participating in this context.''' with self._mutex: return [obj.get_component_profile().instance_name \ for obj in self._participants]
[ "def", "participant_names", "(", "self", ")", ":", "with", "self", ".", "_mutex", ":", "return", "[", "obj", ".", "get_component_profile", "(", ")", ".", "instance_name", "for", "obj", "in", "self", ".", "_participants", "]" ]
The names of the RTObjects participating in this context.
[ "The", "names", "of", "the", "RTObjects", "participating", "in", "this", "context", "." ]
train
https://github.com/gbiggs/rtctree/blob/bd725a47ac87c259c8bce06156ccc9ab71111c26/rtctree/exec_context.py#L190-L194
django-de/django-simple-ratings
ratings/models.py
_RatingsDescriptor.delete_manager
def delete_manager(self, instance): """ Returns a queryset based on the related model's base manager (rather than the default manager, as returned by __get__). Used by Model.delete(). """ return self.create_manager(instance, self.rating_model._base_manager.__class__)
python
def delete_manager(self, instance): """ Returns a queryset based on the related model's base manager (rather than the default manager, as returned by __get__). Used by Model.delete(). """ return self.create_manager(instance, self.rating_model._base_manager.__class__)
[ "def", "delete_manager", "(", "self", ",", "instance", ")", ":", "return", "self", ".", "create_manager", "(", "instance", ",", "self", ".", "rating_model", ".", "_base_manager", ".", "__class__", ")" ]
Returns a queryset based on the related model's base manager (rather than the default manager, as returned by __get__). Used by Model.delete().
[ "Returns", "a", "queryset", "based", "on", "the", "related", "model", "s", "base", "manager", "(", "rather", "than", "the", "default", "manager", "as", "returned", "by", "__get__", ")", ".", "Used", "by", "Model", ".", "delete", "()", "." ]
train
https://github.com/django-de/django-simple-ratings/blob/f876f1284943b4913d865757f5d46b4515e26683/ratings/models.py#L144-L151
django-de/django-simple-ratings
ratings/models.py
_RatingsDescriptor.create_manager
def create_manager(self, instance, superclass): """ Dynamically create a RelatedManager to handle the back side of the (G)FK """ rel_model = self.rating_model rated_model = self.rated_model class RelatedManager(superclass): def get_query_set(self): qs = RatingsQuerySet(rel_model, rated_model=rated_model) return qs.filter(**(self.core_filters)) def add(self, *objs): lookup_kwargs = rel_model.lookup_kwargs(instance) for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) for (k, v) in lookup_kwargs.iteritems(): setattr(obj, k, v) obj.save() add.alters_data = True def create(self, **kwargs): kwargs.update(rel_model.lookup_kwargs(instance)) return super(RelatedManager, self).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): kwargs.update(rel_model.lookup_kwargs(instance)) return super(RelatedManager, self).get_or_create(**kwargs) get_or_create.alters_data = True def remove(self, *objs): for obj in objs: # Is obj actually part of this descriptor set? if obj in self.all(): obj.delete() else: raise rel_model.DoesNotExist( "%r is not related to %r." % (obj, instance)) remove.alters_data = True def clear(self): self.all().delete() clear.alters_data = True def rate(self, user, score): rating, created = self.get_or_create(user=user) if created or score != rating.score: rating.score = score rating.save() return rating def unrate(self, user): return self.filter(user=user, **rel_model.lookup_kwargs(instance) ).delete() def perform_aggregation(self, aggregator): score = self.all().aggregate(agg=aggregator('score')) return score['agg'] def cumulative_score(self): # simply the sum of all scores, useful for +1/-1 return self.perform_aggregation(models.Sum) def average_score(self): # the average of all the scores, useful for 1-5 return self.perform_aggregation(models.Avg) def standard_deviation(self): # the standard deviation of all the scores, useful for 1-5 return self.perform_aggregation(models.StdDev) def variance(self): # the variance of all the scores, useful for 1-5 return self.perform_aggregation(models.Variance) def similar_items(self): return SimilarItem.objects.get_for_item(instance) manager = RelatedManager() manager.core_filters = rel_model.lookup_kwargs(instance) manager.model = rel_model return manager
python
def create_manager(self, instance, superclass): """ Dynamically create a RelatedManager to handle the back side of the (G)FK """ rel_model = self.rating_model rated_model = self.rated_model class RelatedManager(superclass): def get_query_set(self): qs = RatingsQuerySet(rel_model, rated_model=rated_model) return qs.filter(**(self.core_filters)) def add(self, *objs): lookup_kwargs = rel_model.lookup_kwargs(instance) for obj in objs: if not isinstance(obj, self.model): raise TypeError("'%s' instance expected" % self.model._meta.object_name) for (k, v) in lookup_kwargs.iteritems(): setattr(obj, k, v) obj.save() add.alters_data = True def create(self, **kwargs): kwargs.update(rel_model.lookup_kwargs(instance)) return super(RelatedManager, self).create(**kwargs) create.alters_data = True def get_or_create(self, **kwargs): kwargs.update(rel_model.lookup_kwargs(instance)) return super(RelatedManager, self).get_or_create(**kwargs) get_or_create.alters_data = True def remove(self, *objs): for obj in objs: # Is obj actually part of this descriptor set? if obj in self.all(): obj.delete() else: raise rel_model.DoesNotExist( "%r is not related to %r." % (obj, instance)) remove.alters_data = True def clear(self): self.all().delete() clear.alters_data = True def rate(self, user, score): rating, created = self.get_or_create(user=user) if created or score != rating.score: rating.score = score rating.save() return rating def unrate(self, user): return self.filter(user=user, **rel_model.lookup_kwargs(instance) ).delete() def perform_aggregation(self, aggregator): score = self.all().aggregate(agg=aggregator('score')) return score['agg'] def cumulative_score(self): # simply the sum of all scores, useful for +1/-1 return self.perform_aggregation(models.Sum) def average_score(self): # the average of all the scores, useful for 1-5 return self.perform_aggregation(models.Avg) def standard_deviation(self): # the standard deviation of all the scores, useful for 1-5 return self.perform_aggregation(models.StdDev) def variance(self): # the variance of all the scores, useful for 1-5 return self.perform_aggregation(models.Variance) def similar_items(self): return SimilarItem.objects.get_for_item(instance) manager = RelatedManager() manager.core_filters = rel_model.lookup_kwargs(instance) manager.model = rel_model return manager
[ "def", "create_manager", "(", "self", ",", "instance", ",", "superclass", ")", ":", "rel_model", "=", "self", ".", "rating_model", "rated_model", "=", "self", ".", "rated_model", "class", "RelatedManager", "(", "superclass", ")", ":", "def", "get_query_set", "...
Dynamically create a RelatedManager to handle the back side of the (G)FK
[ "Dynamically", "create", "a", "RelatedManager", "to", "handle", "the", "back", "side", "of", "the", "(", "G", ")", "FK" ]
train
https://github.com/django-de/django-simple-ratings/blob/f876f1284943b4913d865757f5d46b4515e26683/ratings/models.py#L153-L239
SylvanasSun/FishFishJump
fish_core/bloomfilter.py
SimpleHash.hash
def hash(self, value): """ function hash() implement to acquire hash value that use simply method that weighted sum. Parameters: ----------- value: string the value is param of need acquire hash Returns: -------- result hash code for value """ result = 0 for i in range(len(value)): result += self.seed * result + ord(value[i]) return (self.capacity - 1) % result
python
def hash(self, value): """ function hash() implement to acquire hash value that use simply method that weighted sum. Parameters: ----------- value: string the value is param of need acquire hash Returns: -------- result hash code for value """ result = 0 for i in range(len(value)): result += self.seed * result + ord(value[i]) return (self.capacity - 1) % result
[ "def", "hash", "(", "self", ",", "value", ")", ":", "result", "=", "0", "for", "i", "in", "range", "(", "len", "(", "value", ")", ")", ":", "result", "+=", "self", ".", "seed", "*", "result", "+", "ord", "(", "value", "[", "i", "]", ")", "ret...
function hash() implement to acquire hash value that use simply method that weighted sum. Parameters: ----------- value: string the value is param of need acquire hash Returns: -------- result hash code for value
[ "function", "hash", "()", "implement", "to", "acquire", "hash", "value", "that", "use", "simply", "method", "that", "weighted", "sum", "." ]
train
https://github.com/SylvanasSun/FishFishJump/blob/696212d242d8d572f3f1b43925f3d8ab8acc6a2d/fish_core/bloomfilter.py#L23-L39