repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
ianmiell/shutit
shutit_setup.py
ConnBash.build
def build(self, shutit): """Sets up the machine ready for building. """ shutit_pexpect_session = ShutItPexpectSession(shutit, 'target_child','/bin/bash') target_child = shutit_pexpect_session.pexpect_child shutit_pexpect_session.expect(shutit_global.shutit_global_object.base_prompt.strip(), timeout=10) self.setup_host_child(shutit) self.setup_target_child(shutit, target_child) return True
python
def build(self, shutit): """Sets up the machine ready for building. """ shutit_pexpect_session = ShutItPexpectSession(shutit, 'target_child','/bin/bash') target_child = shutit_pexpect_session.pexpect_child shutit_pexpect_session.expect(shutit_global.shutit_global_object.base_prompt.strip(), timeout=10) self.setup_host_child(shutit) self.setup_target_child(shutit, target_child) return True
[ "def", "build", "(", "self", ",", "shutit", ")", ":", "shutit_pexpect_session", "=", "ShutItPexpectSession", "(", "shutit", ",", "'target_child'", ",", "'/bin/bash'", ")", "target_child", "=", "shutit_pexpect_session", ".", "pexpect_child", "shutit_pexpect_session", ".", "expect", "(", "shutit_global", ".", "shutit_global_object", ".", "base_prompt", ".", "strip", "(", ")", ",", "timeout", "=", "10", ")", "self", ".", "setup_host_child", "(", "shutit", ")", "self", ".", "setup_target_child", "(", "shutit", ",", "target_child", ")", "return", "True" ]
Sets up the machine ready for building.
[ "Sets", "up", "the", "machine", "ready", "for", "building", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_setup.py#L131-L139
train
ianmiell/shutit
shutit_setup.py
setup.build
def build(self, shutit): """Initializes target ready for build and updating package management if in container. """ if shutit.build['delivery'] in ('docker','dockerfile'): if shutit.get_current_shutit_pexpect_session_environment().install_type == 'apt': shutit.add_to_bashrc('export DEBIAN_FRONTEND=noninteractive') if not shutit.command_available('lsb_release'): shutit.install('lsb-release') shutit.lsb_release() elif shutit.get_current_shutit_pexpect_session_environment().install_type == 'yum': # yum updates are so often "bad" that we let exit codes of 1 through. # TODO: make this more sophisticated shutit.send('yum update -y', timeout=9999, exit_values=['0', '1']) shutit.pause_point('Anything you want to do to the target host ' + 'before the build starts?', level=2) return True
python
def build(self, shutit): """Initializes target ready for build and updating package management if in container. """ if shutit.build['delivery'] in ('docker','dockerfile'): if shutit.get_current_shutit_pexpect_session_environment().install_type == 'apt': shutit.add_to_bashrc('export DEBIAN_FRONTEND=noninteractive') if not shutit.command_available('lsb_release'): shutit.install('lsb-release') shutit.lsb_release() elif shutit.get_current_shutit_pexpect_session_environment().install_type == 'yum': # yum updates are so often "bad" that we let exit codes of 1 through. # TODO: make this more sophisticated shutit.send('yum update -y', timeout=9999, exit_values=['0', '1']) shutit.pause_point('Anything you want to do to the target host ' + 'before the build starts?', level=2) return True
[ "def", "build", "(", "self", ",", "shutit", ")", ":", "if", "shutit", ".", "build", "[", "'delivery'", "]", "in", "(", "'docker'", ",", "'dockerfile'", ")", ":", "if", "shutit", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "install_type", "==", "'apt'", ":", "shutit", ".", "add_to_bashrc", "(", "'export DEBIAN_FRONTEND=noninteractive'", ")", "if", "not", "shutit", ".", "command_available", "(", "'lsb_release'", ")", ":", "shutit", ".", "install", "(", "'lsb-release'", ")", "shutit", ".", "lsb_release", "(", ")", "elif", "shutit", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "install_type", "==", "'yum'", ":", "# yum updates are so often \"bad\" that we let exit codes of 1 through.", "# TODO: make this more sophisticated", "shutit", ".", "send", "(", "'yum update -y'", ",", "timeout", "=", "9999", ",", "exit_values", "=", "[", "'0'", ",", "'1'", "]", ")", "shutit", ".", "pause_point", "(", "'Anything you want to do to the target host '", "+", "'before the build starts?'", ",", "level", "=", "2", ")", "return", "True" ]
Initializes target ready for build and updating package management if in container.
[ "Initializes", "target", "ready", "for", "build", "and", "updating", "package", "management", "if", "in", "container", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_setup.py#L170-L184
train
ianmiell/shutit
emailer.py
Emailer.__set_config
def __set_config(self, cfg_section): """Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__ """ defaults = [ 'shutit.core.alerting.emailer.mailto', None, 'shutit.core.alerting.emailer.mailfrom', '[email protected]', 'shutit.core.alerting.emailer.smtp_server', 'localhost', 'shutit.core.alerting.emailer.smtp_port', 25, 'shutit.core.alerting.emailer.use_tls', True, 'shutit.core.alerting.emailer.send_mail', True, 'shutit.core.alerting.emailer.subject', 'Shutit Report', 'shutit.core.alerting.emailer.signature', '--Angry Shutit', 'shutit.core.alerting.emailer.compress', True, 'shutit.core.alerting.emailer.username', '', 'shutit.core.alerting.emailer.password', '', 'shutit.core.alerting.emailer.safe_mode', True, 'shutit.core.alerting.emailer.maintainer','', 'shutit.core.alerting.emailer.mailto_maintainer', True ] for cfg_name, cfg_default in zip(defaults[0::2], defaults[1::2]): try: self.config[cfg_name] = self.shutit.cfg[cfg_section][cfg_name] except KeyError: if cfg_default is None: raise Exception(cfg_section + ' ' + cfg_name + ' must be set') else: self.config[cfg_name] = cfg_default # only send a mail to the module's maintainer if configured correctly if self.config['shutit.core.alerting.emailer.mailto_maintainer'] and \ (self.config['shutit.core.alerting.emailer.maintainer'] == "" or \ self.config['shutit.core.alerting.emailer.maintainer'] == self.config['shutit.core.alerting.emailer.mailto']): self.config['shutit.core.alerting.emailer.mailto_maintainer'] = False self.config['shutit.core.alerting.emailer.maintainer'] = ""
python
def __set_config(self, cfg_section): """Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__ """ defaults = [ 'shutit.core.alerting.emailer.mailto', None, 'shutit.core.alerting.emailer.mailfrom', '[email protected]', 'shutit.core.alerting.emailer.smtp_server', 'localhost', 'shutit.core.alerting.emailer.smtp_port', 25, 'shutit.core.alerting.emailer.use_tls', True, 'shutit.core.alerting.emailer.send_mail', True, 'shutit.core.alerting.emailer.subject', 'Shutit Report', 'shutit.core.alerting.emailer.signature', '--Angry Shutit', 'shutit.core.alerting.emailer.compress', True, 'shutit.core.alerting.emailer.username', '', 'shutit.core.alerting.emailer.password', '', 'shutit.core.alerting.emailer.safe_mode', True, 'shutit.core.alerting.emailer.maintainer','', 'shutit.core.alerting.emailer.mailto_maintainer', True ] for cfg_name, cfg_default in zip(defaults[0::2], defaults[1::2]): try: self.config[cfg_name] = self.shutit.cfg[cfg_section][cfg_name] except KeyError: if cfg_default is None: raise Exception(cfg_section + ' ' + cfg_name + ' must be set') else: self.config[cfg_name] = cfg_default # only send a mail to the module's maintainer if configured correctly if self.config['shutit.core.alerting.emailer.mailto_maintainer'] and \ (self.config['shutit.core.alerting.emailer.maintainer'] == "" or \ self.config['shutit.core.alerting.emailer.maintainer'] == self.config['shutit.core.alerting.emailer.mailto']): self.config['shutit.core.alerting.emailer.mailto_maintainer'] = False self.config['shutit.core.alerting.emailer.maintainer'] = ""
[ "def", "__set_config", "(", "self", ",", "cfg_section", ")", ":", "defaults", "=", "[", "'shutit.core.alerting.emailer.mailto'", ",", "None", ",", "'shutit.core.alerting.emailer.mailfrom'", ",", "'[email protected]'", ",", "'shutit.core.alerting.emailer.smtp_server'", ",", "'localhost'", ",", "'shutit.core.alerting.emailer.smtp_port'", ",", "25", ",", "'shutit.core.alerting.emailer.use_tls'", ",", "True", ",", "'shutit.core.alerting.emailer.send_mail'", ",", "True", ",", "'shutit.core.alerting.emailer.subject'", ",", "'Shutit Report'", ",", "'shutit.core.alerting.emailer.signature'", ",", "'--Angry Shutit'", ",", "'shutit.core.alerting.emailer.compress'", ",", "True", ",", "'shutit.core.alerting.emailer.username'", ",", "''", ",", "'shutit.core.alerting.emailer.password'", ",", "''", ",", "'shutit.core.alerting.emailer.safe_mode'", ",", "True", ",", "'shutit.core.alerting.emailer.maintainer'", ",", "''", ",", "'shutit.core.alerting.emailer.mailto_maintainer'", ",", "True", "]", "for", "cfg_name", ",", "cfg_default", "in", "zip", "(", "defaults", "[", "0", ":", ":", "2", "]", ",", "defaults", "[", "1", ":", ":", "2", "]", ")", ":", "try", ":", "self", ".", "config", "[", "cfg_name", "]", "=", "self", ".", "shutit", ".", "cfg", "[", "cfg_section", "]", "[", "cfg_name", "]", "except", "KeyError", ":", "if", "cfg_default", "is", "None", ":", "raise", "Exception", "(", "cfg_section", "+", "' '", "+", "cfg_name", "+", "' must be set'", ")", "else", ":", "self", ".", "config", "[", "cfg_name", "]", "=", "cfg_default", "# only send a mail to the module's maintainer if configured correctly", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", "and", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "==", "\"\"", "or", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "==", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto'", "]", ")", ":", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", "=", "False", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "=", "\"\"" ]
Set a local config array up according to defaults and main shutit configuration cfg_section - see __init__
[ "Set", "a", "local", "config", "array", "up", "according", "to", "defaults", "and", "main", "shutit", "configuration" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L88-L125
train
ianmiell/shutit
emailer.py
Emailer.__get_smtp
def __get_smtp(self): """ Return the appropraite smtplib depending on wherther we're using TLS """ use_tls = self.config['shutit.core.alerting.emailer.use_tls'] if use_tls: smtp = SMTP(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) smtp.starttls() else: smtp = SMTP_SSL(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) return smtp
python
def __get_smtp(self): """ Return the appropraite smtplib depending on wherther we're using TLS """ use_tls = self.config['shutit.core.alerting.emailer.use_tls'] if use_tls: smtp = SMTP(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) smtp.starttls() else: smtp = SMTP_SSL(self.config['shutit.core.alerting.emailer.smtp_server'], self.config['shutit.core.alerting.emailer.smtp_port']) return smtp
[ "def", "__get_smtp", "(", "self", ")", ":", "use_tls", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.use_tls'", "]", "if", "use_tls", ":", "smtp", "=", "SMTP", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_server'", "]", ",", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_port'", "]", ")", "smtp", ".", "starttls", "(", ")", "else", ":", "smtp", "=", "SMTP_SSL", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_server'", "]", ",", "self", ".", "config", "[", "'shutit.core.alerting.emailer.smtp_port'", "]", ")", "return", "smtp" ]
Return the appropraite smtplib depending on wherther we're using TLS
[ "Return", "the", "appropraite", "smtplib", "depending", "on", "wherther", "we", "re", "using", "TLS" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L139-L148
train
ianmiell/shutit
emailer.py
Emailer.__compose
def __compose(self): """ Compose the message, pulling together body, attachments etc """ msg = MIMEMultipart() msg['Subject'] = self.config['shutit.core.alerting.emailer.subject'] msg['To'] = self.config['shutit.core.alerting.emailer.mailto'] msg['From'] = self.config['shutit.core.alerting.emailer.mailfrom'] # add the module's maintainer as a CC if configured if self.config['shutit.core.alerting.emailer.mailto_maintainer']: msg['Cc'] = self.config['shutit.core.alerting.emailer.maintainer'] if self.config['shutit.core.alerting.emailer.signature'] != '': signature = '\n\n' + self.config['shutit.core.alerting.emailer.signature'] else: signature = self.config['shutit.core.alerting.emailer.signature'] body = MIMEText('\n'.join(self.lines) + signature) msg.attach(body) for attach in self.attaches: msg.attach(attach) return msg
python
def __compose(self): """ Compose the message, pulling together body, attachments etc """ msg = MIMEMultipart() msg['Subject'] = self.config['shutit.core.alerting.emailer.subject'] msg['To'] = self.config['shutit.core.alerting.emailer.mailto'] msg['From'] = self.config['shutit.core.alerting.emailer.mailfrom'] # add the module's maintainer as a CC if configured if self.config['shutit.core.alerting.emailer.mailto_maintainer']: msg['Cc'] = self.config['shutit.core.alerting.emailer.maintainer'] if self.config['shutit.core.alerting.emailer.signature'] != '': signature = '\n\n' + self.config['shutit.core.alerting.emailer.signature'] else: signature = self.config['shutit.core.alerting.emailer.signature'] body = MIMEText('\n'.join(self.lines) + signature) msg.attach(body) for attach in self.attaches: msg.attach(attach) return msg
[ "def", "__compose", "(", "self", ")", ":", "msg", "=", "MIMEMultipart", "(", ")", "msg", "[", "'Subject'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.subject'", "]", "msg", "[", "'To'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto'", "]", "msg", "[", "'From'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailfrom'", "]", "# add the module's maintainer as a CC if configured", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", ":", "msg", "[", "'Cc'", "]", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.signature'", "]", "!=", "''", ":", "signature", "=", "'\\n\\n'", "+", "self", ".", "config", "[", "'shutit.core.alerting.emailer.signature'", "]", "else", ":", "signature", "=", "self", ".", "config", "[", "'shutit.core.alerting.emailer.signature'", "]", "body", "=", "MIMEText", "(", "'\\n'", ".", "join", "(", "self", ".", "lines", ")", "+", "signature", ")", "msg", ".", "attach", "(", "body", ")", "for", "attach", "in", "self", ".", "attaches", ":", "msg", ".", "attach", "(", "attach", ")", "return", "msg" ]
Compose the message, pulling together body, attachments etc
[ "Compose", "the", "message", "pulling", "together", "body", "attachments", "etc" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L180-L198
train
ianmiell/shutit
emailer.py
Emailer.send
def send(self, attachment_failure=False): """Send the email according to the configured setup attachment_failure - used to indicate a recursive call after the smtp server has refused based on file size. Should not be used externally """ if not self.config['shutit.core.alerting.emailer.send_mail']: self.shutit.log('emailer.send: Not configured to send mail!',level=logging.INFO) return True msg = self.__compose() mailto = [self.config['shutit.core.alerting.emailer.mailto']] smtp = self.__get_smtp() if self.config['shutit.core.alerting.emailer.username'] != '': smtp.login(self.config['shutit.core.alerting.emailer.username'], self.config['shutit.core.alerting.emailer.password']) if self.config['shutit.core.alerting.emailer.mailto_maintainer']: mailto.append(self.config['shutit.core.alerting.emailer.maintainer']) try: self.shutit.log('Attempting to send email',level=logging.INFO) smtp.sendmail(self.config['shutit.core.alerting.emailer.mailfrom'], mailto, msg.as_string()) except SMTPSenderRefused as refused: code = refused.args[0] if code == 552 and not attachment_failure: self.shutit.log("Mailserver rejected message due to " + "oversize attachments, attempting to resend without",level=logging.INFO) self.attaches = [] self.lines.append("Oversized attachments not sent") self.send(attachment_failure=True) else: self.shutit.log("Unhandled SMTP error:" + str(refused),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise refused except Exception as error: self.shutit.log('Unhandled exception: ' + str(error),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise error finally: smtp.quit()
python
def send(self, attachment_failure=False): """Send the email according to the configured setup attachment_failure - used to indicate a recursive call after the smtp server has refused based on file size. Should not be used externally """ if not self.config['shutit.core.alerting.emailer.send_mail']: self.shutit.log('emailer.send: Not configured to send mail!',level=logging.INFO) return True msg = self.__compose() mailto = [self.config['shutit.core.alerting.emailer.mailto']] smtp = self.__get_smtp() if self.config['shutit.core.alerting.emailer.username'] != '': smtp.login(self.config['shutit.core.alerting.emailer.username'], self.config['shutit.core.alerting.emailer.password']) if self.config['shutit.core.alerting.emailer.mailto_maintainer']: mailto.append(self.config['shutit.core.alerting.emailer.maintainer']) try: self.shutit.log('Attempting to send email',level=logging.INFO) smtp.sendmail(self.config['shutit.core.alerting.emailer.mailfrom'], mailto, msg.as_string()) except SMTPSenderRefused as refused: code = refused.args[0] if code == 552 and not attachment_failure: self.shutit.log("Mailserver rejected message due to " + "oversize attachments, attempting to resend without",level=logging.INFO) self.attaches = [] self.lines.append("Oversized attachments not sent") self.send(attachment_failure=True) else: self.shutit.log("Unhandled SMTP error:" + str(refused),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise refused except Exception as error: self.shutit.log('Unhandled exception: ' + str(error),level=logging.INFO) if not self.config['shutit.core.alerting.emailer.safe_mode']: raise error finally: smtp.quit()
[ "def", "send", "(", "self", ",", "attachment_failure", "=", "False", ")", ":", "if", "not", "self", ".", "config", "[", "'shutit.core.alerting.emailer.send_mail'", "]", ":", "self", ".", "shutit", ".", "log", "(", "'emailer.send: Not configured to send mail!'", ",", "level", "=", "logging", ".", "INFO", ")", "return", "True", "msg", "=", "self", ".", "__compose", "(", ")", "mailto", "=", "[", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto'", "]", "]", "smtp", "=", "self", ".", "__get_smtp", "(", ")", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.username'", "]", "!=", "''", ":", "smtp", ".", "login", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.username'", "]", ",", "self", ".", "config", "[", "'shutit.core.alerting.emailer.password'", "]", ")", "if", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailto_maintainer'", "]", ":", "mailto", ".", "append", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.maintainer'", "]", ")", "try", ":", "self", ".", "shutit", ".", "log", "(", "'Attempting to send email'", ",", "level", "=", "logging", ".", "INFO", ")", "smtp", ".", "sendmail", "(", "self", ".", "config", "[", "'shutit.core.alerting.emailer.mailfrom'", "]", ",", "mailto", ",", "msg", ".", "as_string", "(", ")", ")", "except", "SMTPSenderRefused", "as", "refused", ":", "code", "=", "refused", ".", "args", "[", "0", "]", "if", "code", "==", "552", "and", "not", "attachment_failure", ":", "self", ".", "shutit", ".", "log", "(", "\"Mailserver rejected message due to \"", "+", "\"oversize attachments, attempting to resend without\"", ",", "level", "=", "logging", ".", "INFO", ")", "self", ".", "attaches", "=", "[", "]", "self", ".", "lines", ".", "append", "(", "\"Oversized attachments not sent\"", ")", "self", ".", "send", "(", "attachment_failure", "=", "True", ")", "else", ":", "self", ".", "shutit", ".", "log", "(", "\"Unhandled SMTP error:\"", "+", "str", "(", "refused", ")", ",", "level", "=", "logging", ".", "INFO", ")", "if", "not", "self", ".", "config", "[", "'shutit.core.alerting.emailer.safe_mode'", "]", ":", "raise", "refused", "except", "Exception", "as", "error", ":", "self", ".", "shutit", ".", "log", "(", "'Unhandled exception: '", "+", "str", "(", "error", ")", ",", "level", "=", "logging", ".", "INFO", ")", "if", "not", "self", ".", "config", "[", "'shutit.core.alerting.emailer.safe_mode'", "]", ":", "raise", "error", "finally", ":", "smtp", ".", "quit", "(", ")" ]
Send the email according to the configured setup attachment_failure - used to indicate a recursive call after the smtp server has refused based on file size. Should not be used externally
[ "Send", "the", "email", "according", "to", "the", "configured", "setup" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/emailer.py#L200-L236
train
ianmiell/shutit
shutit_global.py
setup_signals
def setup_signals(): """Set up the signal handlers. """ signal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler) signal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler)
python
def setup_signals(): """Set up the signal handlers. """ signal.signal(signal.SIGINT, shutit_util.ctrl_c_signal_handler) signal.signal(signal.SIGQUIT, shutit_util.ctrl_quit_signal_handler)
[ "def", "setup_signals", "(", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "shutit_util", ".", "ctrl_c_signal_handler", ")", "signal", ".", "signal", "(", "signal", ".", "SIGQUIT", ",", "shutit_util", ".", "ctrl_quit_signal_handler", ")" ]
Set up the signal handlers.
[ "Set", "up", "the", "signal", "handlers", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_global.py#L583-L587
train
ianmiell/shutit
shutit_global.py
get_shutit_pexpect_sessions
def get_shutit_pexpect_sessions(): """Returns all the shutit_pexpect sessions in existence. """ sessions = [] for shutit_object in shutit_global_object.shutit_objects: for key in shutit_object.shutit_pexpect_sessions: sessions.append(shutit_object.shutit_pexpect_sessions[key]) return sessions
python
def get_shutit_pexpect_sessions(): """Returns all the shutit_pexpect sessions in existence. """ sessions = [] for shutit_object in shutit_global_object.shutit_objects: for key in shutit_object.shutit_pexpect_sessions: sessions.append(shutit_object.shutit_pexpect_sessions[key]) return sessions
[ "def", "get_shutit_pexpect_sessions", "(", ")", ":", "sessions", "=", "[", "]", "for", "shutit_object", "in", "shutit_global_object", ".", "shutit_objects", ":", "for", "key", "in", "shutit_object", ".", "shutit_pexpect_sessions", ":", "sessions", ".", "append", "(", "shutit_object", ".", "shutit_pexpect_sessions", "[", "key", "]", ")", "return", "sessions" ]
Returns all the shutit_pexpect sessions in existence.
[ "Returns", "all", "the", "shutit_pexpect", "sessions", "in", "existence", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_global.py#L590-L597
train
ianmiell/shutit
shutit.py
main
def main(): """Main ShutIt function. Handles the configured actions: - skeleton - create skeleton module - list_configs - output computed configuration - depgraph - output digraph of module dependencies """ # Create base shutit object. shutit = shutit_global.shutit_global_object.shutit_objects[0] if sys.version_info[0] == 2: if sys.version_info[1] < 7: shutit.fail('Python version must be 2.7+') # pragma: no cover try: shutit.setup_shutit_obj() except KeyboardInterrupt: shutit_util.print_debug(sys.exc_info()) shutit_global.shutit_global_object.shutit_print('Keyboard interrupt caught, exiting with status 1') sys.exit(1)
python
def main(): """Main ShutIt function. Handles the configured actions: - skeleton - create skeleton module - list_configs - output computed configuration - depgraph - output digraph of module dependencies """ # Create base shutit object. shutit = shutit_global.shutit_global_object.shutit_objects[0] if sys.version_info[0] == 2: if sys.version_info[1] < 7: shutit.fail('Python version must be 2.7+') # pragma: no cover try: shutit.setup_shutit_obj() except KeyboardInterrupt: shutit_util.print_debug(sys.exc_info()) shutit_global.shutit_global_object.shutit_print('Keyboard interrupt caught, exiting with status 1') sys.exit(1)
[ "def", "main", "(", ")", ":", "# Create base shutit object.", "shutit", "=", "shutit_global", ".", "shutit_global_object", ".", "shutit_objects", "[", "0", "]", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", ":", "if", "sys", ".", "version_info", "[", "1", "]", "<", "7", ":", "shutit", ".", "fail", "(", "'Python version must be 2.7+'", ")", "# pragma: no cover", "try", ":", "shutit", ".", "setup_shutit_obj", "(", ")", "except", "KeyboardInterrupt", ":", "shutit_util", ".", "print_debug", "(", "sys", ".", "exc_info", "(", ")", ")", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'Keyboard interrupt caught, exiting with status 1'", ")", "sys", ".", "exit", "(", "1", ")" ]
Main ShutIt function. Handles the configured actions: - skeleton - create skeleton module - list_configs - output computed configuration - depgraph - output digraph of module dependencies
[ "Main", "ShutIt", "function", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit.py#L133-L152
train
ianmiell/shutit
shutit_login_stack.py
ShutItLoginStackItem.has_blocking_background_send
def has_blocking_background_send(self): """Check whether any blocking background commands are waiting to run. If any are, return True. If none are, return False. """ for background_object in self.background_objects: # If it's running, or not started yet, it should block other tasks. if background_object.block_other_commands and background_object.run_state in ('S','N'): self.shutit_obj.log('All objects are: ' + str(self),level=logging.DEBUG) self.shutit_obj.log('The current blocking send object is: ' + str(background_object),level=logging.DEBUG) return True elif background_object.block_other_commands and background_object.run_state in ('F','C','T'): assert False, shutit_util.print_debug(msg='Blocking command should have been removed, in run_state: ' + background_object.run_state) else: assert background_object.block_other_commands is False, shutit_util.print_debug() return False
python
def has_blocking_background_send(self): """Check whether any blocking background commands are waiting to run. If any are, return True. If none are, return False. """ for background_object in self.background_objects: # If it's running, or not started yet, it should block other tasks. if background_object.block_other_commands and background_object.run_state in ('S','N'): self.shutit_obj.log('All objects are: ' + str(self),level=logging.DEBUG) self.shutit_obj.log('The current blocking send object is: ' + str(background_object),level=logging.DEBUG) return True elif background_object.block_other_commands and background_object.run_state in ('F','C','T'): assert False, shutit_util.print_debug(msg='Blocking command should have been removed, in run_state: ' + background_object.run_state) else: assert background_object.block_other_commands is False, shutit_util.print_debug() return False
[ "def", "has_blocking_background_send", "(", "self", ")", ":", "for", "background_object", "in", "self", ".", "background_objects", ":", "# If it's running, or not started yet, it should block other tasks.", "if", "background_object", ".", "block_other_commands", "and", "background_object", ".", "run_state", "in", "(", "'S'", ",", "'N'", ")", ":", "self", ".", "shutit_obj", ".", "log", "(", "'All objects are: '", "+", "str", "(", "self", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "shutit_obj", ".", "log", "(", "'The current blocking send object is: '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", "elif", "background_object", ".", "block_other_commands", "and", "background_object", ".", "run_state", "in", "(", "'F'", ",", "'C'", ",", "'T'", ")", ":", "assert", "False", ",", "shutit_util", ".", "print_debug", "(", "msg", "=", "'Blocking command should have been removed, in run_state: '", "+", "background_object", ".", "run_state", ")", "else", ":", "assert", "background_object", ".", "block_other_commands", "is", "False", ",", "shutit_util", ".", "print_debug", "(", ")", "return", "False" ]
Check whether any blocking background commands are waiting to run. If any are, return True. If none are, return False.
[ "Check", "whether", "any", "blocking", "background", "commands", "are", "waiting", "to", "run", ".", "If", "any", "are", "return", "True", ".", "If", "none", "are", "return", "False", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_login_stack.py#L85-L99
train
ianmiell/shutit
shutit_login_stack.py
ShutItLoginStackItem.check_background_commands_complete
def check_background_commands_complete(self): """Check whether any background commands are running or to be run. If none are, return True. If any are, return False. """ unstarted_command_exists = False self.shutit_obj.log('In check_background_commands_complete: all background objects: ' + str(self.background_objects),level=logging.DEBUG) self.shutit_obj.log('Login id: ' + str(self.login_id),level=logging.DEBUG) for background_object in self.background_objects: self.shutit_obj.log('Background object send: ' + str(background_object.sendspec.send),level=logging.DEBUG) background_objects_to_remove = [] def remove_background_objects(a_background_objects_to_remove): for background_object in a_background_objects_to_remove: self.background_objects.remove(background_object) for background_object in self.background_objects: self.shutit_obj.log('Checking background object: ' + str(background_object),level=logging.DEBUG) state = background_object.check_background_command_state() self.shutit_obj.log('State is: ' + state,level=logging.DEBUG) if state in ('C','F','T'): background_objects_to_remove.append(background_object) self.background_objects_completed.append(background_object) elif state == 'S': # Running command exists self.shutit_obj.log('check_background_command_state returning False (S) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'S', background_object elif state == 'N': self.shutit_obj.log('UNSTARTED COMMAND! ' + str(background_object.sendspec.send),level=logging.DEBUG) unstarted_command_exists = True else: remove_background_objects(background_objects_to_remove) assert False, shutit_util.print_debug(msg='Un-handled: ' + state) if state == 'F': self.shutit_obj.log('check_background_command_state returning False (F) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'F', background_object remove_background_objects(background_objects_to_remove) self.shutit_obj.log('Checking background objects done.',level=logging.DEBUG) if unstarted_command_exists: # Start up an unstarted one (in order), and return False for background_object in self.background_objects: state = background_object.check_background_command_state() if state == 'N': background_object.run_background_command() self.shutit_obj.log('check_background_command_state returning False (N) for ' + str(background_object),level=logging.DEBUG) return False, 'N', background_object # Nothing left to do - return True. self.shutit_obj.log('check_background_command_state returning True (OK)',level=logging.DEBUG) return True, 'OK', None
python
def check_background_commands_complete(self): """Check whether any background commands are running or to be run. If none are, return True. If any are, return False. """ unstarted_command_exists = False self.shutit_obj.log('In check_background_commands_complete: all background objects: ' + str(self.background_objects),level=logging.DEBUG) self.shutit_obj.log('Login id: ' + str(self.login_id),level=logging.DEBUG) for background_object in self.background_objects: self.shutit_obj.log('Background object send: ' + str(background_object.sendspec.send),level=logging.DEBUG) background_objects_to_remove = [] def remove_background_objects(a_background_objects_to_remove): for background_object in a_background_objects_to_remove: self.background_objects.remove(background_object) for background_object in self.background_objects: self.shutit_obj.log('Checking background object: ' + str(background_object),level=logging.DEBUG) state = background_object.check_background_command_state() self.shutit_obj.log('State is: ' + state,level=logging.DEBUG) if state in ('C','F','T'): background_objects_to_remove.append(background_object) self.background_objects_completed.append(background_object) elif state == 'S': # Running command exists self.shutit_obj.log('check_background_command_state returning False (S) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'S', background_object elif state == 'N': self.shutit_obj.log('UNSTARTED COMMAND! ' + str(background_object.sendspec.send),level=logging.DEBUG) unstarted_command_exists = True else: remove_background_objects(background_objects_to_remove) assert False, shutit_util.print_debug(msg='Un-handled: ' + state) if state == 'F': self.shutit_obj.log('check_background_command_state returning False (F) for ' + str(background_object),level=logging.DEBUG) remove_background_objects(background_objects_to_remove) return False, 'F', background_object remove_background_objects(background_objects_to_remove) self.shutit_obj.log('Checking background objects done.',level=logging.DEBUG) if unstarted_command_exists: # Start up an unstarted one (in order), and return False for background_object in self.background_objects: state = background_object.check_background_command_state() if state == 'N': background_object.run_background_command() self.shutit_obj.log('check_background_command_state returning False (N) for ' + str(background_object),level=logging.DEBUG) return False, 'N', background_object # Nothing left to do - return True. self.shutit_obj.log('check_background_command_state returning True (OK)',level=logging.DEBUG) return True, 'OK', None
[ "def", "check_background_commands_complete", "(", "self", ")", ":", "unstarted_command_exists", "=", "False", "self", ".", "shutit_obj", ".", "log", "(", "'In check_background_commands_complete: all background objects: '", "+", "str", "(", "self", ".", "background_objects", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "shutit_obj", ".", "log", "(", "'Login id: '", "+", "str", "(", "self", ".", "login_id", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "for", "background_object", "in", "self", ".", "background_objects", ":", "self", ".", "shutit_obj", ".", "log", "(", "'Background object send: '", "+", "str", "(", "background_object", ".", "sendspec", ".", "send", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "background_objects_to_remove", "=", "[", "]", "def", "remove_background_objects", "(", "a_background_objects_to_remove", ")", ":", "for", "background_object", "in", "a_background_objects_to_remove", ":", "self", ".", "background_objects", ".", "remove", "(", "background_object", ")", "for", "background_object", "in", "self", ".", "background_objects", ":", "self", ".", "shutit_obj", ".", "log", "(", "'Checking background object: '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "state", "=", "background_object", ".", "check_background_command_state", "(", ")", "self", ".", "shutit_obj", ".", "log", "(", "'State is: '", "+", "state", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "state", "in", "(", "'C'", ",", "'F'", ",", "'T'", ")", ":", "background_objects_to_remove", ".", "append", "(", "background_object", ")", "self", ".", "background_objects_completed", ".", "append", "(", "background_object", ")", "elif", "state", "==", "'S'", ":", "# Running command exists", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning False (S) for '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "remove_background_objects", "(", "background_objects_to_remove", ")", "return", "False", ",", "'S'", ",", "background_object", "elif", "state", "==", "'N'", ":", "self", ".", "shutit_obj", ".", "log", "(", "'UNSTARTED COMMAND! '", "+", "str", "(", "background_object", ".", "sendspec", ".", "send", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "unstarted_command_exists", "=", "True", "else", ":", "remove_background_objects", "(", "background_objects_to_remove", ")", "assert", "False", ",", "shutit_util", ".", "print_debug", "(", "msg", "=", "'Un-handled: '", "+", "state", ")", "if", "state", "==", "'F'", ":", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning False (F) for '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "remove_background_objects", "(", "background_objects_to_remove", ")", "return", "False", ",", "'F'", ",", "background_object", "remove_background_objects", "(", "background_objects_to_remove", ")", "self", ".", "shutit_obj", ".", "log", "(", "'Checking background objects done.'", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "unstarted_command_exists", ":", "# Start up an unstarted one (in order), and return False", "for", "background_object", "in", "self", ".", "background_objects", ":", "state", "=", "background_object", ".", "check_background_command_state", "(", ")", "if", "state", "==", "'N'", ":", "background_object", ".", "run_background_command", "(", ")", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning False (N) for '", "+", "str", "(", "background_object", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "False", ",", "'N'", ",", "background_object", "# Nothing left to do - return True.", "self", ".", "shutit_obj", ".", "log", "(", "'check_background_command_state returning True (OK)'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", ",", "'OK'", ",", "None" ]
Check whether any background commands are running or to be run. If none are, return True. If any are, return False.
[ "Check", "whether", "any", "background", "commands", "are", "running", "or", "to", "be", "run", ".", "If", "none", "are", "return", "True", ".", "If", "any", "are", "return", "False", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_login_stack.py#L102-L149
train
konomae/lastpass-python
lastpass/vault.py
Vault.open_remote
def open_remote(cls, username, password, multifactor_password=None, client_id=None): """Fetches a blob from the server and creates a vault""" blob = cls.fetch_blob(username, password, multifactor_password, client_id) return cls.open(blob, username, password)
python
def open_remote(cls, username, password, multifactor_password=None, client_id=None): """Fetches a blob from the server and creates a vault""" blob = cls.fetch_blob(username, password, multifactor_password, client_id) return cls.open(blob, username, password)
[ "def", "open_remote", "(", "cls", ",", "username", ",", "password", ",", "multifactor_password", "=", "None", ",", "client_id", "=", "None", ")", ":", "blob", "=", "cls", ".", "fetch_blob", "(", "username", ",", "password", ",", "multifactor_password", ",", "client_id", ")", "return", "cls", ".", "open", "(", "blob", ",", "username", ",", "password", ")" ]
Fetches a blob from the server and creates a vault
[ "Fetches", "a", "blob", "from", "the", "server", "and", "creates", "a", "vault" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/vault.py#L9-L12
train
konomae/lastpass-python
lastpass/vault.py
Vault.open
def open(cls, blob, username, password): """Creates a vault from a blob object""" return cls(blob, blob.encryption_key(username, password))
python
def open(cls, blob, username, password): """Creates a vault from a blob object""" return cls(blob, blob.encryption_key(username, password))
[ "def", "open", "(", "cls", ",", "blob", ",", "username", ",", "password", ")", ":", "return", "cls", "(", "blob", ",", "blob", ".", "encryption_key", "(", "username", ",", "password", ")", ")" ]
Creates a vault from a blob object
[ "Creates", "a", "vault", "from", "a", "blob", "object" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/vault.py#L21-L23
train
konomae/lastpass-python
lastpass/vault.py
Vault.fetch_blob
def fetch_blob(cls, username, password, multifactor_password=None, client_id=None): """Just fetches the blob, could be used to store it locally""" session = fetcher.login(username, password, multifactor_password, client_id) blob = fetcher.fetch(session) fetcher.logout(session) return blob
python
def fetch_blob(cls, username, password, multifactor_password=None, client_id=None): """Just fetches the blob, could be used to store it locally""" session = fetcher.login(username, password, multifactor_password, client_id) blob = fetcher.fetch(session) fetcher.logout(session) return blob
[ "def", "fetch_blob", "(", "cls", ",", "username", ",", "password", ",", "multifactor_password", "=", "None", ",", "client_id", "=", "None", ")", ":", "session", "=", "fetcher", ".", "login", "(", "username", ",", "password", ",", "multifactor_password", ",", "client_id", ")", "blob", "=", "fetcher", ".", "fetch", "(", "session", ")", "fetcher", ".", "logout", "(", "session", ")", "return", "blob" ]
Just fetches the blob, could be used to store it locally
[ "Just", "fetches", "the", "blob", "could", "be", "used", "to", "store", "it", "locally" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/vault.py#L26-L32
train
konomae/lastpass-python
lastpass/parser.py
extract_chunks
def extract_chunks(blob): """Splits the blob into chucks grouped by kind.""" chunks = [] stream = BytesIO(blob.bytes) current_pos = stream.tell() stream.seek(0, 2) length = stream.tell() stream.seek(current_pos, 0) while stream.tell() < length: chunks.append(read_chunk(stream)) return chunks
python
def extract_chunks(blob): """Splits the blob into chucks grouped by kind.""" chunks = [] stream = BytesIO(blob.bytes) current_pos = stream.tell() stream.seek(0, 2) length = stream.tell() stream.seek(current_pos, 0) while stream.tell() < length: chunks.append(read_chunk(stream)) return chunks
[ "def", "extract_chunks", "(", "blob", ")", ":", "chunks", "=", "[", "]", "stream", "=", "BytesIO", "(", "blob", ".", "bytes", ")", "current_pos", "=", "stream", ".", "tell", "(", ")", "stream", ".", "seek", "(", "0", ",", "2", ")", "length", "=", "stream", ".", "tell", "(", ")", "stream", ".", "seek", "(", "current_pos", ",", "0", ")", "while", "stream", ".", "tell", "(", ")", "<", "length", ":", "chunks", ".", "append", "(", "read_chunk", "(", "stream", ")", ")", "return", "chunks" ]
Splits the blob into chucks grouped by kind.
[ "Splits", "the", "blob", "into", "chucks", "grouped", "by", "kind", "." ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L26-L37
train
konomae/lastpass-python
lastpass/parser.py
parse_ACCT
def parse_ACCT(chunk, encryption_key): """ Parses an account chunk, decrypts and creates an Account object. May return nil when the chunk does not represent an account. All secure notes are ACCTs but not all of them strore account information. """ # TODO: Make a test case that covers secure note account io = BytesIO(chunk.payload) id = read_item(io) name = decode_aes256_plain_auto(read_item(io), encryption_key) group = decode_aes256_plain_auto(read_item(io), encryption_key) url = decode_hex(read_item(io)) notes = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) username = decode_aes256_plain_auto(read_item(io), encryption_key) password = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) secure_note = read_item(io) # Parse secure note if secure_note == b'1': parsed = parse_secure_note_server(notes) if parsed.get('type') in ALLOWED_SECURE_NOTE_TYPES: url = parsed.get('url', url) username = parsed.get('username', username) password = parsed.get('password', password) return Account(id, name, username, password, url, group, notes)
python
def parse_ACCT(chunk, encryption_key): """ Parses an account chunk, decrypts and creates an Account object. May return nil when the chunk does not represent an account. All secure notes are ACCTs but not all of them strore account information. """ # TODO: Make a test case that covers secure note account io = BytesIO(chunk.payload) id = read_item(io) name = decode_aes256_plain_auto(read_item(io), encryption_key) group = decode_aes256_plain_auto(read_item(io), encryption_key) url = decode_hex(read_item(io)) notes = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) username = decode_aes256_plain_auto(read_item(io), encryption_key) password = decode_aes256_plain_auto(read_item(io), encryption_key) skip_item(io, 2) secure_note = read_item(io) # Parse secure note if secure_note == b'1': parsed = parse_secure_note_server(notes) if parsed.get('type') in ALLOWED_SECURE_NOTE_TYPES: url = parsed.get('url', url) username = parsed.get('username', username) password = parsed.get('password', password) return Account(id, name, username, password, url, group, notes)
[ "def", "parse_ACCT", "(", "chunk", ",", "encryption_key", ")", ":", "# TODO: Make a test case that covers secure note account", "io", "=", "BytesIO", "(", "chunk", ".", "payload", ")", "id", "=", "read_item", "(", "io", ")", "name", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "group", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "url", "=", "decode_hex", "(", "read_item", "(", "io", ")", ")", "notes", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "skip_item", "(", "io", ",", "2", ")", "username", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "password", "=", "decode_aes256_plain_auto", "(", "read_item", "(", "io", ")", ",", "encryption_key", ")", "skip_item", "(", "io", ",", "2", ")", "secure_note", "=", "read_item", "(", "io", ")", "# Parse secure note", "if", "secure_note", "==", "b'1'", ":", "parsed", "=", "parse_secure_note_server", "(", "notes", ")", "if", "parsed", ".", "get", "(", "'type'", ")", "in", "ALLOWED_SECURE_NOTE_TYPES", ":", "url", "=", "parsed", ".", "get", "(", "'url'", ",", "url", ")", "username", "=", "parsed", ".", "get", "(", "'username'", ",", "username", ")", "password", "=", "parsed", ".", "get", "(", "'password'", ",", "password", ")", "return", "Account", "(", "id", ",", "name", ",", "username", ",", "password", ",", "url", ",", "group", ",", "notes", ")" ]
Parses an account chunk, decrypts and creates an Account object. May return nil when the chunk does not represent an account. All secure notes are ACCTs but not all of them strore account information.
[ "Parses", "an", "account", "chunk", "decrypts", "and", "creates", "an", "Account", "object", ".", "May", "return", "nil", "when", "the", "chunk", "does", "not", "represent", "an", "account", ".", "All", "secure", "notes", "are", "ACCTs", "but", "not", "all", "of", "them", "strore", "account", "information", "." ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L40-L70
train
konomae/lastpass-python
lastpass/parser.py
parse_PRIK
def parse_PRIK(chunk, encryption_key): """Parse PRIK chunk which contains private RSA key""" decrypted = decode_aes256('cbc', encryption_key[:16], decode_hex(chunk.payload), encryption_key) hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decrypted).group('hex_key') rsa_key = RSA.importKey(decode_hex(hex_key)) rsa_key.dmp1 = rsa_key.d % (rsa_key.p - 1) rsa_key.dmq1 = rsa_key.d % (rsa_key.q - 1) rsa_key.iqmp = number.inverse(rsa_key.q, rsa_key.p) return rsa_key
python
def parse_PRIK(chunk, encryption_key): """Parse PRIK chunk which contains private RSA key""" decrypted = decode_aes256('cbc', encryption_key[:16], decode_hex(chunk.payload), encryption_key) hex_key = re.match(br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$', decrypted).group('hex_key') rsa_key = RSA.importKey(decode_hex(hex_key)) rsa_key.dmp1 = rsa_key.d % (rsa_key.p - 1) rsa_key.dmq1 = rsa_key.d % (rsa_key.q - 1) rsa_key.iqmp = number.inverse(rsa_key.q, rsa_key.p) return rsa_key
[ "def", "parse_PRIK", "(", "chunk", ",", "encryption_key", ")", ":", "decrypted", "=", "decode_aes256", "(", "'cbc'", ",", "encryption_key", "[", ":", "16", "]", ",", "decode_hex", "(", "chunk", ".", "payload", ")", ",", "encryption_key", ")", "hex_key", "=", "re", ".", "match", "(", "br'^LastPassPrivateKey<(?P<hex_key>.*)>LastPassPrivateKey$'", ",", "decrypted", ")", ".", "group", "(", "'hex_key'", ")", "rsa_key", "=", "RSA", ".", "importKey", "(", "decode_hex", "(", "hex_key", ")", ")", "rsa_key", ".", "dmp1", "=", "rsa_key", ".", "d", "%", "(", "rsa_key", ".", "p", "-", "1", ")", "rsa_key", ".", "dmq1", "=", "rsa_key", ".", "d", "%", "(", "rsa_key", ".", "q", "-", "1", ")", "rsa_key", ".", "iqmp", "=", "number", ".", "inverse", "(", "rsa_key", ".", "q", ",", "rsa_key", ".", "p", ")", "return", "rsa_key" ]
Parse PRIK chunk which contains private RSA key
[ "Parse", "PRIK", "chunk", "which", "contains", "private", "RSA", "key" ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L73-L87
train
konomae/lastpass-python
lastpass/parser.py
decode_aes256_cbc_base64
def decode_aes256_cbc_base64(data, encryption_key): """Decrypts base64 encoded AES-256 CBC bytes.""" if not data: return b'' else: # LastPass AES-256/CBC/base64 encryted string starts with an "!". # Next 24 bytes are the base64 encoded IV for the cipher. # Then comes the "|". # And the rest is the base64 encoded encrypted payload. return decode_aes256( 'cbc', decode_base64(data[1:25]), decode_base64(data[26:]), encryption_key)
python
def decode_aes256_cbc_base64(data, encryption_key): """Decrypts base64 encoded AES-256 CBC bytes.""" if not data: return b'' else: # LastPass AES-256/CBC/base64 encryted string starts with an "!". # Next 24 bytes are the base64 encoded IV for the cipher. # Then comes the "|". # And the rest is the base64 encoded encrypted payload. return decode_aes256( 'cbc', decode_base64(data[1:25]), decode_base64(data[26:]), encryption_key)
[ "def", "decode_aes256_cbc_base64", "(", "data", ",", "encryption_key", ")", ":", "if", "not", "data", ":", "return", "b''", "else", ":", "# LastPass AES-256/CBC/base64 encryted string starts with an \"!\".", "# Next 24 bytes are the base64 encoded IV for the cipher.", "# Then comes the \"|\".", "# And the rest is the base64 encoded encrypted payload.", "return", "decode_aes256", "(", "'cbc'", ",", "decode_base64", "(", "data", "[", "1", ":", "25", "]", ")", ",", "decode_base64", "(", "data", "[", "26", ":", "]", ")", ",", "encryption_key", ")" ]
Decrypts base64 encoded AES-256 CBC bytes.
[ "Decrypts", "base64", "encoded", "AES", "-", "256", "CBC", "bytes", "." ]
5063911b789868a1fd9db9922db82cdf156b938a
https://github.com/konomae/lastpass-python/blob/5063911b789868a1fd9db9922db82cdf156b938a/lastpass/parser.py#L253-L266
train
ehuggett/send-cli
sendclient/delete.py
api_delete
def api_delete(service, file_id, owner_token): """Delete a file already uploaded to Send""" service += 'api/delete/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'delete_token': owner_token}) r.raise_for_status() if r.text == 'OK': return True return False
python
def api_delete(service, file_id, owner_token): """Delete a file already uploaded to Send""" service += 'api/delete/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'delete_token': owner_token}) r.raise_for_status() if r.text == 'OK': return True return False
[ "def", "api_delete", "(", "service", ",", "file_id", ",", "owner_token", ")", ":", "service", "+=", "'api/delete/%s'", "%", "file_id", "r", "=", "requests", ".", "post", "(", "service", ",", "json", "=", "{", "'owner_token'", ":", "owner_token", ",", "'delete_token'", ":", "owner_token", "}", ")", "r", ".", "raise_for_status", "(", ")", "if", "r", ".", "text", "==", "'OK'", ":", "return", "True", "return", "False" ]
Delete a file already uploaded to Send
[ "Delete", "a", "file", "already", "uploaded", "to", "Send" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/delete.py#L3-L11
train
ehuggett/send-cli
sendclient/params.py
api_params
def api_params(service, file_id, owner_token, download_limit): """Change the download limit for a file hosted on a Send Server""" service += 'api/params/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'dlimit': download_limit}) r.raise_for_status() if r.text == 'OK': return True return False
python
def api_params(service, file_id, owner_token, download_limit): """Change the download limit for a file hosted on a Send Server""" service += 'api/params/%s' % file_id r = requests.post(service, json={'owner_token': owner_token, 'dlimit': download_limit}) r.raise_for_status() if r.text == 'OK': return True return False
[ "def", "api_params", "(", "service", ",", "file_id", ",", "owner_token", ",", "download_limit", ")", ":", "service", "+=", "'api/params/%s'", "%", "file_id", "r", "=", "requests", ".", "post", "(", "service", ",", "json", "=", "{", "'owner_token'", ":", "owner_token", ",", "'dlimit'", ":", "download_limit", "}", ")", "r", ".", "raise_for_status", "(", ")", "if", "r", ".", "text", "==", "'OK'", ":", "return", "True", "return", "False" ]
Change the download limit for a file hosted on a Send Server
[ "Change", "the", "download", "limit", "for", "a", "file", "hosted", "on", "a", "Send", "Server" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/params.py#L3-L11
train
ehuggett/send-cli
sendclient/download.py
api_download
def api_download(service, fileId, authorisation): '''Given a Send url, download and return the encrypted data and metadata''' data = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b') headers = {'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(authorisation)} url = service + 'api/download/' + fileId r = requests.get(url, headers=headers, stream=True) r.raise_for_status() content_length = int(r.headers['Content-length']) pbar = progbar(content_length) for chunk in r.iter_content(chunk_size=CHUNK_SIZE): data.write(chunk) pbar.update(len(chunk)) pbar.close() data.seek(0) return data
python
def api_download(service, fileId, authorisation): '''Given a Send url, download and return the encrypted data and metadata''' data = tempfile.SpooledTemporaryFile(max_size=SPOOL_SIZE, mode='w+b') headers = {'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(authorisation)} url = service + 'api/download/' + fileId r = requests.get(url, headers=headers, stream=True) r.raise_for_status() content_length = int(r.headers['Content-length']) pbar = progbar(content_length) for chunk in r.iter_content(chunk_size=CHUNK_SIZE): data.write(chunk) pbar.update(len(chunk)) pbar.close() data.seek(0) return data
[ "def", "api_download", "(", "service", ",", "fileId", ",", "authorisation", ")", ":", "data", "=", "tempfile", ".", "SpooledTemporaryFile", "(", "max_size", "=", "SPOOL_SIZE", ",", "mode", "=", "'w+b'", ")", "headers", "=", "{", "'Authorization'", ":", "'send-v1 '", "+", "unpadded_urlsafe_b64encode", "(", "authorisation", ")", "}", "url", "=", "service", "+", "'api/download/'", "+", "fileId", "r", "=", "requests", ".", "get", "(", "url", ",", "headers", "=", "headers", ",", "stream", "=", "True", ")", "r", ".", "raise_for_status", "(", ")", "content_length", "=", "int", "(", "r", ".", "headers", "[", "'Content-length'", "]", ")", "pbar", "=", "progbar", "(", "content_length", ")", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "CHUNK_SIZE", ")", ":", "data", ".", "write", "(", "chunk", ")", "pbar", ".", "update", "(", "len", "(", "chunk", ")", ")", "pbar", ".", "close", "(", ")", "data", ".", "seek", "(", "0", ")", "return", "data" ]
Given a Send url, download and return the encrypted data and metadata
[ "Given", "a", "Send", "url", "download", "and", "return", "the", "encrypted", "data", "and", "metadata" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/download.py#L13-L31
train
ehuggett/send-cli
sendclient/download.py
decrypt_filedata
def decrypt_filedata(data, keys): '''Decrypts a file from Send''' # The last 16 bytes / 128 bits of data is the GCM tag # https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :- # 7. Let ciphertext be equal to C | T, where '|' denotes concatenation. data.seek(-16, 2) tag = data.read() # now truncate the file to only contain encrypted data data.seek(-16, 2) data.truncate() data.seek(0) plain = tempfile.NamedTemporaryFile(mode='w+b', delete=False) pbar = progbar(fileSize(data)) obj = Cryptodome.Cipher.AES.new(keys.encryptKey, Cryptodome.Cipher.AES.MODE_GCM, keys.encryptIV) prev_chunk = b'' for chunk in iter(lambda: data.read(CHUNK_SIZE), b''): plain.write(obj.decrypt(prev_chunk)) pbar.update(len(chunk)) prev_chunk = chunk plain.write(obj.decrypt_and_verify(prev_chunk, tag)) data.close() pbar.close() plain.seek(0) return plain
python
def decrypt_filedata(data, keys): '''Decrypts a file from Send''' # The last 16 bytes / 128 bits of data is the GCM tag # https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :- # 7. Let ciphertext be equal to C | T, where '|' denotes concatenation. data.seek(-16, 2) tag = data.read() # now truncate the file to only contain encrypted data data.seek(-16, 2) data.truncate() data.seek(0) plain = tempfile.NamedTemporaryFile(mode='w+b', delete=False) pbar = progbar(fileSize(data)) obj = Cryptodome.Cipher.AES.new(keys.encryptKey, Cryptodome.Cipher.AES.MODE_GCM, keys.encryptIV) prev_chunk = b'' for chunk in iter(lambda: data.read(CHUNK_SIZE), b''): plain.write(obj.decrypt(prev_chunk)) pbar.update(len(chunk)) prev_chunk = chunk plain.write(obj.decrypt_and_verify(prev_chunk, tag)) data.close() pbar.close() plain.seek(0) return plain
[ "def", "decrypt_filedata", "(", "data", ",", "keys", ")", ":", "# The last 16 bytes / 128 bits of data is the GCM tag", "# https://www.w3.org/TR/WebCryptoAPI/#aes-gcm-operations :-", "# 7. Let ciphertext be equal to C | T, where '|' denotes concatenation.", "data", ".", "seek", "(", "-", "16", ",", "2", ")", "tag", "=", "data", ".", "read", "(", ")", "# now truncate the file to only contain encrypted data", "data", ".", "seek", "(", "-", "16", ",", "2", ")", "data", ".", "truncate", "(", ")", "data", ".", "seek", "(", "0", ")", "plain", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'w+b'", ",", "delete", "=", "False", ")", "pbar", "=", "progbar", "(", "fileSize", "(", "data", ")", ")", "obj", "=", "Cryptodome", ".", "Cipher", ".", "AES", ".", "new", "(", "keys", ".", "encryptKey", ",", "Cryptodome", ".", "Cipher", ".", "AES", ".", "MODE_GCM", ",", "keys", ".", "encryptIV", ")", "prev_chunk", "=", "b''", "for", "chunk", "in", "iter", "(", "lambda", ":", "data", ".", "read", "(", "CHUNK_SIZE", ")", ",", "b''", ")", ":", "plain", ".", "write", "(", "obj", ".", "decrypt", "(", "prev_chunk", ")", ")", "pbar", ".", "update", "(", "len", "(", "chunk", ")", ")", "prev_chunk", "=", "chunk", "plain", ".", "write", "(", "obj", ".", "decrypt_and_verify", "(", "prev_chunk", ",", "tag", ")", ")", "data", ".", "close", "(", ")", "pbar", ".", "close", "(", ")", "plain", ".", "seek", "(", "0", ")", "return", "plain" ]
Decrypts a file from Send
[ "Decrypts", "a", "file", "from", "Send" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/download.py#L33-L62
train
ehuggett/send-cli
sendclient/download.py
sign_nonce
def sign_nonce(key, nonce): ''' sign the server nonce from the WWW-Authenticate header with an authKey''' # HMAC.new(key, msg='', digestmod=None) return Cryptodome.Hash.HMAC.new(key, nonce, digestmod=Cryptodome.Hash.SHA256).digest()
python
def sign_nonce(key, nonce): ''' sign the server nonce from the WWW-Authenticate header with an authKey''' # HMAC.new(key, msg='', digestmod=None) return Cryptodome.Hash.HMAC.new(key, nonce, digestmod=Cryptodome.Hash.SHA256).digest()
[ "def", "sign_nonce", "(", "key", ",", "nonce", ")", ":", "# HMAC.new(key, msg='', digestmod=None)", "return", "Cryptodome", ".", "Hash", ".", "HMAC", ".", "new", "(", "key", ",", "nonce", ",", "digestmod", "=", "Cryptodome", ".", "Hash", ".", "SHA256", ")", ".", "digest", "(", ")" ]
sign the server nonce from the WWW-Authenticate header with an authKey
[ "sign", "the", "server", "nonce", "from", "the", "WWW", "-", "Authenticate", "header", "with", "an", "authKey" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/download.py#L95-L98
train
ehuggett/send-cli
sendclient/password.py
api_password
def api_password(service, fileId , ownerToken, newAuthKey): ''' changes the authKey required to download a file hosted on a send server ''' service += 'api/password/%s' % fileId auth = sendclient.common.unpadded_urlsafe_b64encode(newAuthKey) r = requests.post(service, json={'owner_token': ownerToken, 'auth': auth}) r.raise_for_status() if r.text == 'OK': return True return False
python
def api_password(service, fileId , ownerToken, newAuthKey): ''' changes the authKey required to download a file hosted on a send server ''' service += 'api/password/%s' % fileId auth = sendclient.common.unpadded_urlsafe_b64encode(newAuthKey) r = requests.post(service, json={'owner_token': ownerToken, 'auth': auth}) r.raise_for_status() if r.text == 'OK': return True return False
[ "def", "api_password", "(", "service", ",", "fileId", ",", "ownerToken", ",", "newAuthKey", ")", ":", "service", "+=", "'api/password/%s'", "%", "fileId", "auth", "=", "sendclient", ".", "common", ".", "unpadded_urlsafe_b64encode", "(", "newAuthKey", ")", "r", "=", "requests", ".", "post", "(", "service", ",", "json", "=", "{", "'owner_token'", ":", "ownerToken", ",", "'auth'", ":", "auth", "}", ")", "r", ".", "raise_for_status", "(", ")", "if", "r", ".", "text", "==", "'OK'", ":", "return", "True", "return", "False" ]
changes the authKey required to download a file hosted on a send server
[ "changes", "the", "authKey", "required", "to", "download", "a", "file", "hosted", "on", "a", "send", "server" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/password.py#L4-L16
train
ehuggett/send-cli
sendclient/password.py
set_password
def set_password(url, ownerToken, password): ''' set or change the password required to download a file hosted on a send server. ''' service, fileId, key = sendclient.common.splitkeyurl(url) rawKey = sendclient.common.unpadded_urlsafe_b64decode(key) keys = sendclient.common.secretKeys(rawKey, password, url) return api_password(service, fileId, ownerToken, keys.newAuthKey)
python
def set_password(url, ownerToken, password): ''' set or change the password required to download a file hosted on a send server. ''' service, fileId, key = sendclient.common.splitkeyurl(url) rawKey = sendclient.common.unpadded_urlsafe_b64decode(key) keys = sendclient.common.secretKeys(rawKey, password, url) return api_password(service, fileId, ownerToken, keys.newAuthKey)
[ "def", "set_password", "(", "url", ",", "ownerToken", ",", "password", ")", ":", "service", ",", "fileId", ",", "key", "=", "sendclient", ".", "common", ".", "splitkeyurl", "(", "url", ")", "rawKey", "=", "sendclient", ".", "common", ".", "unpadded_urlsafe_b64decode", "(", "key", ")", "keys", "=", "sendclient", ".", "common", ".", "secretKeys", "(", "rawKey", ",", "password", ",", "url", ")", "return", "api_password", "(", "service", ",", "fileId", ",", "ownerToken", ",", "keys", ".", "newAuthKey", ")" ]
set or change the password required to download a file hosted on a send server.
[ "set", "or", "change", "the", "password", "required", "to", "download", "a", "file", "hosted", "on", "a", "send", "server", "." ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/password.py#L18-L27
train
ehuggett/send-cli
sendclient/common.py
splitkeyurl
def splitkeyurl(url): ''' Splits a Send url into key, urlid and 'prefix' for the Send server Should handle any hostname, but will brake on key & id length changes ''' key = url[-22:] urlid = url[-34:-24] service = url[:-43] return service, urlid, key
python
def splitkeyurl(url): ''' Splits a Send url into key, urlid and 'prefix' for the Send server Should handle any hostname, but will brake on key & id length changes ''' key = url[-22:] urlid = url[-34:-24] service = url[:-43] return service, urlid, key
[ "def", "splitkeyurl", "(", "url", ")", ":", "key", "=", "url", "[", "-", "22", ":", "]", "urlid", "=", "url", "[", "-", "34", ":", "-", "24", "]", "service", "=", "url", "[", ":", "-", "43", "]", "return", "service", ",", "urlid", ",", "key" ]
Splits a Send url into key, urlid and 'prefix' for the Send server Should handle any hostname, but will brake on key & id length changes
[ "Splits", "a", "Send", "url", "into", "key", "urlid", "and", "prefix", "for", "the", "Send", "server", "Should", "handle", "any", "hostname", "but", "will", "brake", "on", "key", "&", "id", "length", "changes" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/common.py#L9-L17
train
ehuggett/send-cli
sendclient/upload.py
api_upload
def api_upload(service, encData, encMeta, keys): ''' Uploads data to Send. Caution! Data is uploaded as given, this function will not encrypt it for you ''' service += 'api/upload' files = requests_toolbelt.MultipartEncoder(fields={'file': ('blob', encData, 'application/octet-stream') }) pbar = progbar(files.len) monitor = requests_toolbelt.MultipartEncoderMonitor(files, lambda files: pbar.update(monitor.bytes_read - pbar.n)) headers = { 'X-File-Metadata' : unpadded_urlsafe_b64encode(encMeta), 'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(keys.authKey), 'Content-type' : monitor.content_type } r = requests.post(service, data=monitor, headers=headers, stream=True) r.raise_for_status() pbar.close() body_json = r.json() secretUrl = body_json['url'] + '#' + unpadded_urlsafe_b64encode(keys.secretKey) fileId = body_json['id'] fileNonce = unpadded_urlsafe_b64decode(r.headers['WWW-Authenticate'].replace('send-v1 ', '')) try: owner_token = body_json['owner'] except: owner_token = body_json['delete'] return secretUrl, fileId, fileNonce, owner_token
python
def api_upload(service, encData, encMeta, keys): ''' Uploads data to Send. Caution! Data is uploaded as given, this function will not encrypt it for you ''' service += 'api/upload' files = requests_toolbelt.MultipartEncoder(fields={'file': ('blob', encData, 'application/octet-stream') }) pbar = progbar(files.len) monitor = requests_toolbelt.MultipartEncoderMonitor(files, lambda files: pbar.update(monitor.bytes_read - pbar.n)) headers = { 'X-File-Metadata' : unpadded_urlsafe_b64encode(encMeta), 'Authorization' : 'send-v1 ' + unpadded_urlsafe_b64encode(keys.authKey), 'Content-type' : monitor.content_type } r = requests.post(service, data=monitor, headers=headers, stream=True) r.raise_for_status() pbar.close() body_json = r.json() secretUrl = body_json['url'] + '#' + unpadded_urlsafe_b64encode(keys.secretKey) fileId = body_json['id'] fileNonce = unpadded_urlsafe_b64decode(r.headers['WWW-Authenticate'].replace('send-v1 ', '')) try: owner_token = body_json['owner'] except: owner_token = body_json['delete'] return secretUrl, fileId, fileNonce, owner_token
[ "def", "api_upload", "(", "service", ",", "encData", ",", "encMeta", ",", "keys", ")", ":", "service", "+=", "'api/upload'", "files", "=", "requests_toolbelt", ".", "MultipartEncoder", "(", "fields", "=", "{", "'file'", ":", "(", "'blob'", ",", "encData", ",", "'application/octet-stream'", ")", "}", ")", "pbar", "=", "progbar", "(", "files", ".", "len", ")", "monitor", "=", "requests_toolbelt", ".", "MultipartEncoderMonitor", "(", "files", ",", "lambda", "files", ":", "pbar", ".", "update", "(", "monitor", ".", "bytes_read", "-", "pbar", ".", "n", ")", ")", "headers", "=", "{", "'X-File-Metadata'", ":", "unpadded_urlsafe_b64encode", "(", "encMeta", ")", ",", "'Authorization'", ":", "'send-v1 '", "+", "unpadded_urlsafe_b64encode", "(", "keys", ".", "authKey", ")", ",", "'Content-type'", ":", "monitor", ".", "content_type", "}", "r", "=", "requests", ".", "post", "(", "service", ",", "data", "=", "monitor", ",", "headers", "=", "headers", ",", "stream", "=", "True", ")", "r", ".", "raise_for_status", "(", ")", "pbar", ".", "close", "(", ")", "body_json", "=", "r", ".", "json", "(", ")", "secretUrl", "=", "body_json", "[", "'url'", "]", "+", "'#'", "+", "unpadded_urlsafe_b64encode", "(", "keys", ".", "secretKey", ")", "fileId", "=", "body_json", "[", "'id'", "]", "fileNonce", "=", "unpadded_urlsafe_b64decode", "(", "r", ".", "headers", "[", "'WWW-Authenticate'", "]", ".", "replace", "(", "'send-v1 '", ",", "''", ")", ")", "try", ":", "owner_token", "=", "body_json", "[", "'owner'", "]", "except", ":", "owner_token", "=", "body_json", "[", "'delete'", "]", "return", "secretUrl", ",", "fileId", ",", "fileNonce", ",", "owner_token" ]
Uploads data to Send. Caution! Data is uploaded as given, this function will not encrypt it for you
[ "Uploads", "data", "to", "Send", ".", "Caution!", "Data", "is", "uploaded", "as", "given", "this", "function", "will", "not", "encrypt", "it", "for", "you" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/upload.py#L45-L73
train
ehuggett/send-cli
sendclient/upload.py
send_file
def send_file(service, file, fileName=None, password=None, ignoreVersion=False): if checkServerVersion(service, ignoreVersion=ignoreVersion) == False: print('\033[1;41m!!! Potentially incompatible server version !!!\033[0m') ''' Encrypt & Upload a file to send and return the download URL''' fileName = fileName if fileName != None else os.path.basename(file.name) print('Encrypting data from "' + fileName + '"') keys = secretKeys() encData = encrypt_file(file, keys) encMeta = encrypt_metadata(keys, fileName) print('Uploading "' + fileName + '"') secretUrl, fileId, fileNonce, owner_token = api_upload(service, encData, encMeta, keys) if password != None: print('Setting password') sendclient.password.set_password(secretUrl, owner_token, password) return secretUrl, fileId, owner_token
python
def send_file(service, file, fileName=None, password=None, ignoreVersion=False): if checkServerVersion(service, ignoreVersion=ignoreVersion) == False: print('\033[1;41m!!! Potentially incompatible server version !!!\033[0m') ''' Encrypt & Upload a file to send and return the download URL''' fileName = fileName if fileName != None else os.path.basename(file.name) print('Encrypting data from "' + fileName + '"') keys = secretKeys() encData = encrypt_file(file, keys) encMeta = encrypt_metadata(keys, fileName) print('Uploading "' + fileName + '"') secretUrl, fileId, fileNonce, owner_token = api_upload(service, encData, encMeta, keys) if password != None: print('Setting password') sendclient.password.set_password(secretUrl, owner_token, password) return secretUrl, fileId, owner_token
[ "def", "send_file", "(", "service", ",", "file", ",", "fileName", "=", "None", ",", "password", "=", "None", ",", "ignoreVersion", "=", "False", ")", ":", "if", "checkServerVersion", "(", "service", ",", "ignoreVersion", "=", "ignoreVersion", ")", "==", "False", ":", "print", "(", "'\\033[1;41m!!! Potentially incompatible server version !!!\\033[0m'", ")", "fileName", "=", "fileName", "if", "fileName", "!=", "None", "else", "os", ".", "path", ".", "basename", "(", "file", ".", "name", ")", "print", "(", "'Encrypting data from \"'", "+", "fileName", "+", "'\"'", ")", "keys", "=", "secretKeys", "(", ")", "encData", "=", "encrypt_file", "(", "file", ",", "keys", ")", "encMeta", "=", "encrypt_metadata", "(", "keys", ",", "fileName", ")", "print", "(", "'Uploading \"'", "+", "fileName", "+", "'\"'", ")", "secretUrl", ",", "fileId", ",", "fileNonce", ",", "owner_token", "=", "api_upload", "(", "service", ",", "encData", ",", "encMeta", ",", "keys", ")", "if", "password", "!=", "None", ":", "print", "(", "'Setting password'", ")", "sendclient", ".", "password", ".", "set_password", "(", "secretUrl", ",", "owner_token", ",", "password", ")", "return", "secretUrl", ",", "fileId", ",", "owner_token" ]
Encrypt & Upload a file to send and return the download URL
[ "Encrypt", "&", "Upload", "a", "file", "to", "send", "and", "return", "the", "download", "URL" ]
7f9458299f42e3c558f00e77cf9d3aa9dd857457
https://github.com/ehuggett/send-cli/blob/7f9458299f42e3c558f00e77cf9d3aa9dd857457/sendclient/upload.py#L80-L100
train
haochi/personalcapital
personalcapital/personalcapital.py
PersonalCapital.fetch
def fetch(self, endpoint, data = None): """ for getting data after logged in """ payload = { "lastServerChangeId": "-1", "csrf": self.__csrf, "apiClient": "WEB" } if data is not None: payload.update(data) return self.post(endpoint, payload)
python
def fetch(self, endpoint, data = None): """ for getting data after logged in """ payload = { "lastServerChangeId": "-1", "csrf": self.__csrf, "apiClient": "WEB" } if data is not None: payload.update(data) return self.post(endpoint, payload)
[ "def", "fetch", "(", "self", ",", "endpoint", ",", "data", "=", "None", ")", ":", "payload", "=", "{", "\"lastServerChangeId\"", ":", "\"-1\"", ",", "\"csrf\"", ":", "self", ".", "__csrf", ",", "\"apiClient\"", ":", "\"WEB\"", "}", "if", "data", "is", "not", "None", ":", "payload", ".", "update", "(", "data", ")", "return", "self", ".", "post", "(", "endpoint", ",", "payload", ")" ]
for getting data after logged in
[ "for", "getting", "data", "after", "logged", "in" ]
2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f
https://github.com/haochi/personalcapital/blob/2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f/personalcapital/personalcapital.py#L73-L85
train
haochi/personalcapital
personalcapital/personalcapital.py
PersonalCapital.__identify_user
def __identify_user(self, username, csrf): """ Returns reusable CSRF code and the auth level as a 2-tuple """ data = { "username": username, "csrf": csrf, "apiClient": "WEB", "bindDevice": "false", "skipLinkAccount": "false", "redirectTo": "", "skipFirstUse": "", "referrerId": "", } r = self.post("/login/identifyUser", data) if r.status_code == requests.codes.ok: result = r.json() new_csrf = getSpHeaderValue(result, CSRF_KEY) auth_level = getSpHeaderValue(result, AUTH_LEVEL_KEY) return (new_csrf, auth_level) return (None, None)
python
def __identify_user(self, username, csrf): """ Returns reusable CSRF code and the auth level as a 2-tuple """ data = { "username": username, "csrf": csrf, "apiClient": "WEB", "bindDevice": "false", "skipLinkAccount": "false", "redirectTo": "", "skipFirstUse": "", "referrerId": "", } r = self.post("/login/identifyUser", data) if r.status_code == requests.codes.ok: result = r.json() new_csrf = getSpHeaderValue(result, CSRF_KEY) auth_level = getSpHeaderValue(result, AUTH_LEVEL_KEY) return (new_csrf, auth_level) return (None, None)
[ "def", "__identify_user", "(", "self", ",", "username", ",", "csrf", ")", ":", "data", "=", "{", "\"username\"", ":", "username", ",", "\"csrf\"", ":", "csrf", ",", "\"apiClient\"", ":", "\"WEB\"", ",", "\"bindDevice\"", ":", "\"false\"", ",", "\"skipLinkAccount\"", ":", "\"false\"", ",", "\"redirectTo\"", ":", "\"\"", ",", "\"skipFirstUse\"", ":", "\"\"", ",", "\"referrerId\"", ":", "\"\"", ",", "}", "r", "=", "self", ".", "post", "(", "\"/login/identifyUser\"", ",", "data", ")", "if", "r", ".", "status_code", "==", "requests", ".", "codes", ".", "ok", ":", "result", "=", "r", ".", "json", "(", ")", "new_csrf", "=", "getSpHeaderValue", "(", "result", ",", "CSRF_KEY", ")", "auth_level", "=", "getSpHeaderValue", "(", "result", ",", "AUTH_LEVEL_KEY", ")", "return", "(", "new_csrf", ",", "auth_level", ")", "return", "(", "None", ",", "None", ")" ]
Returns reusable CSRF code and the auth level as a 2-tuple
[ "Returns", "reusable", "CSRF", "code", "and", "the", "auth", "level", "as", "a", "2", "-", "tuple" ]
2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f
https://github.com/haochi/personalcapital/blob/2cdbab3f0a95cbc15aaab7a265f2634bc70dee9f/personalcapital/personalcapital.py#L114-L137
train
linkedin/shiv
setup.py
get_args
def get_args(cls, dist, header=None): """Overrides easy_install.ScriptWriter.get_args This method avoids using pkg_resources to map a named entry_point to a callable at invocation time. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): # ensure_safe_name if re.search(r'[\\/]', name): raise ValueError("Path separators not allowed in script names") script_text = TEMPLATE.format( ep.module_name, ep.attrs[0], '.'.join(ep.attrs), spec, group, name, ) args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res
python
def get_args(cls, dist, header=None): """Overrides easy_install.ScriptWriter.get_args This method avoids using pkg_resources to map a named entry_point to a callable at invocation time. """ if header is None: header = cls.get_header() spec = str(dist.as_requirement()) for type_ in 'console', 'gui': group = type_ + '_scripts' for name, ep in dist.get_entry_map(group).items(): # ensure_safe_name if re.search(r'[\\/]', name): raise ValueError("Path separators not allowed in script names") script_text = TEMPLATE.format( ep.module_name, ep.attrs[0], '.'.join(ep.attrs), spec, group, name, ) args = cls._get_script_args(type_, name, header, script_text) for res in args: yield res
[ "def", "get_args", "(", "cls", ",", "dist", ",", "header", "=", "None", ")", ":", "if", "header", "is", "None", ":", "header", "=", "cls", ".", "get_header", "(", ")", "spec", "=", "str", "(", "dist", ".", "as_requirement", "(", ")", ")", "for", "type_", "in", "'console'", ",", "'gui'", ":", "group", "=", "type_", "+", "'_scripts'", "for", "name", ",", "ep", "in", "dist", ".", "get_entry_map", "(", "group", ")", ".", "items", "(", ")", ":", "# ensure_safe_name", "if", "re", ".", "search", "(", "r'[\\\\/]'", ",", "name", ")", ":", "raise", "ValueError", "(", "\"Path separators not allowed in script names\"", ")", "script_text", "=", "TEMPLATE", ".", "format", "(", "ep", ".", "module_name", ",", "ep", ".", "attrs", "[", "0", "]", ",", "'.'", ".", "join", "(", "ep", ".", "attrs", ")", ",", "spec", ",", "group", ",", "name", ",", ")", "args", "=", "cls", ".", "_get_script_args", "(", "type_", ",", "name", ",", "header", ",", "script_text", ")", "for", "res", "in", "args", ":", "yield", "res" ]
Overrides easy_install.ScriptWriter.get_args This method avoids using pkg_resources to map a named entry_point to a callable at invocation time.
[ "Overrides", "easy_install", ".", "ScriptWriter", ".", "get_args" ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/setup.py#L47-L72
train
linkedin/shiv
src/shiv/pip.py
clean_pip_env
def clean_pip_env() -> Generator[None, None, None]: """A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment. Since shiv installs via `--target`, we need to ignore venv requirements if they exist. """ require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None) try: yield finally: if require_venv is not None: os.environ[PIP_REQUIRE_VIRTUALENV] = require_venv
python
def clean_pip_env() -> Generator[None, None, None]: """A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment. Since shiv installs via `--target`, we need to ignore venv requirements if they exist. """ require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None) try: yield finally: if require_venv is not None: os.environ[PIP_REQUIRE_VIRTUALENV] = require_venv
[ "def", "clean_pip_env", "(", ")", "->", "Generator", "[", "None", ",", "None", ",", "None", "]", ":", "require_venv", "=", "os", ".", "environ", ".", "pop", "(", "PIP_REQUIRE_VIRTUALENV", ",", "None", ")", "try", ":", "yield", "finally", ":", "if", "require_venv", "is", "not", "None", ":", "os", ".", "environ", "[", "PIP_REQUIRE_VIRTUALENV", "]", "=", "require_venv" ]
A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment. Since shiv installs via `--target`, we need to ignore venv requirements if they exist.
[ "A", "context", "manager", "for", "temporarily", "removing", "PIP_REQUIRE_VIRTUALENV", "from", "the", "environment", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/pip.py#L15-L28
train
linkedin/shiv
src/shiv/pip.py
install
def install(args: List[str]) -> None: """`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packages: numpy Successfully installed numpy-1.13.3 """ with clean_pip_env(): # if being invoked as a pyz, we must ensure we have access to our own # site-packages when subprocessing since there is no guarantee that pip # will be available subprocess_env = os.environ.copy() sitedir_index = _first_sitedir_index() _extend_python_path(subprocess_env, sys.path[sitedir_index:]) process = subprocess.Popen( [sys.executable, "-m", "pip", "--disable-pip-version-check", "install"] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=subprocess_env, ) for output in process.stdout: if output: click.echo(output.decode().rstrip()) if process.wait() > 0: sys.exit(PIP_INSTALL_ERROR)
python
def install(args: List[str]) -> None: """`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packages: numpy Successfully installed numpy-1.13.3 """ with clean_pip_env(): # if being invoked as a pyz, we must ensure we have access to our own # site-packages when subprocessing since there is no guarantee that pip # will be available subprocess_env = os.environ.copy() sitedir_index = _first_sitedir_index() _extend_python_path(subprocess_env, sys.path[sitedir_index:]) process = subprocess.Popen( [sys.executable, "-m", "pip", "--disable-pip-version-check", "install"] + args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=subprocess_env, ) for output in process.stdout: if output: click.echo(output.decode().rstrip()) if process.wait() > 0: sys.exit(PIP_INSTALL_ERROR)
[ "def", "install", "(", "args", ":", "List", "[", "str", "]", ")", "->", "None", ":", "with", "clean_pip_env", "(", ")", ":", "# if being invoked as a pyz, we must ensure we have access to our own", "# site-packages when subprocessing since there is no guarantee that pip", "# will be available", "subprocess_env", "=", "os", ".", "environ", ".", "copy", "(", ")", "sitedir_index", "=", "_first_sitedir_index", "(", ")", "_extend_python_path", "(", "subprocess_env", ",", "sys", ".", "path", "[", "sitedir_index", ":", "]", ")", "process", "=", "subprocess", ".", "Popen", "(", "[", "sys", ".", "executable", ",", "\"-m\"", ",", "\"pip\"", ",", "\"--disable-pip-version-check\"", ",", "\"install\"", "]", "+", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "STDOUT", ",", "env", "=", "subprocess_env", ",", ")", "for", "output", "in", "process", ".", "stdout", ":", "if", "output", ":", "click", ".", "echo", "(", "output", ".", "decode", "(", ")", ".", "rstrip", "(", ")", ")", "if", "process", ".", "wait", "(", ")", ">", "0", ":", "sys", ".", "exit", "(", "PIP_INSTALL_ERROR", ")" ]
`pip install` as a function. Accepts a list of pip arguments. .. code-block:: py >>> install(['numpy', '--target', 'site-packages']) Collecting numpy Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB) 100% || 16.9MB 53kB/s Installing collected packages: numpy Successfully installed numpy-1.13.3
[ "pip", "install", "as", "a", "function", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/pip.py#L31-L67
train
linkedin/shiv
src/shiv/bootstrap/__init__.py
current_zipfile
def current_zipfile(): """A function to vend the current zipfile, if any""" if zipfile.is_zipfile(sys.argv[0]): fd = open(sys.argv[0], "rb") return zipfile.ZipFile(fd)
python
def current_zipfile(): """A function to vend the current zipfile, if any""" if zipfile.is_zipfile(sys.argv[0]): fd = open(sys.argv[0], "rb") return zipfile.ZipFile(fd)
[ "def", "current_zipfile", "(", ")", ":", "if", "zipfile", ".", "is_zipfile", "(", "sys", ".", "argv", "[", "0", "]", ")", ":", "fd", "=", "open", "(", "sys", ".", "argv", "[", "0", "]", ",", "\"rb\"", ")", "return", "zipfile", ".", "ZipFile", "(", "fd", ")" ]
A function to vend the current zipfile, if any
[ "A", "function", "to", "vend", "the", "current", "zipfile", "if", "any" ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/__init__.py#L17-L21
train
linkedin/shiv
src/shiv/bootstrap/__init__.py
extract_site_packages
def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False): """Extract everything in site-packages to a specified path. :param ZipFile archive: The zipfile object we are bootstrapping from. :param Path target_path: The path to extract our zip to. """ parent = target_path.parent target_path_tmp = Path(parent, target_path.stem + ".tmp") lock = Path(parent, target_path.stem + ".lock") # If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir if not parent.exists(): parent.mkdir(parents=True, exist_ok=True) with FileLock(lock): # we acquired a lock, it's possible that prior invocation was holding the lock and has # completed bootstrapping, so let's check (again) if we need to do any work if not target_path.exists() or force: # extract our site-packages for filename in archive.namelist(): if filename.startswith("site-packages"): archive.extract(filename, target_path_tmp) if compile_pyc: compileall.compile_dir(target_path_tmp, quiet=2, workers=compile_workers) # if using `force` we will need to delete our target path if target_path.exists(): shutil.rmtree(str(target_path)) # atomic move shutil.move(str(target_path_tmp), str(target_path))
python
def extract_site_packages(archive, target_path, compile_pyc, compile_workers=0, force=False): """Extract everything in site-packages to a specified path. :param ZipFile archive: The zipfile object we are bootstrapping from. :param Path target_path: The path to extract our zip to. """ parent = target_path.parent target_path_tmp = Path(parent, target_path.stem + ".tmp") lock = Path(parent, target_path.stem + ".lock") # If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir if not parent.exists(): parent.mkdir(parents=True, exist_ok=True) with FileLock(lock): # we acquired a lock, it's possible that prior invocation was holding the lock and has # completed bootstrapping, so let's check (again) if we need to do any work if not target_path.exists() or force: # extract our site-packages for filename in archive.namelist(): if filename.startswith("site-packages"): archive.extract(filename, target_path_tmp) if compile_pyc: compileall.compile_dir(target_path_tmp, quiet=2, workers=compile_workers) # if using `force` we will need to delete our target path if target_path.exists(): shutil.rmtree(str(target_path)) # atomic move shutil.move(str(target_path_tmp), str(target_path))
[ "def", "extract_site_packages", "(", "archive", ",", "target_path", ",", "compile_pyc", ",", "compile_workers", "=", "0", ",", "force", "=", "False", ")", ":", "parent", "=", "target_path", ".", "parent", "target_path_tmp", "=", "Path", "(", "parent", ",", "target_path", ".", "stem", "+", "\".tmp\"", ")", "lock", "=", "Path", "(", "parent", ",", "target_path", ".", "stem", "+", "\".lock\"", ")", "# If this is the first time that a pyz is being extracted, we'll need to create the ~/.shiv dir", "if", "not", "parent", ".", "exists", "(", ")", ":", "parent", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "with", "FileLock", "(", "lock", ")", ":", "# we acquired a lock, it's possible that prior invocation was holding the lock and has", "# completed bootstrapping, so let's check (again) if we need to do any work", "if", "not", "target_path", ".", "exists", "(", ")", "or", "force", ":", "# extract our site-packages", "for", "filename", "in", "archive", ".", "namelist", "(", ")", ":", "if", "filename", ".", "startswith", "(", "\"site-packages\"", ")", ":", "archive", ".", "extract", "(", "filename", ",", "target_path_tmp", ")", "if", "compile_pyc", ":", "compileall", ".", "compile_dir", "(", "target_path_tmp", ",", "quiet", "=", "2", ",", "workers", "=", "compile_workers", ")", "# if using `force` we will need to delete our target path", "if", "target_path", ".", "exists", "(", ")", ":", "shutil", ".", "rmtree", "(", "str", "(", "target_path", ")", ")", "# atomic move", "shutil", ".", "move", "(", "str", "(", "target_path_tmp", ")", ",", "str", "(", "target_path", ")", ")" ]
Extract everything in site-packages to a specified path. :param ZipFile archive: The zipfile object we are bootstrapping from. :param Path target_path: The path to extract our zip to.
[ "Extract", "everything", "in", "site", "-", "packages", "to", "a", "specified", "path", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/__init__.py#L70-L103
train
linkedin/shiv
src/shiv/bootstrap/__init__.py
bootstrap
def bootstrap(): # pragma: no cover """Actually bootstrap our shiv environment.""" # get a handle of the currently executing zip file archive = current_zipfile() # create an environment object (a combination of env vars and json metadata) env = Environment.from_json(archive.read("environment.json").decode()) # get a site-packages directory (from env var or via build id) site_packages = cache_path(archive, env.root, env.build_id) / "site-packages" # determine if first run or forcing extract if not site_packages.exists() or env.force_extract: extract_site_packages(archive, site_packages.parent, env.compile_pyc, env.compile_workers, env.force_extract) # get sys.path's length length = len(sys.path) # Find the first instance of an existing site-packages on sys.path index = _first_sitedir_index() or length # append site-packages using the stdlib blessed way of extending path # so as to handle .pth files correctly site.addsitedir(site_packages) # add our site-packages to the environment, if requested if env.extend_pythonpath: _extend_python_path(os.environ, sys.path[index:]) # reorder to place our site-packages before any others found sys.path = sys.path[:index] + sys.path[length:] + sys.path[index:length] # first check if we should drop into interactive mode if not env.interpreter: # do entry point import and call if env.entry_point is not None: mod = import_string(env.entry_point) try: sys.exit(mod()) except TypeError: # catch "<module> is not callable", which is thrown when the entry point's # callable shares a name with it's parent module # e.g. "from foo.bar import bar; bar()" sys.exit(getattr(mod, env.entry_point.replace(":", ".").split(".")[1])()) elif env.script is not None: sys.exit(runpy.run_path(site_packages / "bin" / env.script, run_name="__main__")) # all other options exhausted, drop into interactive mode execute_interpreter()
python
def bootstrap(): # pragma: no cover """Actually bootstrap our shiv environment.""" # get a handle of the currently executing zip file archive = current_zipfile() # create an environment object (a combination of env vars and json metadata) env = Environment.from_json(archive.read("environment.json").decode()) # get a site-packages directory (from env var or via build id) site_packages = cache_path(archive, env.root, env.build_id) / "site-packages" # determine if first run or forcing extract if not site_packages.exists() or env.force_extract: extract_site_packages(archive, site_packages.parent, env.compile_pyc, env.compile_workers, env.force_extract) # get sys.path's length length = len(sys.path) # Find the first instance of an existing site-packages on sys.path index = _first_sitedir_index() or length # append site-packages using the stdlib blessed way of extending path # so as to handle .pth files correctly site.addsitedir(site_packages) # add our site-packages to the environment, if requested if env.extend_pythonpath: _extend_python_path(os.environ, sys.path[index:]) # reorder to place our site-packages before any others found sys.path = sys.path[:index] + sys.path[length:] + sys.path[index:length] # first check if we should drop into interactive mode if not env.interpreter: # do entry point import and call if env.entry_point is not None: mod = import_string(env.entry_point) try: sys.exit(mod()) except TypeError: # catch "<module> is not callable", which is thrown when the entry point's # callable shares a name with it's parent module # e.g. "from foo.bar import bar; bar()" sys.exit(getattr(mod, env.entry_point.replace(":", ".").split(".")[1])()) elif env.script is not None: sys.exit(runpy.run_path(site_packages / "bin" / env.script, run_name="__main__")) # all other options exhausted, drop into interactive mode execute_interpreter()
[ "def", "bootstrap", "(", ")", ":", "# pragma: no cover", "# get a handle of the currently executing zip file", "archive", "=", "current_zipfile", "(", ")", "# create an environment object (a combination of env vars and json metadata)", "env", "=", "Environment", ".", "from_json", "(", "archive", ".", "read", "(", "\"environment.json\"", ")", ".", "decode", "(", ")", ")", "# get a site-packages directory (from env var or via build id)", "site_packages", "=", "cache_path", "(", "archive", ",", "env", ".", "root", ",", "env", ".", "build_id", ")", "/", "\"site-packages\"", "# determine if first run or forcing extract", "if", "not", "site_packages", ".", "exists", "(", ")", "or", "env", ".", "force_extract", ":", "extract_site_packages", "(", "archive", ",", "site_packages", ".", "parent", ",", "env", ".", "compile_pyc", ",", "env", ".", "compile_workers", ",", "env", ".", "force_extract", ")", "# get sys.path's length", "length", "=", "len", "(", "sys", ".", "path", ")", "# Find the first instance of an existing site-packages on sys.path", "index", "=", "_first_sitedir_index", "(", ")", "or", "length", "# append site-packages using the stdlib blessed way of extending path", "# so as to handle .pth files correctly", "site", ".", "addsitedir", "(", "site_packages", ")", "# add our site-packages to the environment, if requested", "if", "env", ".", "extend_pythonpath", ":", "_extend_python_path", "(", "os", ".", "environ", ",", "sys", ".", "path", "[", "index", ":", "]", ")", "# reorder to place our site-packages before any others found", "sys", ".", "path", "=", "sys", ".", "path", "[", ":", "index", "]", "+", "sys", ".", "path", "[", "length", ":", "]", "+", "sys", ".", "path", "[", "index", ":", "length", "]", "# first check if we should drop into interactive mode", "if", "not", "env", ".", "interpreter", ":", "# do entry point import and call", "if", "env", ".", "entry_point", "is", "not", "None", ":", "mod", "=", "import_string", "(", "env", ".", "entry_point", ")", "try", ":", "sys", ".", "exit", "(", "mod", "(", ")", ")", "except", "TypeError", ":", "# catch \"<module> is not callable\", which is thrown when the entry point's", "# callable shares a name with it's parent module", "# e.g. \"from foo.bar import bar; bar()\"", "sys", ".", "exit", "(", "getattr", "(", "mod", ",", "env", ".", "entry_point", ".", "replace", "(", "\":\"", ",", "\".\"", ")", ".", "split", "(", "\".\"", ")", "[", "1", "]", ")", "(", ")", ")", "elif", "env", ".", "script", "is", "not", "None", ":", "sys", ".", "exit", "(", "runpy", ".", "run_path", "(", "site_packages", "/", "\"bin\"", "/", "env", ".", "script", ",", "run_name", "=", "\"__main__\"", ")", ")", "# all other options exhausted, drop into interactive mode", "execute_interpreter", "(", ")" ]
Actually bootstrap our shiv environment.
[ "Actually", "bootstrap", "our", "shiv", "environment", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/__init__.py#L118-L169
train
linkedin/shiv
src/shiv/builder.py
write_file_prefix
def write_file_prefix(f: IO[Any], interpreter: str) -> None: """Write a shebang line. :param f: An open file handle. :param interpreter: A path to a python interpreter. """ # if the provided path is too long for a shebang we should error out if len(interpreter) > BINPRM_BUF_SIZE: sys.exit(BINPRM_ERROR) f.write(b"#!" + interpreter.encode(sys.getfilesystemencoding()) + b"\n")
python
def write_file_prefix(f: IO[Any], interpreter: str) -> None: """Write a shebang line. :param f: An open file handle. :param interpreter: A path to a python interpreter. """ # if the provided path is too long for a shebang we should error out if len(interpreter) > BINPRM_BUF_SIZE: sys.exit(BINPRM_ERROR) f.write(b"#!" + interpreter.encode(sys.getfilesystemencoding()) + b"\n")
[ "def", "write_file_prefix", "(", "f", ":", "IO", "[", "Any", "]", ",", "interpreter", ":", "str", ")", "->", "None", ":", "# if the provided path is too long for a shebang we should error out", "if", "len", "(", "interpreter", ")", ">", "BINPRM_BUF_SIZE", ":", "sys", ".", "exit", "(", "BINPRM_ERROR", ")", "f", ".", "write", "(", "b\"#!\"", "+", "interpreter", ".", "encode", "(", "sys", ".", "getfilesystemencoding", "(", ")", ")", "+", "b\"\\n\"", ")" ]
Write a shebang line. :param f: An open file handle. :param interpreter: A path to a python interpreter.
[ "Write", "a", "shebang", "line", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/builder.py#L30-L40
train
linkedin/shiv
src/shiv/builder.py
create_archive
def create_archive( source: Path, target: Path, interpreter: str, main: str, compressed: bool = True ) -> None: """Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_ """ # Check that main has the right format. mod, sep, fn = main.partition(":") mod_ok = all(part.isidentifier() for part in mod.split(".")) fn_ok = all(part.isidentifier() for part in fn.split(".")) if not (sep == ":" and mod_ok and fn_ok): raise zipapp.ZipAppError("Invalid entry point: " + main) main_py = MAIN_TEMPLATE.format(module=mod, fn=fn) with maybe_open(target, "wb") as fd: # write shebang write_file_prefix(fd, interpreter) # determine compression compression = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED # create zipapp with zipfile.ZipFile(fd, "w", compression=compression) as z: for child in source.rglob("*"): # skip compiled files if child.suffix == '.pyc': continue arcname = child.relative_to(source) z.write(str(child), str(arcname)) # write main z.writestr("__main__.py", main_py.encode("utf-8")) # make executable # NOTE on windows this is no-op target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
python
def create_archive( source: Path, target: Path, interpreter: str, main: str, compressed: bool = True ) -> None: """Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_ """ # Check that main has the right format. mod, sep, fn = main.partition(":") mod_ok = all(part.isidentifier() for part in mod.split(".")) fn_ok = all(part.isidentifier() for part in fn.split(".")) if not (sep == ":" and mod_ok and fn_ok): raise zipapp.ZipAppError("Invalid entry point: " + main) main_py = MAIN_TEMPLATE.format(module=mod, fn=fn) with maybe_open(target, "wb") as fd: # write shebang write_file_prefix(fd, interpreter) # determine compression compression = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED # create zipapp with zipfile.ZipFile(fd, "w", compression=compression) as z: for child in source.rglob("*"): # skip compiled files if child.suffix == '.pyc': continue arcname = child.relative_to(source) z.write(str(child), str(arcname)) # write main z.writestr("__main__.py", main_py.encode("utf-8")) # make executable # NOTE on windows this is no-op target.chmod(target.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
[ "def", "create_archive", "(", "source", ":", "Path", ",", "target", ":", "Path", ",", "interpreter", ":", "str", ",", "main", ":", "str", ",", "compressed", ":", "bool", "=", "True", ")", "->", "None", ":", "# Check that main has the right format.", "mod", ",", "sep", ",", "fn", "=", "main", ".", "partition", "(", "\":\"", ")", "mod_ok", "=", "all", "(", "part", ".", "isidentifier", "(", ")", "for", "part", "in", "mod", ".", "split", "(", "\".\"", ")", ")", "fn_ok", "=", "all", "(", "part", ".", "isidentifier", "(", ")", "for", "part", "in", "fn", ".", "split", "(", "\".\"", ")", ")", "if", "not", "(", "sep", "==", "\":\"", "and", "mod_ok", "and", "fn_ok", ")", ":", "raise", "zipapp", ".", "ZipAppError", "(", "\"Invalid entry point: \"", "+", "main", ")", "main_py", "=", "MAIN_TEMPLATE", ".", "format", "(", "module", "=", "mod", ",", "fn", "=", "fn", ")", "with", "maybe_open", "(", "target", ",", "\"wb\"", ")", "as", "fd", ":", "# write shebang", "write_file_prefix", "(", "fd", ",", "interpreter", ")", "# determine compression", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", "if", "compressed", "else", "zipfile", ".", "ZIP_STORED", "# create zipapp", "with", "zipfile", ".", "ZipFile", "(", "fd", ",", "\"w\"", ",", "compression", "=", "compression", ")", "as", "z", ":", "for", "child", "in", "source", ".", "rglob", "(", "\"*\"", ")", ":", "# skip compiled files", "if", "child", ".", "suffix", "==", "'.pyc'", ":", "continue", "arcname", "=", "child", ".", "relative_to", "(", "source", ")", "z", ".", "write", "(", "str", "(", "child", ")", ",", "str", "(", "arcname", ")", ")", "# write main", "z", ".", "writestr", "(", "\"__main__.py\"", ",", "main_py", ".", "encode", "(", "\"utf-8\"", ")", ")", "# make executable", "# NOTE on windows this is no-op", "target", ".", "chmod", "(", "target", ".", "stat", "(", ")", ".", "st_mode", "|", "stat", ".", "S_IXUSR", "|", "stat", ".", "S_IXGRP", "|", "stat", ".", "S_IXOTH", ")" ]
Create an application archive from SOURCE. A slightly modified version of stdlib's `zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_
[ "Create", "an", "application", "archive", "from", "SOURCE", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/builder.py#L53-L98
train
linkedin/shiv
src/shiv/bootstrap/filelock.py
acquire_win
def acquire_win(lock_file): # pragma: no cover """Acquire a lock file on windows.""" try: fd = os.open(lock_file, OPEN_MODE) except OSError: pass else: try: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) except (IOError, OSError): os.close(fd) else: return fd
python
def acquire_win(lock_file): # pragma: no cover """Acquire a lock file on windows.""" try: fd = os.open(lock_file, OPEN_MODE) except OSError: pass else: try: msvcrt.locking(fd, msvcrt.LK_NBLCK, 1) except (IOError, OSError): os.close(fd) else: return fd
[ "def", "acquire_win", "(", "lock_file", ")", ":", "# pragma: no cover", "try", ":", "fd", "=", "os", ".", "open", "(", "lock_file", ",", "OPEN_MODE", ")", "except", "OSError", ":", "pass", "else", ":", "try", ":", "msvcrt", ".", "locking", "(", "fd", ",", "msvcrt", ".", "LK_NBLCK", ",", "1", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "os", ".", "close", "(", "fd", ")", "else", ":", "return", "fd" ]
Acquire a lock file on windows.
[ "Acquire", "a", "lock", "file", "on", "windows", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/filelock.py#L22-L34
train
linkedin/shiv
src/shiv/bootstrap/filelock.py
acquire_nix
def acquire_nix(lock_file): # pragma: no cover """Acquire a lock file on linux or osx.""" fd = os.open(lock_file, OPEN_MODE) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (IOError, OSError): os.close(fd) else: return fd
python
def acquire_nix(lock_file): # pragma: no cover """Acquire a lock file on linux or osx.""" fd = os.open(lock_file, OPEN_MODE) try: fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) except (IOError, OSError): os.close(fd) else: return fd
[ "def", "acquire_nix", "(", "lock_file", ")", ":", "# pragma: no cover", "fd", "=", "os", ".", "open", "(", "lock_file", ",", "OPEN_MODE", ")", "try", ":", "fcntl", ".", "flock", "(", "fd", ",", "fcntl", ".", "LOCK_EX", "|", "fcntl", ".", "LOCK_NB", ")", "except", "(", "IOError", ",", "OSError", ")", ":", "os", ".", "close", "(", "fd", ")", "else", ":", "return", "fd" ]
Acquire a lock file on linux or osx.
[ "Acquire", "a", "lock", "file", "on", "linux", "or", "osx", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/bootstrap/filelock.py#L37-L46
train
linkedin/shiv
src/shiv/cli.py
find_entry_point
def find_entry_point(site_packages: Path, console_script: str) -> str: """Find a console_script in a site-packages directory. Console script metadata is stored in entry_points.txt per setuptools convention. This function searches all entry_points.txt files and returns the import string for a given console_script argument. :param site_packages: A path to a site-packages directory on disk. :param console_script: A console_script string. """ config_parser = ConfigParser() config_parser.read(site_packages.rglob("entry_points.txt")) return config_parser["console_scripts"][console_script]
python
def find_entry_point(site_packages: Path, console_script: str) -> str: """Find a console_script in a site-packages directory. Console script metadata is stored in entry_points.txt per setuptools convention. This function searches all entry_points.txt files and returns the import string for a given console_script argument. :param site_packages: A path to a site-packages directory on disk. :param console_script: A console_script string. """ config_parser = ConfigParser() config_parser.read(site_packages.rglob("entry_points.txt")) return config_parser["console_scripts"][console_script]
[ "def", "find_entry_point", "(", "site_packages", ":", "Path", ",", "console_script", ":", "str", ")", "->", "str", ":", "config_parser", "=", "ConfigParser", "(", ")", "config_parser", ".", "read", "(", "site_packages", ".", "rglob", "(", "\"entry_points.txt\"", ")", ")", "return", "config_parser", "[", "\"console_scripts\"", "]", "[", "console_script", "]" ]
Find a console_script in a site-packages directory. Console script metadata is stored in entry_points.txt per setuptools convention. This function searches all entry_points.txt files and returns the import string for a given console_script argument. :param site_packages: A path to a site-packages directory on disk. :param console_script: A console_script string.
[ "Find", "a", "console_script", "in", "a", "site", "-", "packages", "directory", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L32-L45
train
linkedin/shiv
src/shiv/cli.py
copy_bootstrap
def copy_bootstrap(bootstrap_target: Path) -> None: """Copy bootstrap code from shiv into the pyz. This function is excluded from type checking due to the conditional import. :param bootstrap_target: The temporary directory where we are staging pyz contents. """ for bootstrap_file in importlib_resources.contents(bootstrap): if importlib_resources.is_resource(bootstrap, bootstrap_file): with importlib_resources.path(bootstrap, bootstrap_file) as f: shutil.copyfile(f.absolute(), bootstrap_target / f.name)
python
def copy_bootstrap(bootstrap_target: Path) -> None: """Copy bootstrap code from shiv into the pyz. This function is excluded from type checking due to the conditional import. :param bootstrap_target: The temporary directory where we are staging pyz contents. """ for bootstrap_file in importlib_resources.contents(bootstrap): if importlib_resources.is_resource(bootstrap, bootstrap_file): with importlib_resources.path(bootstrap, bootstrap_file) as f: shutil.copyfile(f.absolute(), bootstrap_target / f.name)
[ "def", "copy_bootstrap", "(", "bootstrap_target", ":", "Path", ")", "->", "None", ":", "for", "bootstrap_file", "in", "importlib_resources", ".", "contents", "(", "bootstrap", ")", ":", "if", "importlib_resources", ".", "is_resource", "(", "bootstrap", ",", "bootstrap_file", ")", ":", "with", "importlib_resources", ".", "path", "(", "bootstrap", ",", "bootstrap_file", ")", "as", "f", ":", "shutil", ".", "copyfile", "(", "f", ".", "absolute", "(", ")", ",", "bootstrap_target", "/", "f", ".", "name", ")" ]
Copy bootstrap code from shiv into the pyz. This function is excluded from type checking due to the conditional import. :param bootstrap_target: The temporary directory where we are staging pyz contents.
[ "Copy", "bootstrap", "code", "from", "shiv", "into", "the", "pyz", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L49-L60
train
linkedin/shiv
src/shiv/cli.py
_interpreter_path
def _interpreter_path(append_version: bool = False) -> str: """A function to return the path to the current Python interpreter. Even when inside a venv, this will return the interpreter the venv was created with. """ base_dir = Path(getattr(sys, "real_prefix", sys.base_prefix)).resolve() sys_exec = Path(sys.executable) name = sys_exec.stem suffix = sys_exec.suffix if append_version: name += str(sys.version_info.major) name += suffix try: return str(next(iter(base_dir.rglob(name)))) except StopIteration: if not append_version: # If we couldn't find an interpreter, it's likely that we looked for # "python" when we should've been looking for "python3" # so we try again with append_version=True return _interpreter_path(append_version=True) # If we were still unable to find a real interpreter for some reason # we fallback to the current runtime's interpreter return sys.executable
python
def _interpreter_path(append_version: bool = False) -> str: """A function to return the path to the current Python interpreter. Even when inside a venv, this will return the interpreter the venv was created with. """ base_dir = Path(getattr(sys, "real_prefix", sys.base_prefix)).resolve() sys_exec = Path(sys.executable) name = sys_exec.stem suffix = sys_exec.suffix if append_version: name += str(sys.version_info.major) name += suffix try: return str(next(iter(base_dir.rglob(name)))) except StopIteration: if not append_version: # If we couldn't find an interpreter, it's likely that we looked for # "python" when we should've been looking for "python3" # so we try again with append_version=True return _interpreter_path(append_version=True) # If we were still unable to find a real interpreter for some reason # we fallback to the current runtime's interpreter return sys.executable
[ "def", "_interpreter_path", "(", "append_version", ":", "bool", "=", "False", ")", "->", "str", ":", "base_dir", "=", "Path", "(", "getattr", "(", "sys", ",", "\"real_prefix\"", ",", "sys", ".", "base_prefix", ")", ")", ".", "resolve", "(", ")", "sys_exec", "=", "Path", "(", "sys", ".", "executable", ")", "name", "=", "sys_exec", ".", "stem", "suffix", "=", "sys_exec", ".", "suffix", "if", "append_version", ":", "name", "+=", "str", "(", "sys", ".", "version_info", ".", "major", ")", "name", "+=", "suffix", "try", ":", "return", "str", "(", "next", "(", "iter", "(", "base_dir", ".", "rglob", "(", "name", ")", ")", ")", ")", "except", "StopIteration", ":", "if", "not", "append_version", ":", "# If we couldn't find an interpreter, it's likely that we looked for", "# \"python\" when we should've been looking for \"python3\"", "# so we try again with append_version=True", "return", "_interpreter_path", "(", "append_version", "=", "True", ")", "# If we were still unable to find a real interpreter for some reason", "# we fallback to the current runtime's interpreter", "return", "sys", ".", "executable" ]
A function to return the path to the current Python interpreter. Even when inside a venv, this will return the interpreter the venv was created with.
[ "A", "function", "to", "return", "the", "path", "to", "the", "current", "Python", "interpreter", "." ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L63-L93
train
linkedin/shiv
src/shiv/cli.py
main
def main( output_file: str, entry_point: Optional[str], console_script: Optional[str], python: Optional[str], site_packages: Optional[str], compressed: bool, compile_pyc: bool, extend_pythonpath: bool, pip_args: List[str], ) -> None: """ Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included! """ if not pip_args and not site_packages: sys.exit(NO_PIP_ARGS_OR_SITE_PACKAGES) if output_file is None: sys.exit(NO_OUTFILE) # check for disallowed pip arguments for disallowed in DISALLOWED_ARGS: for supplied_arg in pip_args: if supplied_arg in disallowed: sys.exit( DISALLOWED_PIP_ARGS.format( arg=supplied_arg, reason=DISALLOWED_ARGS[disallowed] ) ) with TemporaryDirectory() as working_path: tmp_site_packages = Path(working_path, "site-packages") if site_packages: shutil.copytree(site_packages, tmp_site_packages) if pip_args: # install deps into staged site-packages pip.install(["--target", str(tmp_site_packages)] + list(pip_args)) # if entry_point is a console script, get the callable if entry_point is None and console_script is not None: try: entry_point = find_entry_point(tmp_site_packages, console_script) except KeyError: if not Path(tmp_site_packages, "bin", console_script).exists(): sys.exit(NO_ENTRY_POINT.format(entry_point=console_script)) # create runtime environment metadata env = Environment( build_id=str(uuid.uuid4()), entry_point=entry_point, script=console_script, compile_pyc=compile_pyc, extend_pythonpath=extend_pythonpath, ) Path(working_path, "environment.json").write_text(env.to_json()) # create bootstrapping directory in working path bootstrap_target = Path(working_path, "_bootstrap") bootstrap_target.mkdir(parents=True, exist_ok=True) # copy bootstrap code copy_bootstrap(bootstrap_target) # create the zip builder.create_archive( Path(working_path), target=Path(output_file).expanduser(), interpreter=python or _interpreter_path(), main="_bootstrap:bootstrap", compressed=compressed, )
python
def main( output_file: str, entry_point: Optional[str], console_script: Optional[str], python: Optional[str], site_packages: Optional[str], compressed: bool, compile_pyc: bool, extend_pythonpath: bool, pip_args: List[str], ) -> None: """ Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included! """ if not pip_args and not site_packages: sys.exit(NO_PIP_ARGS_OR_SITE_PACKAGES) if output_file is None: sys.exit(NO_OUTFILE) # check for disallowed pip arguments for disallowed in DISALLOWED_ARGS: for supplied_arg in pip_args: if supplied_arg in disallowed: sys.exit( DISALLOWED_PIP_ARGS.format( arg=supplied_arg, reason=DISALLOWED_ARGS[disallowed] ) ) with TemporaryDirectory() as working_path: tmp_site_packages = Path(working_path, "site-packages") if site_packages: shutil.copytree(site_packages, tmp_site_packages) if pip_args: # install deps into staged site-packages pip.install(["--target", str(tmp_site_packages)] + list(pip_args)) # if entry_point is a console script, get the callable if entry_point is None and console_script is not None: try: entry_point = find_entry_point(tmp_site_packages, console_script) except KeyError: if not Path(tmp_site_packages, "bin", console_script).exists(): sys.exit(NO_ENTRY_POINT.format(entry_point=console_script)) # create runtime environment metadata env = Environment( build_id=str(uuid.uuid4()), entry_point=entry_point, script=console_script, compile_pyc=compile_pyc, extend_pythonpath=extend_pythonpath, ) Path(working_path, "environment.json").write_text(env.to_json()) # create bootstrapping directory in working path bootstrap_target = Path(working_path, "_bootstrap") bootstrap_target.mkdir(parents=True, exist_ok=True) # copy bootstrap code copy_bootstrap(bootstrap_target) # create the zip builder.create_archive( Path(working_path), target=Path(output_file).expanduser(), interpreter=python or _interpreter_path(), main="_bootstrap:bootstrap", compressed=compressed, )
[ "def", "main", "(", "output_file", ":", "str", ",", "entry_point", ":", "Optional", "[", "str", "]", ",", "console_script", ":", "Optional", "[", "str", "]", ",", "python", ":", "Optional", "[", "str", "]", ",", "site_packages", ":", "Optional", "[", "str", "]", ",", "compressed", ":", "bool", ",", "compile_pyc", ":", "bool", ",", "extend_pythonpath", ":", "bool", ",", "pip_args", ":", "List", "[", "str", "]", ",", ")", "->", "None", ":", "if", "not", "pip_args", "and", "not", "site_packages", ":", "sys", ".", "exit", "(", "NO_PIP_ARGS_OR_SITE_PACKAGES", ")", "if", "output_file", "is", "None", ":", "sys", ".", "exit", "(", "NO_OUTFILE", ")", "# check for disallowed pip arguments", "for", "disallowed", "in", "DISALLOWED_ARGS", ":", "for", "supplied_arg", "in", "pip_args", ":", "if", "supplied_arg", "in", "disallowed", ":", "sys", ".", "exit", "(", "DISALLOWED_PIP_ARGS", ".", "format", "(", "arg", "=", "supplied_arg", ",", "reason", "=", "DISALLOWED_ARGS", "[", "disallowed", "]", ")", ")", "with", "TemporaryDirectory", "(", ")", "as", "working_path", ":", "tmp_site_packages", "=", "Path", "(", "working_path", ",", "\"site-packages\"", ")", "if", "site_packages", ":", "shutil", ".", "copytree", "(", "site_packages", ",", "tmp_site_packages", ")", "if", "pip_args", ":", "# install deps into staged site-packages", "pip", ".", "install", "(", "[", "\"--target\"", ",", "str", "(", "tmp_site_packages", ")", "]", "+", "list", "(", "pip_args", ")", ")", "# if entry_point is a console script, get the callable", "if", "entry_point", "is", "None", "and", "console_script", "is", "not", "None", ":", "try", ":", "entry_point", "=", "find_entry_point", "(", "tmp_site_packages", ",", "console_script", ")", "except", "KeyError", ":", "if", "not", "Path", "(", "tmp_site_packages", ",", "\"bin\"", ",", "console_script", ")", ".", "exists", "(", ")", ":", "sys", ".", "exit", "(", "NO_ENTRY_POINT", ".", "format", "(", "entry_point", "=", "console_script", ")", ")", "# create runtime environment metadata", "env", "=", "Environment", "(", "build_id", "=", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", "entry_point", "=", "entry_point", ",", "script", "=", "console_script", ",", "compile_pyc", "=", "compile_pyc", ",", "extend_pythonpath", "=", "extend_pythonpath", ",", ")", "Path", "(", "working_path", ",", "\"environment.json\"", ")", ".", "write_text", "(", "env", ".", "to_json", "(", ")", ")", "# create bootstrapping directory in working path", "bootstrap_target", "=", "Path", "(", "working_path", ",", "\"_bootstrap\"", ")", "bootstrap_target", ".", "mkdir", "(", "parents", "=", "True", ",", "exist_ok", "=", "True", ")", "# copy bootstrap code", "copy_bootstrap", "(", "bootstrap_target", ")", "# create the zip", "builder", ".", "create_archive", "(", "Path", "(", "working_path", ")", ",", "target", "=", "Path", "(", "output_file", ")", ".", "expanduser", "(", ")", ",", "interpreter", "=", "python", "or", "_interpreter_path", "(", ")", ",", "main", "=", "\"_bootstrap:bootstrap\"", ",", "compressed", "=", "compressed", ",", ")" ]
Shiv is a command line utility for building fully self-contained Python zipapps as outlined in PEP 441, but with all their dependencies included!
[ "Shiv", "is", "a", "command", "line", "utility", "for", "building", "fully", "self", "-", "contained", "Python", "zipapps", "as", "outlined", "in", "PEP", "441", "but", "with", "all", "their", "dependencies", "included!" ]
6bda78676170b35d0877f67b71095c39ce41a74a
https://github.com/linkedin/shiv/blob/6bda78676170b35d0877f67b71095c39ce41a74a/src/shiv/cli.py#L128-L204
train
aio-libs/aiobotocore
aiobotocore/session.py
get_session
def get_session(*, env_vars=None, loop=None): """ Return a new session object. """ loop = loop or asyncio.get_event_loop() return AioSession(session_vars=env_vars, loop=loop)
python
def get_session(*, env_vars=None, loop=None): """ Return a new session object. """ loop = loop or asyncio.get_event_loop() return AioSession(session_vars=env_vars, loop=loop)
[ "def", "get_session", "(", "*", ",", "env_vars", "=", "None", ",", "loop", "=", "None", ")", ":", "loop", "=", "loop", "or", "asyncio", ".", "get_event_loop", "(", ")", "return", "AioSession", "(", "session_vars", "=", "env_vars", ",", "loop", "=", "loop", ")" ]
Return a new session object.
[ "Return", "a", "new", "session", "object", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/session.py#L88-L93
train
aio-libs/aiobotocore
aiobotocore/response.py
StreamingBody.read
async def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ # botocore to aiohttp mapping chunk = await self.__wrapped__.read(amt if amt is not None else -1) self._self_amount_read += len(chunk) if amt is None or (not chunk and amt > 0): # If the server sends empty contents or # we ask to read all of the contents, then we know # we need to verify the content length. self._verify_content_length() return chunk
python
async def read(self, amt=None): """Read at most amt bytes from the stream. If the amt argument is omitted, read all data. """ # botocore to aiohttp mapping chunk = await self.__wrapped__.read(amt if amt is not None else -1) self._self_amount_read += len(chunk) if amt is None or (not chunk and amt > 0): # If the server sends empty contents or # we ask to read all of the contents, then we know # we need to verify the content length. self._verify_content_length() return chunk
[ "async", "def", "read", "(", "self", ",", "amt", "=", "None", ")", ":", "# botocore to aiohttp mapping", "chunk", "=", "await", "self", ".", "__wrapped__", ".", "read", "(", "amt", "if", "amt", "is", "not", "None", "else", "-", "1", ")", "self", ".", "_self_amount_read", "+=", "len", "(", "chunk", ")", "if", "amt", "is", "None", "or", "(", "not", "chunk", "and", "amt", ">", "0", ")", ":", "# If the server sends empty contents or", "# we ask to read all of the contents, then we know", "# we need to verify the content length.", "self", ".", "_verify_content_length", "(", ")", "return", "chunk" ]
Read at most amt bytes from the stream. If the amt argument is omitted, read all data.
[ "Read", "at", "most", "amt", "bytes", "from", "the", "stream", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/response.py#L37-L50
train
aio-libs/aiobotocore
aiobotocore/response.py
StreamingBody.iter_lines
async def iter_lines(self, chunk_size=1024): """Return an iterator to yield lines from the raw stream. This is achieved by reading chunk of bytes (of size chunk_size) at a time from the raw stream, and then yielding lines from there. """ pending = b'' async for chunk in self.iter_chunks(chunk_size): lines = (pending + chunk).splitlines(True) for line in lines[:-1]: await yield_(line.splitlines()[0]) pending = lines[-1] if pending: await yield_(pending.splitlines()[0])
python
async def iter_lines(self, chunk_size=1024): """Return an iterator to yield lines from the raw stream. This is achieved by reading chunk of bytes (of size chunk_size) at a time from the raw stream, and then yielding lines from there. """ pending = b'' async for chunk in self.iter_chunks(chunk_size): lines = (pending + chunk).splitlines(True) for line in lines[:-1]: await yield_(line.splitlines()[0]) pending = lines[-1] if pending: await yield_(pending.splitlines()[0])
[ "async", "def", "iter_lines", "(", "self", ",", "chunk_size", "=", "1024", ")", ":", "pending", "=", "b''", "async", "for", "chunk", "in", "self", ".", "iter_chunks", "(", "chunk_size", ")", ":", "lines", "=", "(", "pending", "+", "chunk", ")", ".", "splitlines", "(", "True", ")", "for", "line", "in", "lines", "[", ":", "-", "1", "]", ":", "await", "yield_", "(", "line", ".", "splitlines", "(", ")", "[", "0", "]", ")", "pending", "=", "lines", "[", "-", "1", "]", "if", "pending", ":", "await", "yield_", "(", "pending", ".", "splitlines", "(", ")", "[", "0", "]", ")" ]
Return an iterator to yield lines from the raw stream. This is achieved by reading chunk of bytes (of size chunk_size) at a time from the raw stream, and then yielding lines from there.
[ "Return", "an", "iterator", "to", "yield", "lines", "from", "the", "raw", "stream", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/response.py#L68-L81
train
aio-libs/aiobotocore
aiobotocore/response.py
StreamingBody.iter_chunks
async def iter_chunks(self, chunk_size=_DEFAULT_CHUNK_SIZE): """Return an iterator to yield chunks of chunk_size bytes from the raw stream. """ while True: current_chunk = await self.read(chunk_size) if current_chunk == b"": break await yield_(current_chunk)
python
async def iter_chunks(self, chunk_size=_DEFAULT_CHUNK_SIZE): """Return an iterator to yield chunks of chunk_size bytes from the raw stream. """ while True: current_chunk = await self.read(chunk_size) if current_chunk == b"": break await yield_(current_chunk)
[ "async", "def", "iter_chunks", "(", "self", ",", "chunk_size", "=", "_DEFAULT_CHUNK_SIZE", ")", ":", "while", "True", ":", "current_chunk", "=", "await", "self", ".", "read", "(", "chunk_size", ")", "if", "current_chunk", "==", "b\"\"", ":", "break", "await", "yield_", "(", "current_chunk", ")" ]
Return an iterator to yield chunks of chunk_size bytes from the raw stream.
[ "Return", "an", "iterator", "to", "yield", "chunks", "of", "chunk_size", "bytes", "from", "the", "raw", "stream", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/response.py#L84-L92
train
aio-libs/aiobotocore
examples/dynamodb_batch_write.py
get_items
def get_items(start_num, num_items): """ Generate a sequence of dynamo items :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: List of dictionaries :rtype: list of dict """ result = [] for i in range(start_num, start_num+num_items): result.append({'pk': {'S': 'item{0}'.format(i)}}) return result
python
def get_items(start_num, num_items): """ Generate a sequence of dynamo items :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: List of dictionaries :rtype: list of dict """ result = [] for i in range(start_num, start_num+num_items): result.append({'pk': {'S': 'item{0}'.format(i)}}) return result
[ "def", "get_items", "(", "start_num", ",", "num_items", ")", ":", "result", "=", "[", "]", "for", "i", "in", "range", "(", "start_num", ",", "start_num", "+", "num_items", ")", ":", "result", ".", "append", "(", "{", "'pk'", ":", "{", "'S'", ":", "'item{0}'", ".", "format", "(", "i", ")", "}", "}", ")", "return", "result" ]
Generate a sequence of dynamo items :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: List of dictionaries :rtype: list of dict
[ "Generate", "a", "sequence", "of", "dynamo", "items" ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/examples/dynamodb_batch_write.py#L7-L21
train
aio-libs/aiobotocore
examples/dynamodb_batch_write.py
create_batch_write_structure
def create_batch_write_structure(table_name, start_num, num_items): """ Create item structure for passing to batch_write_item :param table_name: DynamoDB table name :type table_name: str :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: dictionary of tables to write to :rtype: dict """ return { table_name: [ {'PutRequest': {'Item': item}} for item in get_items(start_num, num_items) ] }
python
def create_batch_write_structure(table_name, start_num, num_items): """ Create item structure for passing to batch_write_item :param table_name: DynamoDB table name :type table_name: str :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: dictionary of tables to write to :rtype: dict """ return { table_name: [ {'PutRequest': {'Item': item}} for item in get_items(start_num, num_items) ] }
[ "def", "create_batch_write_structure", "(", "table_name", ",", "start_num", ",", "num_items", ")", ":", "return", "{", "table_name", ":", "[", "{", "'PutRequest'", ":", "{", "'Item'", ":", "item", "}", "}", "for", "item", "in", "get_items", "(", "start_num", ",", "num_items", ")", "]", "}" ]
Create item structure for passing to batch_write_item :param table_name: DynamoDB table name :type table_name: str :param start_num: Start index :type start_num: int :param num_items: Number of items :type num_items: int :return: dictionary of tables to write to :rtype: dict
[ "Create", "item", "structure", "for", "passing", "to", "batch_write_item" ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/examples/dynamodb_batch_write.py#L24-L42
train
aio-libs/aiobotocore
aiobotocore/client.py
AioBaseClient.get_paginator
def get_paginator(self, operation_name): """Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd normally invoke the operation as ``client.create_foo(**kwargs)``, if the ``create_foo`` operation can be paginated, you can use the call ``client.get_paginator("create_foo")``. :raise OperationNotPageableError: Raised if the operation is not pageable. You can use the ``client.can_paginate`` method to check if an operation is pageable. :rtype: L{botocore.paginate.Paginator} :return: A paginator object. """ if not self.can_paginate(operation_name): raise OperationNotPageableError(operation_name=operation_name) else: # substitute iterator with async one Paginator.PAGE_ITERATOR_CLS = AioPageIterator actual_operation_name = self._PY_TO_OP_NAME[operation_name] # Create a new paginate method that will serve as a proxy to # the underlying Paginator.paginate method. This is needed to # attach a docstring to the method. def paginate(self, **kwargs): return Paginator.paginate(self, **kwargs) paginator_config = self._cache['page_config'][ actual_operation_name] # Rename the paginator class based on the type of paginator. paginator_class_name = str('%s.Paginator.%s' % ( get_service_module_name(self.meta.service_model), actual_operation_name)) # Create the new paginator class documented_paginator_cls = type( paginator_class_name, (Paginator,), {'paginate': paginate}) operation_model = self._service_model.\ operation_model(actual_operation_name) paginator = documented_paginator_cls( getattr(self, operation_name), paginator_config, operation_model) return paginator
python
def get_paginator(self, operation_name): """Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd normally invoke the operation as ``client.create_foo(**kwargs)``, if the ``create_foo`` operation can be paginated, you can use the call ``client.get_paginator("create_foo")``. :raise OperationNotPageableError: Raised if the operation is not pageable. You can use the ``client.can_paginate`` method to check if an operation is pageable. :rtype: L{botocore.paginate.Paginator} :return: A paginator object. """ if not self.can_paginate(operation_name): raise OperationNotPageableError(operation_name=operation_name) else: # substitute iterator with async one Paginator.PAGE_ITERATOR_CLS = AioPageIterator actual_operation_name = self._PY_TO_OP_NAME[operation_name] # Create a new paginate method that will serve as a proxy to # the underlying Paginator.paginate method. This is needed to # attach a docstring to the method. def paginate(self, **kwargs): return Paginator.paginate(self, **kwargs) paginator_config = self._cache['page_config'][ actual_operation_name] # Rename the paginator class based on the type of paginator. paginator_class_name = str('%s.Paginator.%s' % ( get_service_module_name(self.meta.service_model), actual_operation_name)) # Create the new paginator class documented_paginator_cls = type( paginator_class_name, (Paginator,), {'paginate': paginate}) operation_model = self._service_model.\ operation_model(actual_operation_name) paginator = documented_paginator_cls( getattr(self, operation_name), paginator_config, operation_model) return paginator
[ "def", "get_paginator", "(", "self", ",", "operation_name", ")", ":", "if", "not", "self", ".", "can_paginate", "(", "operation_name", ")", ":", "raise", "OperationNotPageableError", "(", "operation_name", "=", "operation_name", ")", "else", ":", "# substitute iterator with async one", "Paginator", ".", "PAGE_ITERATOR_CLS", "=", "AioPageIterator", "actual_operation_name", "=", "self", ".", "_PY_TO_OP_NAME", "[", "operation_name", "]", "# Create a new paginate method that will serve as a proxy to", "# the underlying Paginator.paginate method. This is needed to", "# attach a docstring to the method.", "def", "paginate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "Paginator", ".", "paginate", "(", "self", ",", "*", "*", "kwargs", ")", "paginator_config", "=", "self", ".", "_cache", "[", "'page_config'", "]", "[", "actual_operation_name", "]", "# Rename the paginator class based on the type of paginator.", "paginator_class_name", "=", "str", "(", "'%s.Paginator.%s'", "%", "(", "get_service_module_name", "(", "self", ".", "meta", ".", "service_model", ")", ",", "actual_operation_name", ")", ")", "# Create the new paginator class", "documented_paginator_cls", "=", "type", "(", "paginator_class_name", ",", "(", "Paginator", ",", ")", ",", "{", "'paginate'", ":", "paginate", "}", ")", "operation_model", "=", "self", ".", "_service_model", ".", "operation_model", "(", "actual_operation_name", ")", "paginator", "=", "documented_paginator_cls", "(", "getattr", "(", "self", ",", "operation_name", ")", ",", "paginator_config", ",", "operation_model", ")", "return", "paginator" ]
Create a paginator for an operation. :type operation_name: string :param operation_name: The operation name. This is the same name as the method name on the client. For example, if the method name is ``create_foo``, and you'd normally invoke the operation as ``client.create_foo(**kwargs)``, if the ``create_foo`` operation can be paginated, you can use the call ``client.get_paginator("create_foo")``. :raise OperationNotPageableError: Raised if the operation is not pageable. You can use the ``client.can_paginate`` method to check if an operation is pageable. :rtype: L{botocore.paginate.Paginator} :return: A paginator object.
[ "Create", "a", "paginator", "for", "an", "operation", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/client.py#L124-L176
train
aio-libs/aiobotocore
aiobotocore/client.py
AioBaseClient.get_waiter
def get_waiter(self, waiter_name): """Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. :returns: The specified waiter object. :rtype: botocore.waiter.Waiter """ config = self._get_waiter_config() if not config: raise ValueError("Waiter does not exist: %s" % waiter_name) model = waiter.WaiterModel(config) mapping = {} for name in model.waiter_names: mapping[xform_name(name)] = name if waiter_name not in mapping: raise ValueError("Waiter does not exist: %s" % waiter_name) return waiter.create_waiter_with_client( mapping[waiter_name], model, self, loop=self._loop)
python
def get_waiter(self, waiter_name): """Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. :returns: The specified waiter object. :rtype: botocore.waiter.Waiter """ config = self._get_waiter_config() if not config: raise ValueError("Waiter does not exist: %s" % waiter_name) model = waiter.WaiterModel(config) mapping = {} for name in model.waiter_names: mapping[xform_name(name)] = name if waiter_name not in mapping: raise ValueError("Waiter does not exist: %s" % waiter_name) return waiter.create_waiter_with_client( mapping[waiter_name], model, self, loop=self._loop)
[ "def", "get_waiter", "(", "self", ",", "waiter_name", ")", ":", "config", "=", "self", ".", "_get_waiter_config", "(", ")", "if", "not", "config", ":", "raise", "ValueError", "(", "\"Waiter does not exist: %s\"", "%", "waiter_name", ")", "model", "=", "waiter", ".", "WaiterModel", "(", "config", ")", "mapping", "=", "{", "}", "for", "name", "in", "model", ".", "waiter_names", ":", "mapping", "[", "xform_name", "(", "name", ")", "]", "=", "name", "if", "waiter_name", "not", "in", "mapping", ":", "raise", "ValueError", "(", "\"Waiter does not exist: %s\"", "%", "waiter_name", ")", "return", "waiter", ".", "create_waiter_with_client", "(", "mapping", "[", "waiter_name", "]", ",", "model", ",", "self", ",", "loop", "=", "self", ".", "_loop", ")" ]
Returns an object that can wait for some condition. :type waiter_name: str :param waiter_name: The name of the waiter to get. See the waiters section of the service docs for a list of available waiters. :returns: The specified waiter object. :rtype: botocore.waiter.Waiter
[ "Returns", "an", "object", "that", "can", "wait", "for", "some", "condition", "." ]
d0c0a8651a3738b6260efe962218a5738694dd2a
https://github.com/aio-libs/aiobotocore/blob/d0c0a8651a3738b6260efe962218a5738694dd2a/aiobotocore/client.py#L178-L199
train
gabrielfalcao/HTTPretty
httpretty/core.py
url_fix
def url_fix(s, charset=None): """escapes special characters """ if charset: warnings.warn("{}.url_fix() charset argument is deprecated".format(__name__), DeprecationWarning) scheme, netloc, path, querystring, fragment = urlsplit(s) path = quote(path, b'/%') querystring = quote_plus(querystring, b':&=') return urlunsplit((scheme, netloc, path, querystring, fragment))
python
def url_fix(s, charset=None): """escapes special characters """ if charset: warnings.warn("{}.url_fix() charset argument is deprecated".format(__name__), DeprecationWarning) scheme, netloc, path, querystring, fragment = urlsplit(s) path = quote(path, b'/%') querystring = quote_plus(querystring, b':&=') return urlunsplit((scheme, netloc, path, querystring, fragment))
[ "def", "url_fix", "(", "s", ",", "charset", "=", "None", ")", ":", "if", "charset", ":", "warnings", ".", "warn", "(", "\"{}.url_fix() charset argument is deprecated\"", ".", "format", "(", "__name__", ")", ",", "DeprecationWarning", ")", "scheme", ",", "netloc", ",", "path", ",", "querystring", ",", "fragment", "=", "urlsplit", "(", "s", ")", "path", "=", "quote", "(", "path", ",", "b'/%'", ")", "querystring", "=", "quote_plus", "(", "querystring", ",", "b':&='", ")", "return", "urlunsplit", "(", "(", "scheme", ",", "netloc", ",", "path", ",", "querystring", ",", "fragment", ")", ")" ]
escapes special characters
[ "escapes", "special", "characters" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L831-L840
train
gabrielfalcao/HTTPretty
httpretty/core.py
httprettified
def httprettified(test=None, allow_net_connect=True): """decorator for test functions .. tip:: Also available under the alias :py:func:`httpretty.activate` :param test: a callable example usage with `nosetests <https://nose.readthedocs.io/en/latest/>`_ .. testcode:: import sure from httpretty import httprettified @httprettified def test_using_nosetests(): httpretty.register_uri( httpretty.GET, 'https://httpbin.org/ip' ) response = requests.get('https://httpbin.org/ip') response.json().should.equal({ "message": "HTTPretty :)" }) example usage with `unittest module <https://docs.python.org/3/library/unittest.html>`_ .. testcode:: import unittest from sure import expect from httpretty import httprettified @httprettified class TestWithPyUnit(unittest.TestCase): def test_httpbin(self): httpretty.register_uri(httpretty.GET, 'https://httpbin.org/ip') response = requests.get('https://httpbin.org/ip') expect(response.json()).to.equal({ "message": "HTTPretty :)" }) """ def decorate_unittest_TestCase_setUp(klass): # Prefer addCleanup (added in python 2.7), but fall back # to using tearDown if it isn't available use_addCleanup = hasattr(klass, 'addCleanup') original_setUp = (klass.setUp if hasattr(klass, 'setUp') else None) def new_setUp(self): httpretty.reset() httpretty.enable(allow_net_connect) if use_addCleanup: self.addCleanup(httpretty.disable) if original_setUp: original_setUp(self) klass.setUp = new_setUp if not use_addCleanup: original_tearDown = (klass.setUp if hasattr(klass, 'tearDown') else None) def new_tearDown(self): httpretty.disable() httpretty.reset() if original_tearDown: original_tearDown(self) klass.tearDown = new_tearDown return klass def decorate_test_methods(klass): for attr in dir(klass): if not attr.startswith('test_'): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue setattr(klass, attr, decorate_callable(attr_value)) return klass def is_unittest_TestCase(klass): try: import unittest return issubclass(klass, unittest.TestCase) except ImportError: return False "A decorator for tests that use HTTPretty" def decorate_class(klass): if is_unittest_TestCase(klass): return decorate_unittest_TestCase_setUp(klass) return decorate_test_methods(klass) def decorate_callable(test): @functools.wraps(test) def wrapper(*args, **kw): with httprettized(allow_net_connect): return test(*args, **kw) return wrapper if isinstance(test, ClassTypes): return decorate_class(test) elif callable(test): return decorate_callable(test) return decorate_callable
python
def httprettified(test=None, allow_net_connect=True): """decorator for test functions .. tip:: Also available under the alias :py:func:`httpretty.activate` :param test: a callable example usage with `nosetests <https://nose.readthedocs.io/en/latest/>`_ .. testcode:: import sure from httpretty import httprettified @httprettified def test_using_nosetests(): httpretty.register_uri( httpretty.GET, 'https://httpbin.org/ip' ) response = requests.get('https://httpbin.org/ip') response.json().should.equal({ "message": "HTTPretty :)" }) example usage with `unittest module <https://docs.python.org/3/library/unittest.html>`_ .. testcode:: import unittest from sure import expect from httpretty import httprettified @httprettified class TestWithPyUnit(unittest.TestCase): def test_httpbin(self): httpretty.register_uri(httpretty.GET, 'https://httpbin.org/ip') response = requests.get('https://httpbin.org/ip') expect(response.json()).to.equal({ "message": "HTTPretty :)" }) """ def decorate_unittest_TestCase_setUp(klass): # Prefer addCleanup (added in python 2.7), but fall back # to using tearDown if it isn't available use_addCleanup = hasattr(klass, 'addCleanup') original_setUp = (klass.setUp if hasattr(klass, 'setUp') else None) def new_setUp(self): httpretty.reset() httpretty.enable(allow_net_connect) if use_addCleanup: self.addCleanup(httpretty.disable) if original_setUp: original_setUp(self) klass.setUp = new_setUp if not use_addCleanup: original_tearDown = (klass.setUp if hasattr(klass, 'tearDown') else None) def new_tearDown(self): httpretty.disable() httpretty.reset() if original_tearDown: original_tearDown(self) klass.tearDown = new_tearDown return klass def decorate_test_methods(klass): for attr in dir(klass): if not attr.startswith('test_'): continue attr_value = getattr(klass, attr) if not hasattr(attr_value, "__call__"): continue setattr(klass, attr, decorate_callable(attr_value)) return klass def is_unittest_TestCase(klass): try: import unittest return issubclass(klass, unittest.TestCase) except ImportError: return False "A decorator for tests that use HTTPretty" def decorate_class(klass): if is_unittest_TestCase(klass): return decorate_unittest_TestCase_setUp(klass) return decorate_test_methods(klass) def decorate_callable(test): @functools.wraps(test) def wrapper(*args, **kw): with httprettized(allow_net_connect): return test(*args, **kw) return wrapper if isinstance(test, ClassTypes): return decorate_class(test) elif callable(test): return decorate_callable(test) return decorate_callable
[ "def", "httprettified", "(", "test", "=", "None", ",", "allow_net_connect", "=", "True", ")", ":", "def", "decorate_unittest_TestCase_setUp", "(", "klass", ")", ":", "# Prefer addCleanup (added in python 2.7), but fall back", "# to using tearDown if it isn't available", "use_addCleanup", "=", "hasattr", "(", "klass", ",", "'addCleanup'", ")", "original_setUp", "=", "(", "klass", ".", "setUp", "if", "hasattr", "(", "klass", ",", "'setUp'", ")", "else", "None", ")", "def", "new_setUp", "(", "self", ")", ":", "httpretty", ".", "reset", "(", ")", "httpretty", ".", "enable", "(", "allow_net_connect", ")", "if", "use_addCleanup", ":", "self", ".", "addCleanup", "(", "httpretty", ".", "disable", ")", "if", "original_setUp", ":", "original_setUp", "(", "self", ")", "klass", ".", "setUp", "=", "new_setUp", "if", "not", "use_addCleanup", ":", "original_tearDown", "=", "(", "klass", ".", "setUp", "if", "hasattr", "(", "klass", ",", "'tearDown'", ")", "else", "None", ")", "def", "new_tearDown", "(", "self", ")", ":", "httpretty", ".", "disable", "(", ")", "httpretty", ".", "reset", "(", ")", "if", "original_tearDown", ":", "original_tearDown", "(", "self", ")", "klass", ".", "tearDown", "=", "new_tearDown", "return", "klass", "def", "decorate_test_methods", "(", "klass", ")", ":", "for", "attr", "in", "dir", "(", "klass", ")", ":", "if", "not", "attr", ".", "startswith", "(", "'test_'", ")", ":", "continue", "attr_value", "=", "getattr", "(", "klass", ",", "attr", ")", "if", "not", "hasattr", "(", "attr_value", ",", "\"__call__\"", ")", ":", "continue", "setattr", "(", "klass", ",", "attr", ",", "decorate_callable", "(", "attr_value", ")", ")", "return", "klass", "def", "is_unittest_TestCase", "(", "klass", ")", ":", "try", ":", "import", "unittest", "return", "issubclass", "(", "klass", ",", "unittest", ".", "TestCase", ")", "except", "ImportError", ":", "return", "False", "\"A decorator for tests that use HTTPretty\"", "def", "decorate_class", "(", "klass", ")", ":", "if", "is_unittest_TestCase", "(", "klass", ")", ":", "return", "decorate_unittest_TestCase_setUp", "(", "klass", ")", "return", "decorate_test_methods", "(", "klass", ")", "def", "decorate_callable", "(", "test", ")", ":", "@", "functools", ".", "wraps", "(", "test", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kw", ")", ":", "with", "httprettized", "(", "allow_net_connect", ")", ":", "return", "test", "(", "*", "args", ",", "*", "*", "kw", ")", "return", "wrapper", "if", "isinstance", "(", "test", ",", "ClassTypes", ")", ":", "return", "decorate_class", "(", "test", ")", "elif", "callable", "(", "test", ")", ":", "return", "decorate_callable", "(", "test", ")", "return", "decorate_callable" ]
decorator for test functions .. tip:: Also available under the alias :py:func:`httpretty.activate` :param test: a callable example usage with `nosetests <https://nose.readthedocs.io/en/latest/>`_ .. testcode:: import sure from httpretty import httprettified @httprettified def test_using_nosetests(): httpretty.register_uri( httpretty.GET, 'https://httpbin.org/ip' ) response = requests.get('https://httpbin.org/ip') response.json().should.equal({ "message": "HTTPretty :)" }) example usage with `unittest module <https://docs.python.org/3/library/unittest.html>`_ .. testcode:: import unittest from sure import expect from httpretty import httprettified @httprettified class TestWithPyUnit(unittest.TestCase): def test_httpbin(self): httpretty.register_uri(httpretty.GET, 'https://httpbin.org/ip') response = requests.get('https://httpbin.org/ip') expect(response.json()).to.equal({ "message": "HTTPretty :)" })
[ "decorator", "for", "test", "functions" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L1594-L1709
train
gabrielfalcao/HTTPretty
httpretty/core.py
HTTPrettyRequest.parse_request_body
def parse_request_body(self, body): """Attempt to parse the post based on the content-type passed. Return the regular body if not :param body: string :returns: a python object such as dict or list in case the deserialization suceeded. Else returns the given param ``body`` """ PARSING_FUNCTIONS = { 'application/json': json.loads, 'text/json': json.loads, 'application/x-www-form-urlencoded': self.parse_querystring, } content_type = self.headers.get('content-type', '') do_parse = PARSING_FUNCTIONS.get(content_type, FALLBACK_FUNCTION) try: body = decode_utf8(body) return do_parse(body) except (Exception, BaseException): return body
python
def parse_request_body(self, body): """Attempt to parse the post based on the content-type passed. Return the regular body if not :param body: string :returns: a python object such as dict or list in case the deserialization suceeded. Else returns the given param ``body`` """ PARSING_FUNCTIONS = { 'application/json': json.loads, 'text/json': json.loads, 'application/x-www-form-urlencoded': self.parse_querystring, } content_type = self.headers.get('content-type', '') do_parse = PARSING_FUNCTIONS.get(content_type, FALLBACK_FUNCTION) try: body = decode_utf8(body) return do_parse(body) except (Exception, BaseException): return body
[ "def", "parse_request_body", "(", "self", ",", "body", ")", ":", "PARSING_FUNCTIONS", "=", "{", "'application/json'", ":", "json", ".", "loads", ",", "'text/json'", ":", "json", ".", "loads", ",", "'application/x-www-form-urlencoded'", ":", "self", ".", "parse_querystring", ",", "}", "content_type", "=", "self", ".", "headers", ".", "get", "(", "'content-type'", ",", "''", ")", "do_parse", "=", "PARSING_FUNCTIONS", ".", "get", "(", "content_type", ",", "FALLBACK_FUNCTION", ")", "try", ":", "body", "=", "decode_utf8", "(", "body", ")", "return", "do_parse", "(", "body", ")", "except", "(", "Exception", ",", "BaseException", ")", ":", "return", "body" ]
Attempt to parse the post based on the content-type passed. Return the regular body if not :param body: string :returns: a python object such as dict or list in case the deserialization suceeded. Else returns the given param ``body``
[ "Attempt", "to", "parse", "the", "post", "based", "on", "the", "content", "-", "type", "passed", ".", "Return", "the", "regular", "body", "if", "not" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L256-L277
train
gabrielfalcao/HTTPretty
httpretty/core.py
Entry.fill_filekind
def fill_filekind(self, fk): """writes HTTP Response data to a file descriptor :parm fk: a file-like object .. warning:: **side-effect:** this method moves the cursor of the given file object to zero """ now = datetime.utcnow() headers = { 'status': self.status, 'date': now.strftime('%a, %d %b %Y %H:%M:%S GMT'), 'server': 'Python/HTTPretty', 'connection': 'close', } if self.forcing_headers: headers = self.forcing_headers if self.adding_headers: headers.update( self.normalize_headers( self.adding_headers)) headers = self.normalize_headers(headers) status = headers.get('status', self.status) if self.body_is_callable: status, headers, self.body = self.callable_body(self.request, self.info.full_url(), headers) headers = self.normalize_headers(headers) # TODO: document this behavior: if 'content-length' not in headers: headers.update({ 'content-length': len(self.body) }) string_list = [ 'HTTP/1.1 %d %s' % (status, STATUSES[status]), ] if 'date' in headers: string_list.append('date: %s' % headers.pop('date')) if not self.forcing_headers: content_type = headers.pop('content-type', 'text/plain; charset=utf-8') content_length = headers.pop('content-length', self.body_length) string_list.append('content-type: %s' % content_type) if not self.streaming: string_list.append('content-length: %s' % content_length) server = headers.pop('server', None) if server: string_list.append('server: %s' % server) for k, v in headers.items(): string_list.append( '{}: {}'.format(k, v), ) for item in string_list: fk.write(utf8(item) + b'\n') fk.write(b'\r\n') if self.streaming: self.body, body = itertools.tee(self.body) for chunk in body: fk.write(utf8(chunk)) else: fk.write(utf8(self.body)) fk.seek(0)
python
def fill_filekind(self, fk): """writes HTTP Response data to a file descriptor :parm fk: a file-like object .. warning:: **side-effect:** this method moves the cursor of the given file object to zero """ now = datetime.utcnow() headers = { 'status': self.status, 'date': now.strftime('%a, %d %b %Y %H:%M:%S GMT'), 'server': 'Python/HTTPretty', 'connection': 'close', } if self.forcing_headers: headers = self.forcing_headers if self.adding_headers: headers.update( self.normalize_headers( self.adding_headers)) headers = self.normalize_headers(headers) status = headers.get('status', self.status) if self.body_is_callable: status, headers, self.body = self.callable_body(self.request, self.info.full_url(), headers) headers = self.normalize_headers(headers) # TODO: document this behavior: if 'content-length' not in headers: headers.update({ 'content-length': len(self.body) }) string_list = [ 'HTTP/1.1 %d %s' % (status, STATUSES[status]), ] if 'date' in headers: string_list.append('date: %s' % headers.pop('date')) if not self.forcing_headers: content_type = headers.pop('content-type', 'text/plain; charset=utf-8') content_length = headers.pop('content-length', self.body_length) string_list.append('content-type: %s' % content_type) if not self.streaming: string_list.append('content-length: %s' % content_length) server = headers.pop('server', None) if server: string_list.append('server: %s' % server) for k, v in headers.items(): string_list.append( '{}: {}'.format(k, v), ) for item in string_list: fk.write(utf8(item) + b'\n') fk.write(b'\r\n') if self.streaming: self.body, body = itertools.tee(self.body) for chunk in body: fk.write(utf8(chunk)) else: fk.write(utf8(self.body)) fk.seek(0)
[ "def", "fill_filekind", "(", "self", ",", "fk", ")", ":", "now", "=", "datetime", ".", "utcnow", "(", ")", "headers", "=", "{", "'status'", ":", "self", ".", "status", ",", "'date'", ":", "now", ".", "strftime", "(", "'%a, %d %b %Y %H:%M:%S GMT'", ")", ",", "'server'", ":", "'Python/HTTPretty'", ",", "'connection'", ":", "'close'", ",", "}", "if", "self", ".", "forcing_headers", ":", "headers", "=", "self", ".", "forcing_headers", "if", "self", ".", "adding_headers", ":", "headers", ".", "update", "(", "self", ".", "normalize_headers", "(", "self", ".", "adding_headers", ")", ")", "headers", "=", "self", ".", "normalize_headers", "(", "headers", ")", "status", "=", "headers", ".", "get", "(", "'status'", ",", "self", ".", "status", ")", "if", "self", ".", "body_is_callable", ":", "status", ",", "headers", ",", "self", ".", "body", "=", "self", ".", "callable_body", "(", "self", ".", "request", ",", "self", ".", "info", ".", "full_url", "(", ")", ",", "headers", ")", "headers", "=", "self", ".", "normalize_headers", "(", "headers", ")", "# TODO: document this behavior:", "if", "'content-length'", "not", "in", "headers", ":", "headers", ".", "update", "(", "{", "'content-length'", ":", "len", "(", "self", ".", "body", ")", "}", ")", "string_list", "=", "[", "'HTTP/1.1 %d %s'", "%", "(", "status", ",", "STATUSES", "[", "status", "]", ")", ",", "]", "if", "'date'", "in", "headers", ":", "string_list", ".", "append", "(", "'date: %s'", "%", "headers", ".", "pop", "(", "'date'", ")", ")", "if", "not", "self", ".", "forcing_headers", ":", "content_type", "=", "headers", ".", "pop", "(", "'content-type'", ",", "'text/plain; charset=utf-8'", ")", "content_length", "=", "headers", ".", "pop", "(", "'content-length'", ",", "self", ".", "body_length", ")", "string_list", ".", "append", "(", "'content-type: %s'", "%", "content_type", ")", "if", "not", "self", ".", "streaming", ":", "string_list", ".", "append", "(", "'content-length: %s'", "%", "content_length", ")", "server", "=", "headers", ".", "pop", "(", "'server'", ",", "None", ")", "if", "server", ":", "string_list", ".", "append", "(", "'server: %s'", "%", "server", ")", "for", "k", ",", "v", "in", "headers", ".", "items", "(", ")", ":", "string_list", ".", "append", "(", "'{}: {}'", ".", "format", "(", "k", ",", "v", ")", ",", ")", "for", "item", "in", "string_list", ":", "fk", ".", "write", "(", "utf8", "(", "item", ")", "+", "b'\\n'", ")", "fk", ".", "write", "(", "b'\\r\\n'", ")", "if", "self", ".", "streaming", ":", "self", ".", "body", ",", "body", "=", "itertools", ".", "tee", "(", "self", ".", "body", ")", "for", "chunk", "in", "body", ":", "fk", ".", "write", "(", "utf8", "(", "chunk", ")", ")", "else", ":", "fk", ".", "write", "(", "utf8", "(", "self", ".", "body", ")", ")", "fk", ".", "seek", "(", "0", ")" ]
writes HTTP Response data to a file descriptor :parm fk: a file-like object .. warning:: **side-effect:** this method moves the cursor of the given file object to zero
[ "writes", "HTTP", "Response", "data", "to", "a", "file", "descriptor" ]
91dab803011d190c4602cf4c2a07a19835a092e3
https://github.com/gabrielfalcao/HTTPretty/blob/91dab803011d190c4602cf4c2a07a19835a092e3/httpretty/core.py#L754-L828
train
trehn/termdown
termdown.py
draw_text
def draw_text(stdscr, text, color=0, fallback=None, title=None): """ Draws text in the given color. Duh. """ if fallback is None: fallback = text y, x = stdscr.getmaxyx() if title: title = pad_to_size(title, x, 1) if "\n" in title.rstrip("\n"): # hack to get more spacing between title and body for figlet title += "\n" * 5 text = title + "\n" + pad_to_size(text, x, len(text.split("\n"))) lines = pad_to_size(text, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: lines = pad_to_size(fallback, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines[:]): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: pass stdscr.refresh()
python
def draw_text(stdscr, text, color=0, fallback=None, title=None): """ Draws text in the given color. Duh. """ if fallback is None: fallback = text y, x = stdscr.getmaxyx() if title: title = pad_to_size(title, x, 1) if "\n" in title.rstrip("\n"): # hack to get more spacing between title and body for figlet title += "\n" * 5 text = title + "\n" + pad_to_size(text, x, len(text.split("\n"))) lines = pad_to_size(text, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: lines = pad_to_size(fallback, x, y).rstrip("\n").split("\n") try: for i, line in enumerate(lines[:]): stdscr.insstr(i, 0, line, curses.color_pair(color)) except: pass stdscr.refresh()
[ "def", "draw_text", "(", "stdscr", ",", "text", ",", "color", "=", "0", ",", "fallback", "=", "None", ",", "title", "=", "None", ")", ":", "if", "fallback", "is", "None", ":", "fallback", "=", "text", "y", ",", "x", "=", "stdscr", ".", "getmaxyx", "(", ")", "if", "title", ":", "title", "=", "pad_to_size", "(", "title", ",", "x", ",", "1", ")", "if", "\"\\n\"", "in", "title", ".", "rstrip", "(", "\"\\n\"", ")", ":", "# hack to get more spacing between title and body for figlet", "title", "+=", "\"\\n\"", "*", "5", "text", "=", "title", "+", "\"\\n\"", "+", "pad_to_size", "(", "text", ",", "x", ",", "len", "(", "text", ".", "split", "(", "\"\\n\"", ")", ")", ")", "lines", "=", "pad_to_size", "(", "text", ",", "x", ",", "y", ")", ".", "rstrip", "(", "\"\\n\"", ")", ".", "split", "(", "\"\\n\"", ")", "try", ":", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "stdscr", ".", "insstr", "(", "i", ",", "0", ",", "line", ",", "curses", ".", "color_pair", "(", "color", ")", ")", "except", ":", "lines", "=", "pad_to_size", "(", "fallback", ",", "x", ",", "y", ")", ".", "rstrip", "(", "\"\\n\"", ")", ".", "split", "(", "\"\\n\"", ")", "try", ":", "for", "i", ",", "line", "in", "enumerate", "(", "lines", "[", ":", "]", ")", ":", "stdscr", ".", "insstr", "(", "i", ",", "0", ",", "line", ",", "curses", ".", "color_pair", "(", "color", ")", ")", "except", ":", "pass", "stdscr", ".", "refresh", "(", ")" ]
Draws text in the given color. Duh.
[ "Draws", "text", "in", "the", "given", "color", ".", "Duh", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L70-L95
train
trehn/termdown
termdown.py
format_seconds
def format_seconds(seconds, hide_seconds=False): """ Returns a human-readable string representation of the given amount of seconds. """ if seconds <= 60: return str(seconds) output = "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600), ('m', 60), ('s', 1), ): if seconds >= period_seconds and not (hide_seconds and period == 's'): output += str(int(seconds / period_seconds)) output += period output += " " seconds = seconds % period_seconds return output.strip()
python
def format_seconds(seconds, hide_seconds=False): """ Returns a human-readable string representation of the given amount of seconds. """ if seconds <= 60: return str(seconds) output = "" for period, period_seconds in ( ('y', 31557600), ('d', 86400), ('h', 3600), ('m', 60), ('s', 1), ): if seconds >= period_seconds and not (hide_seconds and period == 's'): output += str(int(seconds / period_seconds)) output += period output += " " seconds = seconds % period_seconds return output.strip()
[ "def", "format_seconds", "(", "seconds", ",", "hide_seconds", "=", "False", ")", ":", "if", "seconds", "<=", "60", ":", "return", "str", "(", "seconds", ")", "output", "=", "\"\"", "for", "period", ",", "period_seconds", "in", "(", "(", "'y'", ",", "31557600", ")", ",", "(", "'d'", ",", "86400", ")", ",", "(", "'h'", ",", "3600", ")", ",", "(", "'m'", ",", "60", ")", ",", "(", "'s'", ",", "1", ")", ",", ")", ":", "if", "seconds", ">=", "period_seconds", "and", "not", "(", "hide_seconds", "and", "period", "==", "'s'", ")", ":", "output", "+=", "str", "(", "int", "(", "seconds", "/", "period_seconds", ")", ")", "output", "+=", "period", "output", "+=", "\" \"", "seconds", "=", "seconds", "%", "period_seconds", "return", "output", ".", "strip", "(", ")" ]
Returns a human-readable string representation of the given amount of seconds.
[ "Returns", "a", "human", "-", "readable", "string", "representation", "of", "the", "given", "amount", "of", "seconds", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L98-L118
train
trehn/termdown
termdown.py
graceful_ctrlc
def graceful_ctrlc(func): """ Makes the decorated function exit with code 1 on CTRL+C. """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except KeyboardInterrupt: exit(1) return wrapper
python
def graceful_ctrlc(func): """ Makes the decorated function exit with code 1 on CTRL+C. """ @wraps(func) def wrapper(*args, **kwargs): try: return func(*args, **kwargs) except KeyboardInterrupt: exit(1) return wrapper
[ "def", "graceful_ctrlc", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "func", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "KeyboardInterrupt", ":", "exit", "(", "1", ")", "return", "wrapper" ]
Makes the decorated function exit with code 1 on CTRL+C.
[ "Makes", "the", "decorated", "function", "exit", "with", "code", "1", "on", "CTRL", "+", "C", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L144-L154
train
trehn/termdown
termdown.py
pad_to_size
def pad_to_size(text, x, y): """ Adds whitespace to text to center it within a frame of the given dimensions. """ input_lines = text.rstrip().split("\n") longest_input_line = max(map(len, input_lines)) number_of_input_lines = len(input_lines) x = max(x, longest_input_line) y = max(y, number_of_input_lines) output = "" padding_top = int((y - number_of_input_lines) / 2) padding_bottom = y - number_of_input_lines - padding_top padding_left = int((x - longest_input_line) / 2) output += padding_top * (" " * x + "\n") for line in input_lines: output += padding_left * " " + line + " " * (x - padding_left - len(line)) + "\n" output += padding_bottom * (" " * x + "\n") return output
python
def pad_to_size(text, x, y): """ Adds whitespace to text to center it within a frame of the given dimensions. """ input_lines = text.rstrip().split("\n") longest_input_line = max(map(len, input_lines)) number_of_input_lines = len(input_lines) x = max(x, longest_input_line) y = max(y, number_of_input_lines) output = "" padding_top = int((y - number_of_input_lines) / 2) padding_bottom = y - number_of_input_lines - padding_top padding_left = int((x - longest_input_line) / 2) output += padding_top * (" " * x + "\n") for line in input_lines: output += padding_left * " " + line + " " * (x - padding_left - len(line)) + "\n" output += padding_bottom * (" " * x + "\n") return output
[ "def", "pad_to_size", "(", "text", ",", "x", ",", "y", ")", ":", "input_lines", "=", "text", ".", "rstrip", "(", ")", ".", "split", "(", "\"\\n\"", ")", "longest_input_line", "=", "max", "(", "map", "(", "len", ",", "input_lines", ")", ")", "number_of_input_lines", "=", "len", "(", "input_lines", ")", "x", "=", "max", "(", "x", ",", "longest_input_line", ")", "y", "=", "max", "(", "y", ",", "number_of_input_lines", ")", "output", "=", "\"\"", "padding_top", "=", "int", "(", "(", "y", "-", "number_of_input_lines", ")", "/", "2", ")", "padding_bottom", "=", "y", "-", "number_of_input_lines", "-", "padding_top", "padding_left", "=", "int", "(", "(", "x", "-", "longest_input_line", ")", "/", "2", ")", "output", "+=", "padding_top", "*", "(", "\" \"", "*", "x", "+", "\"\\n\"", ")", "for", "line", "in", "input_lines", ":", "output", "+=", "padding_left", "*", "\" \"", "+", "line", "+", "\" \"", "*", "(", "x", "-", "padding_left", "-", "len", "(", "line", ")", ")", "+", "\"\\n\"", "output", "+=", "padding_bottom", "*", "(", "\" \"", "*", "x", "+", "\"\\n\"", ")", "return", "output" ]
Adds whitespace to text to center it within a frame of the given dimensions.
[ "Adds", "whitespace", "to", "text", "to", "center", "it", "within", "a", "frame", "of", "the", "given", "dimensions", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L177-L198
train
trehn/termdown
termdown.py
parse_timestr
def parse_timestr(timestr): """ Parse a string describing a point in time. """ timedelta_secs = parse_timedelta(timestr) sync_start = datetime.now() if timedelta_secs: target = datetime.now() + timedelta(seconds=timedelta_secs) elif timestr.isdigit(): target = datetime.now() + timedelta(seconds=int(timestr)) else: try: target = parse(timestr) except: # unfortunately, dateutil doesn't raise the best exceptions raise ValueError("Unable to parse '{}'".format(timestr)) # When I do "termdown 10" (the two cases above), I want a # countdown for the next 10 seconds. Okay. But when I do # "termdown 23:52", I want a countdown that ends at that exact # moment -- the countdown is related to real time. Thus, I want # my frames to be drawn at full seconds, so I enforce # microsecond=0. sync_start = sync_start.replace(microsecond=0) try: # try to convert target to naive local timezone target = target.astimezone(tz=tz.tzlocal()).replace(tzinfo=None) except ValueError: # parse() already returned a naive datetime, all is well pass return (sync_start, target)
python
def parse_timestr(timestr): """ Parse a string describing a point in time. """ timedelta_secs = parse_timedelta(timestr) sync_start = datetime.now() if timedelta_secs: target = datetime.now() + timedelta(seconds=timedelta_secs) elif timestr.isdigit(): target = datetime.now() + timedelta(seconds=int(timestr)) else: try: target = parse(timestr) except: # unfortunately, dateutil doesn't raise the best exceptions raise ValueError("Unable to parse '{}'".format(timestr)) # When I do "termdown 10" (the two cases above), I want a # countdown for the next 10 seconds. Okay. But when I do # "termdown 23:52", I want a countdown that ends at that exact # moment -- the countdown is related to real time. Thus, I want # my frames to be drawn at full seconds, so I enforce # microsecond=0. sync_start = sync_start.replace(microsecond=0) try: # try to convert target to naive local timezone target = target.astimezone(tz=tz.tzlocal()).replace(tzinfo=None) except ValueError: # parse() already returned a naive datetime, all is well pass return (sync_start, target)
[ "def", "parse_timestr", "(", "timestr", ")", ":", "timedelta_secs", "=", "parse_timedelta", "(", "timestr", ")", "sync_start", "=", "datetime", ".", "now", "(", ")", "if", "timedelta_secs", ":", "target", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "timedelta_secs", ")", "elif", "timestr", ".", "isdigit", "(", ")", ":", "target", "=", "datetime", ".", "now", "(", ")", "+", "timedelta", "(", "seconds", "=", "int", "(", "timestr", ")", ")", "else", ":", "try", ":", "target", "=", "parse", "(", "timestr", ")", "except", ":", "# unfortunately, dateutil doesn't raise the best exceptions", "raise", "ValueError", "(", "\"Unable to parse '{}'\"", ".", "format", "(", "timestr", ")", ")", "# When I do \"termdown 10\" (the two cases above), I want a", "# countdown for the next 10 seconds. Okay. But when I do", "# \"termdown 23:52\", I want a countdown that ends at that exact", "# moment -- the countdown is related to real time. Thus, I want", "# my frames to be drawn at full seconds, so I enforce", "# microsecond=0.", "sync_start", "=", "sync_start", ".", "replace", "(", "microsecond", "=", "0", ")", "try", ":", "# try to convert target to naive local timezone", "target", "=", "target", ".", "astimezone", "(", "tz", "=", "tz", ".", "tzlocal", "(", ")", ")", ".", "replace", "(", "tzinfo", "=", "None", ")", "except", "ValueError", ":", "# parse() already returned a naive datetime, all is well", "pass", "return", "(", "sync_start", ",", "target", ")" ]
Parse a string describing a point in time.
[ "Parse", "a", "string", "describing", "a", "point", "in", "time", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L201-L232
train
trehn/termdown
termdown.py
parse_timedelta
def parse_timedelta(deltastr): """ Parse a string describing a period of time. """ matches = TIMEDELTA_REGEX.match(deltastr) if not matches: return None components = {} for name, value in matches.groupdict().items(): if value: components[name] = int(value) for period, hours in (('days', 24), ('years', 8766)): if period in components: components['hours'] = components.get('hours', 0) + \ components[period] * hours del components[period] return int(timedelta(**components).total_seconds())
python
def parse_timedelta(deltastr): """ Parse a string describing a period of time. """ matches = TIMEDELTA_REGEX.match(deltastr) if not matches: return None components = {} for name, value in matches.groupdict().items(): if value: components[name] = int(value) for period, hours in (('days', 24), ('years', 8766)): if period in components: components['hours'] = components.get('hours', 0) + \ components[period] * hours del components[period] return int(timedelta(**components).total_seconds())
[ "def", "parse_timedelta", "(", "deltastr", ")", ":", "matches", "=", "TIMEDELTA_REGEX", ".", "match", "(", "deltastr", ")", "if", "not", "matches", ":", "return", "None", "components", "=", "{", "}", "for", "name", ",", "value", "in", "matches", ".", "groupdict", "(", ")", ".", "items", "(", ")", ":", "if", "value", ":", "components", "[", "name", "]", "=", "int", "(", "value", ")", "for", "period", ",", "hours", "in", "(", "(", "'days'", ",", "24", ")", ",", "(", "'years'", ",", "8766", ")", ")", ":", "if", "period", "in", "components", ":", "components", "[", "'hours'", "]", "=", "components", ".", "get", "(", "'hours'", ",", "0", ")", "+", "components", "[", "period", "]", "*", "hours", "del", "components", "[", "period", "]", "return", "int", "(", "timedelta", "(", "*", "*", "components", ")", ".", "total_seconds", "(", ")", ")" ]
Parse a string describing a period of time.
[ "Parse", "a", "string", "describing", "a", "period", "of", "time", "." ]
aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2
https://github.com/trehn/termdown/blob/aa0c4e39d9864fd1466ef9d76947fb93d0cf5be2/termdown.py#L235-L251
train
wakatime/wakatime
wakatime/packages/ntlm_auth/session_security.py
SessionSecurity._verify_signature
def _verify_signature(self, message, signature): """ Will verify that the signature received from the server matches up with the expected signature computed locally. Will throw an exception if they do not match @param message: The message data that is received from the server @param signature: The signature of the message received from the server """ if self.negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: actual_checksum = signature[4:12] actual_seq_num = struct.unpack("<I", signature[12:16])[0] else: actual_checksum = signature[8:12] actual_seq_num = struct.unpack("<I", signature[12:16])[0] expected_signature = calc_signature(message, self.negotiate_flags, self.incoming_signing_key, self.incoming_seq_num, self.incoming_handle) expected_checksum = expected_signature.checksum expected_seq_num = struct.unpack("<I", expected_signature.seq_num)[0] if actual_checksum != expected_checksum: raise Exception("The signature checksum does not match, message has been altered") if actual_seq_num != expected_seq_num: raise Exception("The signature sequence number does not match up, message not received in the correct sequence") self.incoming_seq_num += 1
python
def _verify_signature(self, message, signature): """ Will verify that the signature received from the server matches up with the expected signature computed locally. Will throw an exception if they do not match @param message: The message data that is received from the server @param signature: The signature of the message received from the server """ if self.negotiate_flags & NegotiateFlags.NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY: actual_checksum = signature[4:12] actual_seq_num = struct.unpack("<I", signature[12:16])[0] else: actual_checksum = signature[8:12] actual_seq_num = struct.unpack("<I", signature[12:16])[0] expected_signature = calc_signature(message, self.negotiate_flags, self.incoming_signing_key, self.incoming_seq_num, self.incoming_handle) expected_checksum = expected_signature.checksum expected_seq_num = struct.unpack("<I", expected_signature.seq_num)[0] if actual_checksum != expected_checksum: raise Exception("The signature checksum does not match, message has been altered") if actual_seq_num != expected_seq_num: raise Exception("The signature sequence number does not match up, message not received in the correct sequence") self.incoming_seq_num += 1
[ "def", "_verify_signature", "(", "self", ",", "message", ",", "signature", ")", ":", "if", "self", ".", "negotiate_flags", "&", "NegotiateFlags", ".", "NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY", ":", "actual_checksum", "=", "signature", "[", "4", ":", "12", "]", "actual_seq_num", "=", "struct", ".", "unpack", "(", "\"<I\"", ",", "signature", "[", "12", ":", "16", "]", ")", "[", "0", "]", "else", ":", "actual_checksum", "=", "signature", "[", "8", ":", "12", "]", "actual_seq_num", "=", "struct", ".", "unpack", "(", "\"<I\"", ",", "signature", "[", "12", ":", "16", "]", ")", "[", "0", "]", "expected_signature", "=", "calc_signature", "(", "message", ",", "self", ".", "negotiate_flags", ",", "self", ".", "incoming_signing_key", ",", "self", ".", "incoming_seq_num", ",", "self", ".", "incoming_handle", ")", "expected_checksum", "=", "expected_signature", ".", "checksum", "expected_seq_num", "=", "struct", ".", "unpack", "(", "\"<I\"", ",", "expected_signature", ".", "seq_num", ")", "[", "0", "]", "if", "actual_checksum", "!=", "expected_checksum", ":", "raise", "Exception", "(", "\"The signature checksum does not match, message has been altered\"", ")", "if", "actual_seq_num", "!=", "expected_seq_num", ":", "raise", "Exception", "(", "\"The signature sequence number does not match up, message not received in the correct sequence\"", ")", "self", ".", "incoming_seq_num", "+=", "1" ]
Will verify that the signature received from the server matches up with the expected signature computed locally. Will throw an exception if they do not match @param message: The message data that is received from the server @param signature: The signature of the message received from the server
[ "Will", "verify", "that", "the", "signature", "received", "from", "the", "server", "matches", "up", "with", "the", "expected", "signature", "computed", "locally", ".", "Will", "throw", "an", "exception", "if", "they", "do", "not", "match" ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/ntlm_auth/session_security.py#L201-L226
train
wakatime/wakatime
wakatime/packages/pygments/regexopt.py
regex_opt_inner
def regex_opt_inner(strings, open_paren): """Return a regex that matches any string in the sorted list of strings.""" close_paren = open_paren and ')' or '' # print strings, repr(open_paren) if not strings: # print '-> nothing left' return '' first = strings[0] if len(strings) == 1: # print '-> only 1 string' return open_paren + escape(first) + close_paren if not first: # print '-> first string empty' return open_paren + regex_opt_inner(strings[1:], '(?:') \ + '?' + close_paren if len(first) == 1: # multiple one-char strings? make a charset oneletter = [] rest = [] for s in strings: if len(s) == 1: oneletter.append(s) else: rest.append(s) if len(oneletter) > 1: # do we have more than one oneletter string? if rest: # print '-> 1-character + rest' return open_paren + regex_opt_inner(rest, '') + '|' \ + make_charset(oneletter) + close_paren # print '-> only 1-character' return open_paren + make_charset(oneletter) + close_paren prefix = commonprefix(strings) if prefix: plen = len(prefix) # we have a prefix for all strings # print '-> prefix:', prefix return open_paren + escape(prefix) \ + regex_opt_inner([s[plen:] for s in strings], '(?:') \ + close_paren # is there a suffix? strings_rev = [s[::-1] for s in strings] suffix = commonprefix(strings_rev) if suffix: slen = len(suffix) # print '-> suffix:', suffix[::-1] return open_paren \ + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \ + escape(suffix[::-1]) + close_paren # recurse on common 1-string prefixes # print '-> last resort' return open_paren + \ '|'.join(regex_opt_inner(list(group[1]), '') for group in groupby(strings, lambda s: s[0] == first[0])) \ + close_paren
python
def regex_opt_inner(strings, open_paren): """Return a regex that matches any string in the sorted list of strings.""" close_paren = open_paren and ')' or '' # print strings, repr(open_paren) if not strings: # print '-> nothing left' return '' first = strings[0] if len(strings) == 1: # print '-> only 1 string' return open_paren + escape(first) + close_paren if not first: # print '-> first string empty' return open_paren + regex_opt_inner(strings[1:], '(?:') \ + '?' + close_paren if len(first) == 1: # multiple one-char strings? make a charset oneletter = [] rest = [] for s in strings: if len(s) == 1: oneletter.append(s) else: rest.append(s) if len(oneletter) > 1: # do we have more than one oneletter string? if rest: # print '-> 1-character + rest' return open_paren + regex_opt_inner(rest, '') + '|' \ + make_charset(oneletter) + close_paren # print '-> only 1-character' return open_paren + make_charset(oneletter) + close_paren prefix = commonprefix(strings) if prefix: plen = len(prefix) # we have a prefix for all strings # print '-> prefix:', prefix return open_paren + escape(prefix) \ + regex_opt_inner([s[plen:] for s in strings], '(?:') \ + close_paren # is there a suffix? strings_rev = [s[::-1] for s in strings] suffix = commonprefix(strings_rev) if suffix: slen = len(suffix) # print '-> suffix:', suffix[::-1] return open_paren \ + regex_opt_inner(sorted(s[:-slen] for s in strings), '(?:') \ + escape(suffix[::-1]) + close_paren # recurse on common 1-string prefixes # print '-> last resort' return open_paren + \ '|'.join(regex_opt_inner(list(group[1]), '') for group in groupby(strings, lambda s: s[0] == first[0])) \ + close_paren
[ "def", "regex_opt_inner", "(", "strings", ",", "open_paren", ")", ":", "close_paren", "=", "open_paren", "and", "')'", "or", "''", "# print strings, repr(open_paren)", "if", "not", "strings", ":", "# print '-> nothing left'", "return", "''", "first", "=", "strings", "[", "0", "]", "if", "len", "(", "strings", ")", "==", "1", ":", "# print '-> only 1 string'", "return", "open_paren", "+", "escape", "(", "first", ")", "+", "close_paren", "if", "not", "first", ":", "# print '-> first string empty'", "return", "open_paren", "+", "regex_opt_inner", "(", "strings", "[", "1", ":", "]", ",", "'(?:'", ")", "+", "'?'", "+", "close_paren", "if", "len", "(", "first", ")", "==", "1", ":", "# multiple one-char strings? make a charset", "oneletter", "=", "[", "]", "rest", "=", "[", "]", "for", "s", "in", "strings", ":", "if", "len", "(", "s", ")", "==", "1", ":", "oneletter", ".", "append", "(", "s", ")", "else", ":", "rest", ".", "append", "(", "s", ")", "if", "len", "(", "oneletter", ")", ">", "1", ":", "# do we have more than one oneletter string?", "if", "rest", ":", "# print '-> 1-character + rest'", "return", "open_paren", "+", "regex_opt_inner", "(", "rest", ",", "''", ")", "+", "'|'", "+", "make_charset", "(", "oneletter", ")", "+", "close_paren", "# print '-> only 1-character'", "return", "open_paren", "+", "make_charset", "(", "oneletter", ")", "+", "close_paren", "prefix", "=", "commonprefix", "(", "strings", ")", "if", "prefix", ":", "plen", "=", "len", "(", "prefix", ")", "# we have a prefix for all strings", "# print '-> prefix:', prefix", "return", "open_paren", "+", "escape", "(", "prefix", ")", "+", "regex_opt_inner", "(", "[", "s", "[", "plen", ":", "]", "for", "s", "in", "strings", "]", ",", "'(?:'", ")", "+", "close_paren", "# is there a suffix?", "strings_rev", "=", "[", "s", "[", ":", ":", "-", "1", "]", "for", "s", "in", "strings", "]", "suffix", "=", "commonprefix", "(", "strings_rev", ")", "if", "suffix", ":", "slen", "=", "len", "(", "suffix", ")", "# print '-> suffix:', suffix[::-1]", "return", "open_paren", "+", "regex_opt_inner", "(", "sorted", "(", "s", "[", ":", "-", "slen", "]", "for", "s", "in", "strings", ")", ",", "'(?:'", ")", "+", "escape", "(", "suffix", "[", ":", ":", "-", "1", "]", ")", "+", "close_paren", "# recurse on common 1-string prefixes", "# print '-> last resort'", "return", "open_paren", "+", "'|'", ".", "join", "(", "regex_opt_inner", "(", "list", "(", "group", "[", "1", "]", ")", ",", "''", ")", "for", "group", "in", "groupby", "(", "strings", ",", "lambda", "s", ":", "s", "[", "0", "]", "==", "first", "[", "0", "]", ")", ")", "+", "close_paren" ]
Return a regex that matches any string in the sorted list of strings.
[ "Return", "a", "regex", "that", "matches", "any", "string", "in", "the", "sorted", "list", "of", "strings", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/regexopt.py#L27-L80
train
wakatime/wakatime
wakatime/packages/pygments/regexopt.py
regex_opt
def regex_opt(strings, prefix='', suffix=''): """Return a compiled regex that matches any string in the given list. The strings to match must be literal strings, not regexes. They will be regex-escaped. *prefix* and *suffix* are pre- and appended to the final regex. """ strings = sorted(strings) return prefix + regex_opt_inner(strings, '(') + suffix
python
def regex_opt(strings, prefix='', suffix=''): """Return a compiled regex that matches any string in the given list. The strings to match must be literal strings, not regexes. They will be regex-escaped. *prefix* and *suffix* are pre- and appended to the final regex. """ strings = sorted(strings) return prefix + regex_opt_inner(strings, '(') + suffix
[ "def", "regex_opt", "(", "strings", ",", "prefix", "=", "''", ",", "suffix", "=", "''", ")", ":", "strings", "=", "sorted", "(", "strings", ")", "return", "prefix", "+", "regex_opt_inner", "(", "strings", ",", "'('", ")", "+", "suffix" ]
Return a compiled regex that matches any string in the given list. The strings to match must be literal strings, not regexes. They will be regex-escaped. *prefix* and *suffix* are pre- and appended to the final regex.
[ "Return", "a", "compiled", "regex", "that", "matches", "any", "string", "in", "the", "given", "list", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/regexopt.py#L83-L92
train
wakatime/wakatime
wakatime/packages/pytz/__init__.py
open_resource
def open_resource(name): """Open a resource from the zoneinfo subdir for reading. Uses the pkg_resources module if available and no standard file found at the calculated location. """ name_parts = name.lstrip('/').split('/') for part in name_parts: if part == os.path.pardir or os.path.sep in part: raise ValueError('Bad path segment: %r' % part) filename = os.path.join(os.path.dirname(__file__), 'zoneinfo', *name_parts) if not os.path.exists(filename): # http://bugs.launchpad.net/bugs/383171 - we avoid using this # unless absolutely necessary to help when a broken version of # pkg_resources is installed. try: from pkg_resources import resource_stream except ImportError: resource_stream = None if resource_stream is not None: return resource_stream(__name__, 'zoneinfo/' + name) return open(filename, 'rb')
python
def open_resource(name): """Open a resource from the zoneinfo subdir for reading. Uses the pkg_resources module if available and no standard file found at the calculated location. """ name_parts = name.lstrip('/').split('/') for part in name_parts: if part == os.path.pardir or os.path.sep in part: raise ValueError('Bad path segment: %r' % part) filename = os.path.join(os.path.dirname(__file__), 'zoneinfo', *name_parts) if not os.path.exists(filename): # http://bugs.launchpad.net/bugs/383171 - we avoid using this # unless absolutely necessary to help when a broken version of # pkg_resources is installed. try: from pkg_resources import resource_stream except ImportError: resource_stream = None if resource_stream is not None: return resource_stream(__name__, 'zoneinfo/' + name) return open(filename, 'rb')
[ "def", "open_resource", "(", "name", ")", ":", "name_parts", "=", "name", ".", "lstrip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "for", "part", "in", "name_parts", ":", "if", "part", "==", "os", ".", "path", ".", "pardir", "or", "os", ".", "path", ".", "sep", "in", "part", ":", "raise", "ValueError", "(", "'Bad path segment: %r'", "%", "part", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'zoneinfo'", ",", "*", "name_parts", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "# http://bugs.launchpad.net/bugs/383171 - we avoid using this", "# unless absolutely necessary to help when a broken version of", "# pkg_resources is installed.", "try", ":", "from", "pkg_resources", "import", "resource_stream", "except", "ImportError", ":", "resource_stream", "=", "None", "if", "resource_stream", "is", "not", "None", ":", "return", "resource_stream", "(", "__name__", ",", "'zoneinfo/'", "+", "name", ")", "return", "open", "(", "filename", ",", "'rb'", ")" ]
Open a resource from the zoneinfo subdir for reading. Uses the pkg_resources module if available and no standard file found at the calculated location.
[ "Open", "a", "resource", "from", "the", "zoneinfo", "subdir", "for", "reading", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pytz/__init__.py#L74-L97
train
wakatime/wakatime
wakatime/packages/pytz/__init__.py
FixedOffset
def FixedOffset(offset, _tzinfos = {}): """return a fixed-offset timezone based off a number of minutes. >>> one = FixedOffset(-330) >>> one pytz.FixedOffset(-330) >>> one.utcoffset(datetime.datetime.now()) datetime.timedelta(-1, 66600) >>> one.dst(datetime.datetime.now()) datetime.timedelta(0) >>> two = FixedOffset(1380) >>> two pytz.FixedOffset(1380) >>> two.utcoffset(datetime.datetime.now()) datetime.timedelta(0, 82800) >>> two.dst(datetime.datetime.now()) datetime.timedelta(0) The datetime.timedelta must be between the range of -1 and 1 day, non-inclusive. >>> FixedOffset(1440) Traceback (most recent call last): ... ValueError: ('absolute offset is too large', 1440) >>> FixedOffset(-1440) Traceback (most recent call last): ... ValueError: ('absolute offset is too large', -1440) An offset of 0 is special-cased to return UTC. >>> FixedOffset(0) is UTC True There should always be only one instance of a FixedOffset per timedelta. This should be true for multiple creation calls. >>> FixedOffset(-330) is one True >>> FixedOffset(1380) is two True It should also be true for pickling. >>> import pickle >>> pickle.loads(pickle.dumps(one)) is one True >>> pickle.loads(pickle.dumps(two)) is two True """ if offset == 0: return UTC info = _tzinfos.get(offset) if info is None: # We haven't seen this one before. we need to save it. # Use setdefault to avoid a race condition and make sure we have # only one info = _tzinfos.setdefault(offset, _FixedOffset(offset)) return info
python
def FixedOffset(offset, _tzinfos = {}): """return a fixed-offset timezone based off a number of minutes. >>> one = FixedOffset(-330) >>> one pytz.FixedOffset(-330) >>> one.utcoffset(datetime.datetime.now()) datetime.timedelta(-1, 66600) >>> one.dst(datetime.datetime.now()) datetime.timedelta(0) >>> two = FixedOffset(1380) >>> two pytz.FixedOffset(1380) >>> two.utcoffset(datetime.datetime.now()) datetime.timedelta(0, 82800) >>> two.dst(datetime.datetime.now()) datetime.timedelta(0) The datetime.timedelta must be between the range of -1 and 1 day, non-inclusive. >>> FixedOffset(1440) Traceback (most recent call last): ... ValueError: ('absolute offset is too large', 1440) >>> FixedOffset(-1440) Traceback (most recent call last): ... ValueError: ('absolute offset is too large', -1440) An offset of 0 is special-cased to return UTC. >>> FixedOffset(0) is UTC True There should always be only one instance of a FixedOffset per timedelta. This should be true for multiple creation calls. >>> FixedOffset(-330) is one True >>> FixedOffset(1380) is two True It should also be true for pickling. >>> import pickle >>> pickle.loads(pickle.dumps(one)) is one True >>> pickle.loads(pickle.dumps(two)) is two True """ if offset == 0: return UTC info = _tzinfos.get(offset) if info is None: # We haven't seen this one before. we need to save it. # Use setdefault to avoid a race condition and make sure we have # only one info = _tzinfos.setdefault(offset, _FixedOffset(offset)) return info
[ "def", "FixedOffset", "(", "offset", ",", "_tzinfos", "=", "{", "}", ")", ":", "if", "offset", "==", "0", ":", "return", "UTC", "info", "=", "_tzinfos", ".", "get", "(", "offset", ")", "if", "info", "is", "None", ":", "# We haven't seen this one before. we need to save it.", "# Use setdefault to avoid a race condition and make sure we have", "# only one", "info", "=", "_tzinfos", ".", "setdefault", "(", "offset", ",", "_FixedOffset", "(", "offset", ")", ")", "return", "info" ]
return a fixed-offset timezone based off a number of minutes. >>> one = FixedOffset(-330) >>> one pytz.FixedOffset(-330) >>> one.utcoffset(datetime.datetime.now()) datetime.timedelta(-1, 66600) >>> one.dst(datetime.datetime.now()) datetime.timedelta(0) >>> two = FixedOffset(1380) >>> two pytz.FixedOffset(1380) >>> two.utcoffset(datetime.datetime.now()) datetime.timedelta(0, 82800) >>> two.dst(datetime.datetime.now()) datetime.timedelta(0) The datetime.timedelta must be between the range of -1 and 1 day, non-inclusive. >>> FixedOffset(1440) Traceback (most recent call last): ... ValueError: ('absolute offset is too large', 1440) >>> FixedOffset(-1440) Traceback (most recent call last): ... ValueError: ('absolute offset is too large', -1440) An offset of 0 is special-cased to return UTC. >>> FixedOffset(0) is UTC True There should always be only one instance of a FixedOffset per timedelta. This should be true for multiple creation calls. >>> FixedOffset(-330) is one True >>> FixedOffset(1380) is two True It should also be true for pickling. >>> import pickle >>> pickle.loads(pickle.dumps(one)) is one True >>> pickle.loads(pickle.dumps(two)) is two True
[ "return", "a", "fixed", "-", "offset", "timezone", "based", "off", "a", "number", "of", "minutes", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pytz/__init__.py#L415-L479
train
wakatime/wakatime
wakatime/arguments.py
boolean_or_list
def boolean_or_list(config_name, args, configs, alternative_names=[]): """Get a boolean or list of regexes from args and configs.""" # when argument flag present, set to wildcard regex for key in alternative_names + [config_name]: if hasattr(args, key) and getattr(args, key): setattr(args, config_name, ['.*']) return setattr(args, config_name, []) option = None alternative_names.insert(0, config_name) for key in alternative_names: if configs.has_option('settings', key): option = configs.get('settings', key) break if option is not None: if option.strip().lower() == 'true': setattr(args, config_name, ['.*']) elif option.strip().lower() != 'false': for pattern in option.split("\n"): if pattern.strip() != '': getattr(args, config_name).append(pattern)
python
def boolean_or_list(config_name, args, configs, alternative_names=[]): """Get a boolean or list of regexes from args and configs.""" # when argument flag present, set to wildcard regex for key in alternative_names + [config_name]: if hasattr(args, key) and getattr(args, key): setattr(args, config_name, ['.*']) return setattr(args, config_name, []) option = None alternative_names.insert(0, config_name) for key in alternative_names: if configs.has_option('settings', key): option = configs.get('settings', key) break if option is not None: if option.strip().lower() == 'true': setattr(args, config_name, ['.*']) elif option.strip().lower() != 'false': for pattern in option.split("\n"): if pattern.strip() != '': getattr(args, config_name).append(pattern)
[ "def", "boolean_or_list", "(", "config_name", ",", "args", ",", "configs", ",", "alternative_names", "=", "[", "]", ")", ":", "# when argument flag present, set to wildcard regex", "for", "key", "in", "alternative_names", "+", "[", "config_name", "]", ":", "if", "hasattr", "(", "args", ",", "key", ")", "and", "getattr", "(", "args", ",", "key", ")", ":", "setattr", "(", "args", ",", "config_name", ",", "[", "'.*'", "]", ")", "return", "setattr", "(", "args", ",", "config_name", ",", "[", "]", ")", "option", "=", "None", "alternative_names", ".", "insert", "(", "0", ",", "config_name", ")", "for", "key", "in", "alternative_names", ":", "if", "configs", ".", "has_option", "(", "'settings'", ",", "key", ")", ":", "option", "=", "configs", ".", "get", "(", "'settings'", ",", "key", ")", "break", "if", "option", "is", "not", "None", ":", "if", "option", ".", "strip", "(", ")", ".", "lower", "(", ")", "==", "'true'", ":", "setattr", "(", "args", ",", "config_name", ",", "[", "'.*'", "]", ")", "elif", "option", ".", "strip", "(", ")", ".", "lower", "(", ")", "!=", "'false'", ":", "for", "pattern", "in", "option", ".", "split", "(", "\"\\n\"", ")", ":", "if", "pattern", ".", "strip", "(", ")", "!=", "''", ":", "getattr", "(", "args", ",", "config_name", ")", ".", "append", "(", "pattern", ")" ]
Get a boolean or list of regexes from args and configs.
[ "Get", "a", "boolean", "or", "list", "of", "regexes", "from", "args", "and", "configs", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/arguments.py#L340-L364
train
wakatime/wakatime
wakatime/packages/pygments/formatters/latex.py
LatexFormatter.get_style_defs
def get_style_defs(self, arg=''): """ Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored. """ cp = self.commandprefix styles = [] for name, definition in iteritems(self.cmd2def): styles.append(r'\expandafter\def\csname %s@tok@%s\endcsname{%s}' % (cp, name, definition)) return STYLE_TEMPLATE % {'cp': self.commandprefix, 'styles': '\n'.join(styles)}
python
def get_style_defs(self, arg=''): """ Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored. """ cp = self.commandprefix styles = [] for name, definition in iteritems(self.cmd2def): styles.append(r'\expandafter\def\csname %s@tok@%s\endcsname{%s}' % (cp, name, definition)) return STYLE_TEMPLATE % {'cp': self.commandprefix, 'styles': '\n'.join(styles)}
[ "def", "get_style_defs", "(", "self", ",", "arg", "=", "''", ")", ":", "cp", "=", "self", ".", "commandprefix", "styles", "=", "[", "]", "for", "name", ",", "definition", "in", "iteritems", "(", "self", ".", "cmd2def", ")", ":", "styles", ".", "append", "(", "r'\\expandafter\\def\\csname %s@tok@%s\\endcsname{%s}'", "%", "(", "cp", ",", "name", ",", "definition", ")", ")", "return", "STYLE_TEMPLATE", "%", "{", "'cp'", ":", "self", ".", "commandprefix", ",", "'styles'", ":", "'\\n'", ".", "join", "(", "styles", ")", "}" ]
Return the command sequences needed to define the commands used to format text in the verbatim environment. ``arg`` is ignored.
[ "Return", "the", "command", "sequences", "needed", "to", "define", "the", "commands", "used", "to", "format", "text", "in", "the", "verbatim", "environment", ".", "arg", "is", "ignored", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/latex.py#L318-L329
train
wakatime/wakatime
wakatime/packages/pygments/formatters/__init__.py
_fn_matches
def _fn_matches(fn, glob): """Return whether the supplied file name fn matches pattern filename.""" if glob not in _pattern_cache: pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob)) return pattern.match(fn) return _pattern_cache[glob].match(fn)
python
def _fn_matches(fn, glob): """Return whether the supplied file name fn matches pattern filename.""" if glob not in _pattern_cache: pattern = _pattern_cache[glob] = re.compile(fnmatch.translate(glob)) return pattern.match(fn) return _pattern_cache[glob].match(fn)
[ "def", "_fn_matches", "(", "fn", ",", "glob", ")", ":", "if", "glob", "not", "in", "_pattern_cache", ":", "pattern", "=", "_pattern_cache", "[", "glob", "]", "=", "re", ".", "compile", "(", "fnmatch", ".", "translate", "(", "glob", ")", ")", "return", "pattern", ".", "match", "(", "fn", ")", "return", "_pattern_cache", "[", "glob", "]", ".", "match", "(", "fn", ")" ]
Return whether the supplied file name fn matches pattern filename.
[ "Return", "whether", "the", "supplied", "file", "name", "fn", "matches", "pattern", "filename", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/__init__.py#L29-L34
train
wakatime/wakatime
wakatime/packages/pygments/formatters/__init__.py
get_all_formatters
def get_all_formatters(): """Return a generator for all formatter classes.""" # NB: this returns formatter classes, not info like get_all_lexers(). for info in itervalues(FORMATTERS): if info[1] not in _formatter_cache: _load_formatters(info[0]) yield _formatter_cache[info[1]] for _, formatter in find_plugin_formatters(): yield formatter
python
def get_all_formatters(): """Return a generator for all formatter classes.""" # NB: this returns formatter classes, not info like get_all_lexers(). for info in itervalues(FORMATTERS): if info[1] not in _formatter_cache: _load_formatters(info[0]) yield _formatter_cache[info[1]] for _, formatter in find_plugin_formatters(): yield formatter
[ "def", "get_all_formatters", "(", ")", ":", "# NB: this returns formatter classes, not info like get_all_lexers().", "for", "info", "in", "itervalues", "(", "FORMATTERS", ")", ":", "if", "info", "[", "1", "]", "not", "in", "_formatter_cache", ":", "_load_formatters", "(", "info", "[", "0", "]", ")", "yield", "_formatter_cache", "[", "info", "[", "1", "]", "]", "for", "_", ",", "formatter", "in", "find_plugin_formatters", "(", ")", ":", "yield", "formatter" ]
Return a generator for all formatter classes.
[ "Return", "a", "generator", "for", "all", "formatter", "classes", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/__init__.py#L45-L53
train
wakatime/wakatime
wakatime/packages/pygments/formatters/__init__.py
find_formatter_class
def find_formatter_class(alias): """Lookup a formatter by alias. Returns None if not found. """ for module_name, name, aliases, _, _ in itervalues(FORMATTERS): if alias in aliases: if name not in _formatter_cache: _load_formatters(module_name) return _formatter_cache[name] for _, cls in find_plugin_formatters(): if alias in cls.aliases: return cls
python
def find_formatter_class(alias): """Lookup a formatter by alias. Returns None if not found. """ for module_name, name, aliases, _, _ in itervalues(FORMATTERS): if alias in aliases: if name not in _formatter_cache: _load_formatters(module_name) return _formatter_cache[name] for _, cls in find_plugin_formatters(): if alias in cls.aliases: return cls
[ "def", "find_formatter_class", "(", "alias", ")", ":", "for", "module_name", ",", "name", ",", "aliases", ",", "_", ",", "_", "in", "itervalues", "(", "FORMATTERS", ")", ":", "if", "alias", "in", "aliases", ":", "if", "name", "not", "in", "_formatter_cache", ":", "_load_formatters", "(", "module_name", ")", "return", "_formatter_cache", "[", "name", "]", "for", "_", ",", "cls", "in", "find_plugin_formatters", "(", ")", ":", "if", "alias", "in", "cls", ".", "aliases", ":", "return", "cls" ]
Lookup a formatter by alias. Returns None if not found.
[ "Lookup", "a", "formatter", "by", "alias", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/__init__.py#L56-L68
train
wakatime/wakatime
wakatime/packages/pygments/formatters/__init__.py
get_formatter_by_name
def get_formatter_by_name(_alias, **options): """Lookup and instantiate a formatter by alias. Raises ClassNotFound if not found. """ cls = find_formatter_class(_alias) if cls is None: raise ClassNotFound("no formatter found for name %r" % _alias) return cls(**options)
python
def get_formatter_by_name(_alias, **options): """Lookup and instantiate a formatter by alias. Raises ClassNotFound if not found. """ cls = find_formatter_class(_alias) if cls is None: raise ClassNotFound("no formatter found for name %r" % _alias) return cls(**options)
[ "def", "get_formatter_by_name", "(", "_alias", ",", "*", "*", "options", ")", ":", "cls", "=", "find_formatter_class", "(", "_alias", ")", "if", "cls", "is", "None", ":", "raise", "ClassNotFound", "(", "\"no formatter found for name %r\"", "%", "_alias", ")", "return", "cls", "(", "*", "*", "options", ")" ]
Lookup and instantiate a formatter by alias. Raises ClassNotFound if not found.
[ "Lookup", "and", "instantiate", "a", "formatter", "by", "alias", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/__init__.py#L71-L79
train
wakatime/wakatime
wakatime/packages/pygments/formatters/__init__.py
load_formatter_from_file
def load_formatter_from_file(filename, formattername="CustomFormatter", **options): """Load a formatter from a file. This method expects a file located relative to the current working directory, which contains a class named CustomFormatter. By default, it expects the Formatter to be named CustomFormatter; you can specify your own class name as the second argument to this function. Users should be very careful with the input, because this method is equivalent to running eval on the input file. Raises ClassNotFound if there are any problems importing the Formatter. .. versionadded:: 2.2 """ try: # This empty dict will contain the namespace for the exec'd file custom_namespace = {} exec(open(filename, 'rb').read(), custom_namespace) # Retrieve the class `formattername` from that namespace if formattername not in custom_namespace: raise ClassNotFound('no valid %s class found in %s' % (formattername, filename)) formatter_class = custom_namespace[formattername] # And finally instantiate it with the options return formatter_class(**options) except IOError as err: raise ClassNotFound('cannot read %s' % filename) except ClassNotFound as err: raise except Exception as err: raise ClassNotFound('error when loading custom formatter: %s' % err)
python
def load_formatter_from_file(filename, formattername="CustomFormatter", **options): """Load a formatter from a file. This method expects a file located relative to the current working directory, which contains a class named CustomFormatter. By default, it expects the Formatter to be named CustomFormatter; you can specify your own class name as the second argument to this function. Users should be very careful with the input, because this method is equivalent to running eval on the input file. Raises ClassNotFound if there are any problems importing the Formatter. .. versionadded:: 2.2 """ try: # This empty dict will contain the namespace for the exec'd file custom_namespace = {} exec(open(filename, 'rb').read(), custom_namespace) # Retrieve the class `formattername` from that namespace if formattername not in custom_namespace: raise ClassNotFound('no valid %s class found in %s' % (formattername, filename)) formatter_class = custom_namespace[formattername] # And finally instantiate it with the options return formatter_class(**options) except IOError as err: raise ClassNotFound('cannot read %s' % filename) except ClassNotFound as err: raise except Exception as err: raise ClassNotFound('error when loading custom formatter: %s' % err)
[ "def", "load_formatter_from_file", "(", "filename", ",", "formattername", "=", "\"CustomFormatter\"", ",", "*", "*", "options", ")", ":", "try", ":", "# This empty dict will contain the namespace for the exec'd file", "custom_namespace", "=", "{", "}", "exec", "(", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", ")", ",", "custom_namespace", ")", "# Retrieve the class `formattername` from that namespace", "if", "formattername", "not", "in", "custom_namespace", ":", "raise", "ClassNotFound", "(", "'no valid %s class found in %s'", "%", "(", "formattername", ",", "filename", ")", ")", "formatter_class", "=", "custom_namespace", "[", "formattername", "]", "# And finally instantiate it with the options", "return", "formatter_class", "(", "*", "*", "options", ")", "except", "IOError", "as", "err", ":", "raise", "ClassNotFound", "(", "'cannot read %s'", "%", "filename", ")", "except", "ClassNotFound", "as", "err", ":", "raise", "except", "Exception", "as", "err", ":", "raise", "ClassNotFound", "(", "'error when loading custom formatter: %s'", "%", "err", ")" ]
Load a formatter from a file. This method expects a file located relative to the current working directory, which contains a class named CustomFormatter. By default, it expects the Formatter to be named CustomFormatter; you can specify your own class name as the second argument to this function. Users should be very careful with the input, because this method is equivalent to running eval on the input file. Raises ClassNotFound if there are any problems importing the Formatter. .. versionadded:: 2.2
[ "Load", "a", "formatter", "from", "a", "file", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/__init__.py#L82-L114
train
wakatime/wakatime
wakatime/packages/pygments/formatters/__init__.py
get_formatter_for_filename
def get_formatter_for_filename(fn, **options): """Lookup and instantiate a formatter by filename pattern. Raises ClassNotFound if not found. """ fn = basename(fn) for modname, name, _, filenames, _ in itervalues(FORMATTERS): for filename in filenames: if _fn_matches(fn, filename): if name not in _formatter_cache: _load_formatters(modname) return _formatter_cache[name](**options) for cls in find_plugin_formatters(): for filename in cls.filenames: if _fn_matches(fn, filename): return cls(**options) raise ClassNotFound("no formatter found for file name %r" % fn)
python
def get_formatter_for_filename(fn, **options): """Lookup and instantiate a formatter by filename pattern. Raises ClassNotFound if not found. """ fn = basename(fn) for modname, name, _, filenames, _ in itervalues(FORMATTERS): for filename in filenames: if _fn_matches(fn, filename): if name not in _formatter_cache: _load_formatters(modname) return _formatter_cache[name](**options) for cls in find_plugin_formatters(): for filename in cls.filenames: if _fn_matches(fn, filename): return cls(**options) raise ClassNotFound("no formatter found for file name %r" % fn)
[ "def", "get_formatter_for_filename", "(", "fn", ",", "*", "*", "options", ")", ":", "fn", "=", "basename", "(", "fn", ")", "for", "modname", ",", "name", ",", "_", ",", "filenames", ",", "_", "in", "itervalues", "(", "FORMATTERS", ")", ":", "for", "filename", "in", "filenames", ":", "if", "_fn_matches", "(", "fn", ",", "filename", ")", ":", "if", "name", "not", "in", "_formatter_cache", ":", "_load_formatters", "(", "modname", ")", "return", "_formatter_cache", "[", "name", "]", "(", "*", "*", "options", ")", "for", "cls", "in", "find_plugin_formatters", "(", ")", ":", "for", "filename", "in", "cls", ".", "filenames", ":", "if", "_fn_matches", "(", "fn", ",", "filename", ")", ":", "return", "cls", "(", "*", "*", "options", ")", "raise", "ClassNotFound", "(", "\"no formatter found for file name %r\"", "%", "fn", ")" ]
Lookup and instantiate a formatter by filename pattern. Raises ClassNotFound if not found.
[ "Lookup", "and", "instantiate", "a", "formatter", "by", "filename", "pattern", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/__init__.py#L117-L133
train
wakatime/wakatime
wakatime/packages/pygments/lexers/textfmts.py
HttpLexer.get_tokens_unprocessed
def get_tokens_unprocessed(self, text, stack=('root',)): """Reset the content-type state.""" self.content_type = None return RegexLexer.get_tokens_unprocessed(self, text, stack)
python
def get_tokens_unprocessed(self, text, stack=('root',)): """Reset the content-type state.""" self.content_type = None return RegexLexer.get_tokens_unprocessed(self, text, stack)
[ "def", "get_tokens_unprocessed", "(", "self", ",", "text", ",", "stack", "=", "(", "'root'", ",", ")", ")", ":", "self", ".", "content_type", "=", "None", "return", "RegexLexer", ".", "get_tokens_unprocessed", "(", "self", ",", "text", ",", "stack", ")" ]
Reset the content-type state.
[ "Reset", "the", "content", "-", "type", "state", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/textfmts.py#L125-L128
train
wakatime/wakatime
wakatime/packages/pygments/lexers/__init__.py
find_lexer_class
def find_lexer_class(name): """Lookup a lexer class by name. Return None if not found. """ if name in _lexer_cache: return _lexer_cache[name] # lookup builtin lexers for module_name, lname, aliases, _, _ in itervalues(LEXERS): if name == lname: _load_lexers(module_name) return _lexer_cache[name] # continue with lexers from setuptools entrypoints for cls in find_plugin_lexers(): if cls.name == name: return cls
python
def find_lexer_class(name): """Lookup a lexer class by name. Return None if not found. """ if name in _lexer_cache: return _lexer_cache[name] # lookup builtin lexers for module_name, lname, aliases, _, _ in itervalues(LEXERS): if name == lname: _load_lexers(module_name) return _lexer_cache[name] # continue with lexers from setuptools entrypoints for cls in find_plugin_lexers(): if cls.name == name: return cls
[ "def", "find_lexer_class", "(", "name", ")", ":", "if", "name", "in", "_lexer_cache", ":", "return", "_lexer_cache", "[", "name", "]", "# lookup builtin lexers", "for", "module_name", ",", "lname", ",", "aliases", ",", "_", ",", "_", "in", "itervalues", "(", "LEXERS", ")", ":", "if", "name", "==", "lname", ":", "_load_lexers", "(", "module_name", ")", "return", "_lexer_cache", "[", "name", "]", "# continue with lexers from setuptools entrypoints", "for", "cls", "in", "find_plugin_lexers", "(", ")", ":", "if", "cls", ".", "name", "==", "name", ":", "return", "cls" ]
Lookup a lexer class by name. Return None if not found.
[ "Lookup", "a", "lexer", "class", "by", "name", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/__init__.py#L57-L72
train
wakatime/wakatime
wakatime/packages/pygments/lexers/__init__.py
find_lexer_class_by_name
def find_lexer_class_by_name(_alias): """Lookup a lexer class by alias. Like `get_lexer_by_name`, but does not instantiate the class. .. versionadded:: 2.2 """ if not _alias: raise ClassNotFound('no lexer for alias %r found' % _alias) # lookup builtin lexers for module_name, name, aliases, _, _ in itervalues(LEXERS): if _alias.lower() in aliases: if name not in _lexer_cache: _load_lexers(module_name) return _lexer_cache[name] # continue with lexers from setuptools entrypoints for cls in find_plugin_lexers(): if _alias.lower() in cls.aliases: return cls raise ClassNotFound('no lexer for alias %r found' % _alias)
python
def find_lexer_class_by_name(_alias): """Lookup a lexer class by alias. Like `get_lexer_by_name`, but does not instantiate the class. .. versionadded:: 2.2 """ if not _alias: raise ClassNotFound('no lexer for alias %r found' % _alias) # lookup builtin lexers for module_name, name, aliases, _, _ in itervalues(LEXERS): if _alias.lower() in aliases: if name not in _lexer_cache: _load_lexers(module_name) return _lexer_cache[name] # continue with lexers from setuptools entrypoints for cls in find_plugin_lexers(): if _alias.lower() in cls.aliases: return cls raise ClassNotFound('no lexer for alias %r found' % _alias)
[ "def", "find_lexer_class_by_name", "(", "_alias", ")", ":", "if", "not", "_alias", ":", "raise", "ClassNotFound", "(", "'no lexer for alias %r found'", "%", "_alias", ")", "# lookup builtin lexers", "for", "module_name", ",", "name", ",", "aliases", ",", "_", ",", "_", "in", "itervalues", "(", "LEXERS", ")", ":", "if", "_alias", ".", "lower", "(", ")", "in", "aliases", ":", "if", "name", "not", "in", "_lexer_cache", ":", "_load_lexers", "(", "module_name", ")", "return", "_lexer_cache", "[", "name", "]", "# continue with lexers from setuptools entrypoints", "for", "cls", "in", "find_plugin_lexers", "(", ")", ":", "if", "_alias", ".", "lower", "(", ")", "in", "cls", ".", "aliases", ":", "return", "cls", "raise", "ClassNotFound", "(", "'no lexer for alias %r found'", "%", "_alias", ")" ]
Lookup a lexer class by alias. Like `get_lexer_by_name`, but does not instantiate the class. .. versionadded:: 2.2
[ "Lookup", "a", "lexer", "class", "by", "alias", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/__init__.py#L75-L94
train
wakatime/wakatime
wakatime/packages/pygments/lexers/__init__.py
load_lexer_from_file
def load_lexer_from_file(filename, lexername="CustomLexer", **options): """Load a lexer from a file. This method expects a file located relative to the current working directory, which contains a Lexer class. By default, it expects the Lexer to be name CustomLexer; you can specify your own class name as the second argument to this function. Users should be very careful with the input, because this method is equivalent to running eval on the input file. Raises ClassNotFound if there are any problems importing the Lexer. .. versionadded:: 2.2 """ try: # This empty dict will contain the namespace for the exec'd file custom_namespace = {} exec(open(filename, 'rb').read(), custom_namespace) # Retrieve the class `lexername` from that namespace if lexername not in custom_namespace: raise ClassNotFound('no valid %s class found in %s' % (lexername, filename)) lexer_class = custom_namespace[lexername] # And finally instantiate it with the options return lexer_class(**options) except IOError as err: raise ClassNotFound('cannot read %s' % filename) except ClassNotFound as err: raise except Exception as err: raise ClassNotFound('error when loading custom lexer: %s' % err)
python
def load_lexer_from_file(filename, lexername="CustomLexer", **options): """Load a lexer from a file. This method expects a file located relative to the current working directory, which contains a Lexer class. By default, it expects the Lexer to be name CustomLexer; you can specify your own class name as the second argument to this function. Users should be very careful with the input, because this method is equivalent to running eval on the input file. Raises ClassNotFound if there are any problems importing the Lexer. .. versionadded:: 2.2 """ try: # This empty dict will contain the namespace for the exec'd file custom_namespace = {} exec(open(filename, 'rb').read(), custom_namespace) # Retrieve the class `lexername` from that namespace if lexername not in custom_namespace: raise ClassNotFound('no valid %s class found in %s' % (lexername, filename)) lexer_class = custom_namespace[lexername] # And finally instantiate it with the options return lexer_class(**options) except IOError as err: raise ClassNotFound('cannot read %s' % filename) except ClassNotFound as err: raise except Exception as err: raise ClassNotFound('error when loading custom lexer: %s' % err)
[ "def", "load_lexer_from_file", "(", "filename", ",", "lexername", "=", "\"CustomLexer\"", ",", "*", "*", "options", ")", ":", "try", ":", "# This empty dict will contain the namespace for the exec'd file", "custom_namespace", "=", "{", "}", "exec", "(", "open", "(", "filename", ",", "'rb'", ")", ".", "read", "(", ")", ",", "custom_namespace", ")", "# Retrieve the class `lexername` from that namespace", "if", "lexername", "not", "in", "custom_namespace", ":", "raise", "ClassNotFound", "(", "'no valid %s class found in %s'", "%", "(", "lexername", ",", "filename", ")", ")", "lexer_class", "=", "custom_namespace", "[", "lexername", "]", "# And finally instantiate it with the options", "return", "lexer_class", "(", "*", "*", "options", ")", "except", "IOError", "as", "err", ":", "raise", "ClassNotFound", "(", "'cannot read %s'", "%", "filename", ")", "except", "ClassNotFound", "as", "err", ":", "raise", "except", "Exception", "as", "err", ":", "raise", "ClassNotFound", "(", "'error when loading custom lexer: %s'", "%", "err", ")" ]
Load a lexer from a file. This method expects a file located relative to the current working directory, which contains a Lexer class. By default, it expects the Lexer to be name CustomLexer; you can specify your own class name as the second argument to this function. Users should be very careful with the input, because this method is equivalent to running eval on the input file. Raises ClassNotFound if there are any problems importing the Lexer. .. versionadded:: 2.2
[ "Load", "a", "lexer", "from", "a", "file", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/__init__.py#L118-L149
train
wakatime/wakatime
wakatime/packages/pygments/lexers/__init__.py
get_lexer_for_mimetype
def get_lexer_for_mimetype(_mime, **options): """Get a lexer for a mimetype. Raises ClassNotFound if not found. """ for modname, name, _, _, mimetypes in itervalues(LEXERS): if _mime in mimetypes: if name not in _lexer_cache: _load_lexers(modname) return _lexer_cache[name](**options) for cls in find_plugin_lexers(): if _mime in cls.mimetypes: return cls(**options) raise ClassNotFound('no lexer for mimetype %r found' % _mime)
python
def get_lexer_for_mimetype(_mime, **options): """Get a lexer for a mimetype. Raises ClassNotFound if not found. """ for modname, name, _, _, mimetypes in itervalues(LEXERS): if _mime in mimetypes: if name not in _lexer_cache: _load_lexers(modname) return _lexer_cache[name](**options) for cls in find_plugin_lexers(): if _mime in cls.mimetypes: return cls(**options) raise ClassNotFound('no lexer for mimetype %r found' % _mime)
[ "def", "get_lexer_for_mimetype", "(", "_mime", ",", "*", "*", "options", ")", ":", "for", "modname", ",", "name", ",", "_", ",", "_", ",", "mimetypes", "in", "itervalues", "(", "LEXERS", ")", ":", "if", "_mime", "in", "mimetypes", ":", "if", "name", "not", "in", "_lexer_cache", ":", "_load_lexers", "(", "modname", ")", "return", "_lexer_cache", "[", "name", "]", "(", "*", "*", "options", ")", "for", "cls", "in", "find_plugin_lexers", "(", ")", ":", "if", "_mime", "in", "cls", ".", "mimetypes", ":", "return", "cls", "(", "*", "*", "options", ")", "raise", "ClassNotFound", "(", "'no lexer for mimetype %r found'", "%", "_mime", ")" ]
Get a lexer for a mimetype. Raises ClassNotFound if not found.
[ "Get", "a", "lexer", "for", "a", "mimetype", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/__init__.py#L209-L222
train
wakatime/wakatime
wakatime/packages/pygments/lexers/__init__.py
_iter_lexerclasses
def _iter_lexerclasses(plugins=True): """Return an iterator over all lexer classes.""" for key in sorted(LEXERS): module_name, name = LEXERS[key][:2] if name not in _lexer_cache: _load_lexers(module_name) yield _lexer_cache[name] if plugins: for lexer in find_plugin_lexers(): yield lexer
python
def _iter_lexerclasses(plugins=True): """Return an iterator over all lexer classes.""" for key in sorted(LEXERS): module_name, name = LEXERS[key][:2] if name not in _lexer_cache: _load_lexers(module_name) yield _lexer_cache[name] if plugins: for lexer in find_plugin_lexers(): yield lexer
[ "def", "_iter_lexerclasses", "(", "plugins", "=", "True", ")", ":", "for", "key", "in", "sorted", "(", "LEXERS", ")", ":", "module_name", ",", "name", "=", "LEXERS", "[", "key", "]", "[", ":", "2", "]", "if", "name", "not", "in", "_lexer_cache", ":", "_load_lexers", "(", "module_name", ")", "yield", "_lexer_cache", "[", "name", "]", "if", "plugins", ":", "for", "lexer", "in", "find_plugin_lexers", "(", ")", ":", "yield", "lexer" ]
Return an iterator over all lexer classes.
[ "Return", "an", "iterator", "over", "all", "lexer", "classes", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/__init__.py#L225-L234
train
wakatime/wakatime
wakatime/stats.py
get_file_stats
def get_file_stats(file_name, entity_type='file', lineno=None, cursorpos=None, plugin=None, language=None, local_file=None): """Returns a hash of information about the entity.""" language = standardize_language(language, plugin) stats = { 'language': language, 'dependencies': [], 'lines': None, 'lineno': lineno, 'cursorpos': cursorpos, } if entity_type == 'file': lexer = get_lexer(language) if not language: language, lexer = guess_language(file_name, local_file) parser = DependencyParser(local_file or file_name, lexer) stats.update({ 'language': use_root_language(language, lexer), 'dependencies': parser.parse(), 'lines': number_lines_in_file(local_file or file_name), }) return stats
python
def get_file_stats(file_name, entity_type='file', lineno=None, cursorpos=None, plugin=None, language=None, local_file=None): """Returns a hash of information about the entity.""" language = standardize_language(language, plugin) stats = { 'language': language, 'dependencies': [], 'lines': None, 'lineno': lineno, 'cursorpos': cursorpos, } if entity_type == 'file': lexer = get_lexer(language) if not language: language, lexer = guess_language(file_name, local_file) parser = DependencyParser(local_file or file_name, lexer) stats.update({ 'language': use_root_language(language, lexer), 'dependencies': parser.parse(), 'lines': number_lines_in_file(local_file or file_name), }) return stats
[ "def", "get_file_stats", "(", "file_name", ",", "entity_type", "=", "'file'", ",", "lineno", "=", "None", ",", "cursorpos", "=", "None", ",", "plugin", "=", "None", ",", "language", "=", "None", ",", "local_file", "=", "None", ")", ":", "language", "=", "standardize_language", "(", "language", ",", "plugin", ")", "stats", "=", "{", "'language'", ":", "language", ",", "'dependencies'", ":", "[", "]", ",", "'lines'", ":", "None", ",", "'lineno'", ":", "lineno", ",", "'cursorpos'", ":", "cursorpos", ",", "}", "if", "entity_type", "==", "'file'", ":", "lexer", "=", "get_lexer", "(", "language", ")", "if", "not", "language", ":", "language", ",", "lexer", "=", "guess_language", "(", "file_name", ",", "local_file", ")", "parser", "=", "DependencyParser", "(", "local_file", "or", "file_name", ",", "lexer", ")", "stats", ".", "update", "(", "{", "'language'", ":", "use_root_language", "(", "language", ",", "lexer", ")", ",", "'dependencies'", ":", "parser", ".", "parse", "(", ")", ",", "'lines'", ":", "number_lines_in_file", "(", "local_file", "or", "file_name", ")", ",", "}", ")", "return", "stats" ]
Returns a hash of information about the entity.
[ "Returns", "a", "hash", "of", "information", "about", "the", "entity", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L43-L67
train
wakatime/wakatime
wakatime/stats.py
guess_language
def guess_language(file_name, local_file): """Guess lexer and language for a file. Returns a tuple of (language_str, lexer_obj). """ lexer = None language = get_language_from_extension(file_name) if language: lexer = get_lexer(language) else: lexer = smart_guess_lexer(file_name, local_file) if lexer: language = u(lexer.name) return language, lexer
python
def guess_language(file_name, local_file): """Guess lexer and language for a file. Returns a tuple of (language_str, lexer_obj). """ lexer = None language = get_language_from_extension(file_name) if language: lexer = get_lexer(language) else: lexer = smart_guess_lexer(file_name, local_file) if lexer: language = u(lexer.name) return language, lexer
[ "def", "guess_language", "(", "file_name", ",", "local_file", ")", ":", "lexer", "=", "None", "language", "=", "get_language_from_extension", "(", "file_name", ")", "if", "language", ":", "lexer", "=", "get_lexer", "(", "language", ")", "else", ":", "lexer", "=", "smart_guess_lexer", "(", "file_name", ",", "local_file", ")", "if", "lexer", ":", "language", "=", "u", "(", "lexer", ".", "name", ")", "return", "language", ",", "lexer" ]
Guess lexer and language for a file. Returns a tuple of (language_str, lexer_obj).
[ "Guess", "lexer", "and", "language", "for", "a", "file", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L70-L86
train
wakatime/wakatime
wakatime/stats.py
smart_guess_lexer
def smart_guess_lexer(file_name, local_file): """Guess Pygments lexer for a file. Looks for a vim modeline in file contents, then compares the accuracy of that lexer with a second guess. The second guess looks up all lexers matching the file name, then runs a text analysis for the best choice. """ lexer = None text = get_file_head(file_name) lexer1, accuracy1 = guess_lexer_using_filename(local_file or file_name, text) lexer2, accuracy2 = guess_lexer_using_modeline(text) if lexer1: lexer = lexer1 if (lexer2 and accuracy2 and (not accuracy1 or accuracy2 > accuracy1)): lexer = lexer2 return lexer
python
def smart_guess_lexer(file_name, local_file): """Guess Pygments lexer for a file. Looks for a vim modeline in file contents, then compares the accuracy of that lexer with a second guess. The second guess looks up all lexers matching the file name, then runs a text analysis for the best choice. """ lexer = None text = get_file_head(file_name) lexer1, accuracy1 = guess_lexer_using_filename(local_file or file_name, text) lexer2, accuracy2 = guess_lexer_using_modeline(text) if lexer1: lexer = lexer1 if (lexer2 and accuracy2 and (not accuracy1 or accuracy2 > accuracy1)): lexer = lexer2 return lexer
[ "def", "smart_guess_lexer", "(", "file_name", ",", "local_file", ")", ":", "lexer", "=", "None", "text", "=", "get_file_head", "(", "file_name", ")", "lexer1", ",", "accuracy1", "=", "guess_lexer_using_filename", "(", "local_file", "or", "file_name", ",", "text", ")", "lexer2", ",", "accuracy2", "=", "guess_lexer_using_modeline", "(", "text", ")", "if", "lexer1", ":", "lexer", "=", "lexer1", "if", "(", "lexer2", "and", "accuracy2", "and", "(", "not", "accuracy1", "or", "accuracy2", ">", "accuracy1", ")", ")", ":", "lexer", "=", "lexer2", "return", "lexer" ]
Guess Pygments lexer for a file. Looks for a vim modeline in file contents, then compares the accuracy of that lexer with a second guess. The second guess looks up all lexers matching the file name, then runs a text analysis for the best choice.
[ "Guess", "Pygments", "lexer", "for", "a", "file", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L89-L109
train
wakatime/wakatime
wakatime/stats.py
guess_lexer_using_filename
def guess_lexer_using_filename(file_name, text): """Guess lexer for given text, limited to lexers for this file's extension. Returns a tuple of (lexer, accuracy). """ lexer, accuracy = None, None try: lexer = custom_pygments_guess_lexer_for_filename(file_name, text) except SkipHeartbeat as ex: raise SkipHeartbeat(u(ex)) except: log.traceback(logging.DEBUG) if lexer is not None: try: accuracy = lexer.analyse_text(text) except: log.traceback(logging.DEBUG) return lexer, accuracy
python
def guess_lexer_using_filename(file_name, text): """Guess lexer for given text, limited to lexers for this file's extension. Returns a tuple of (lexer, accuracy). """ lexer, accuracy = None, None try: lexer = custom_pygments_guess_lexer_for_filename(file_name, text) except SkipHeartbeat as ex: raise SkipHeartbeat(u(ex)) except: log.traceback(logging.DEBUG) if lexer is not None: try: accuracy = lexer.analyse_text(text) except: log.traceback(logging.DEBUG) return lexer, accuracy
[ "def", "guess_lexer_using_filename", "(", "file_name", ",", "text", ")", ":", "lexer", ",", "accuracy", "=", "None", ",", "None", "try", ":", "lexer", "=", "custom_pygments_guess_lexer_for_filename", "(", "file_name", ",", "text", ")", "except", "SkipHeartbeat", "as", "ex", ":", "raise", "SkipHeartbeat", "(", "u", "(", "ex", ")", ")", "except", ":", "log", ".", "traceback", "(", "logging", ".", "DEBUG", ")", "if", "lexer", "is", "not", "None", ":", "try", ":", "accuracy", "=", "lexer", ".", "analyse_text", "(", "text", ")", "except", ":", "log", ".", "traceback", "(", "logging", ".", "DEBUG", ")", "return", "lexer", ",", "accuracy" ]
Guess lexer for given text, limited to lexers for this file's extension. Returns a tuple of (lexer, accuracy).
[ "Guess", "lexer", "for", "given", "text", "limited", "to", "lexers", "for", "this", "file", "s", "extension", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L112-L133
train
wakatime/wakatime
wakatime/stats.py
guess_lexer_using_modeline
def guess_lexer_using_modeline(text): """Guess lexer for given text using Vim modeline. Returns a tuple of (lexer, accuracy). """ lexer, accuracy = None, None file_type = None try: file_type = get_filetype_from_buffer(text) except: # pragma: nocover log.traceback(logging.DEBUG) if file_type is not None: try: lexer = get_lexer_by_name(file_type) except ClassNotFound: log.traceback(logging.DEBUG) if lexer is not None: try: accuracy = lexer.analyse_text(text) except: # pragma: nocover log.traceback(logging.DEBUG) return lexer, accuracy
python
def guess_lexer_using_modeline(text): """Guess lexer for given text using Vim modeline. Returns a tuple of (lexer, accuracy). """ lexer, accuracy = None, None file_type = None try: file_type = get_filetype_from_buffer(text) except: # pragma: nocover log.traceback(logging.DEBUG) if file_type is not None: try: lexer = get_lexer_by_name(file_type) except ClassNotFound: log.traceback(logging.DEBUG) if lexer is not None: try: accuracy = lexer.analyse_text(text) except: # pragma: nocover log.traceback(logging.DEBUG) return lexer, accuracy
[ "def", "guess_lexer_using_modeline", "(", "text", ")", ":", "lexer", ",", "accuracy", "=", "None", ",", "None", "file_type", "=", "None", "try", ":", "file_type", "=", "get_filetype_from_buffer", "(", "text", ")", "except", ":", "# pragma: nocover", "log", ".", "traceback", "(", "logging", ".", "DEBUG", ")", "if", "file_type", "is", "not", "None", ":", "try", ":", "lexer", "=", "get_lexer_by_name", "(", "file_type", ")", "except", "ClassNotFound", ":", "log", ".", "traceback", "(", "logging", ".", "DEBUG", ")", "if", "lexer", "is", "not", "None", ":", "try", ":", "accuracy", "=", "lexer", ".", "analyse_text", "(", "text", ")", "except", ":", "# pragma: nocover", "log", ".", "traceback", "(", "logging", ".", "DEBUG", ")", "return", "lexer", ",", "accuracy" ]
Guess lexer for given text using Vim modeline. Returns a tuple of (lexer, accuracy).
[ "Guess", "lexer", "for", "given", "text", "using", "Vim", "modeline", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L136-L162
train
wakatime/wakatime
wakatime/stats.py
get_language_from_extension
def get_language_from_extension(file_name): """Returns a matching language for the given file extension. When guessed_language is 'C', does not restrict to known file extensions. """ filepart, extension = os.path.splitext(file_name) pathpart, filename = os.path.split(file_name) if filename == 'go.mod': return 'Go' if re.match(r'\.h.*$', extension, re.IGNORECASE) or re.match(r'\.c.*$', extension, re.IGNORECASE): if os.path.exists(u('{0}{1}').format(u(filepart), u('.c'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.C'))): return 'C' if os.path.exists(u('{0}{1}').format(u(filepart), u('.m'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.M'))): return 'Objective-C' if os.path.exists(u('{0}{1}').format(u(filepart), u('.mm'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.MM'))): return 'Objective-C++' available_extensions = extensions_in_same_folder(file_name) for ext in CppLexer.filenames: ext = ext.lstrip('*') if ext in available_extensions: return 'C++' if '.c' in available_extensions: return 'C' if re.match(r'\.m$', extension, re.IGNORECASE) and (os.path.exists(u('{0}{1}').format(u(filepart), u('.h'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.H')))): return 'Objective-C' if re.match(r'\.mm$', extension, re.IGNORECASE) and (os.path.exists(u('{0}{1}').format(u(filepart), u('.h'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.H')))): return 'Objective-C++' return None
python
def get_language_from_extension(file_name): """Returns a matching language for the given file extension. When guessed_language is 'C', does not restrict to known file extensions. """ filepart, extension = os.path.splitext(file_name) pathpart, filename = os.path.split(file_name) if filename == 'go.mod': return 'Go' if re.match(r'\.h.*$', extension, re.IGNORECASE) or re.match(r'\.c.*$', extension, re.IGNORECASE): if os.path.exists(u('{0}{1}').format(u(filepart), u('.c'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.C'))): return 'C' if os.path.exists(u('{0}{1}').format(u(filepart), u('.m'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.M'))): return 'Objective-C' if os.path.exists(u('{0}{1}').format(u(filepart), u('.mm'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.MM'))): return 'Objective-C++' available_extensions = extensions_in_same_folder(file_name) for ext in CppLexer.filenames: ext = ext.lstrip('*') if ext in available_extensions: return 'C++' if '.c' in available_extensions: return 'C' if re.match(r'\.m$', extension, re.IGNORECASE) and (os.path.exists(u('{0}{1}').format(u(filepart), u('.h'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.H')))): return 'Objective-C' if re.match(r'\.mm$', extension, re.IGNORECASE) and (os.path.exists(u('{0}{1}').format(u(filepart), u('.h'))) or os.path.exists(u('{0}{1}').format(u(filepart), u('.H')))): return 'Objective-C++' return None
[ "def", "get_language_from_extension", "(", "file_name", ")", ":", "filepart", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "file_name", ")", "pathpart", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "file_name", ")", "if", "filename", "==", "'go.mod'", ":", "return", "'Go'", "if", "re", ".", "match", "(", "r'\\.h.*$'", ",", "extension", ",", "re", ".", "IGNORECASE", ")", "or", "re", ".", "match", "(", "r'\\.c.*$'", ",", "extension", ",", "re", ".", "IGNORECASE", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.c'", ")", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.C'", ")", ")", ")", ":", "return", "'C'", "if", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.m'", ")", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.M'", ")", ")", ")", ":", "return", "'Objective-C'", "if", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.mm'", ")", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.MM'", ")", ")", ")", ":", "return", "'Objective-C++'", "available_extensions", "=", "extensions_in_same_folder", "(", "file_name", ")", "for", "ext", "in", "CppLexer", ".", "filenames", ":", "ext", "=", "ext", ".", "lstrip", "(", "'*'", ")", "if", "ext", "in", "available_extensions", ":", "return", "'C++'", "if", "'.c'", "in", "available_extensions", ":", "return", "'C'", "if", "re", ".", "match", "(", "r'\\.m$'", ",", "extension", ",", "re", ".", "IGNORECASE", ")", "and", "(", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.h'", ")", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.H'", ")", ")", ")", ")", ":", "return", "'Objective-C'", "if", "re", ".", "match", "(", "r'\\.mm$'", ",", "extension", ",", "re", ".", "IGNORECASE", ")", "and", "(", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.h'", ")", ")", ")", "or", "os", ".", "path", ".", "exists", "(", "u", "(", "'{0}{1}'", ")", ".", "format", "(", "u", "(", "filepart", ")", ",", "u", "(", "'.H'", ")", ")", ")", ")", ":", "return", "'Objective-C++'", "return", "None" ]
Returns a matching language for the given file extension. When guessed_language is 'C', does not restrict to known file extensions.
[ "Returns", "a", "matching", "language", "for", "the", "given", "file", "extension", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L165-L204
train
wakatime/wakatime
wakatime/stats.py
standardize_language
def standardize_language(language, plugin): """Maps a string to the equivalent Pygments language. Returns the standardized language string. """ if not language: return None # standardize language for this plugin if plugin: plugin = plugin.split(' ')[-1].split('/')[0].split('-')[0] standardized = get_language_from_json(language, plugin) if standardized is not None: return standardized # standardize language against default languages return get_language_from_json(language, 'default')
python
def standardize_language(language, plugin): """Maps a string to the equivalent Pygments language. Returns the standardized language string. """ if not language: return None # standardize language for this plugin if plugin: plugin = plugin.split(' ')[-1].split('/')[0].split('-')[0] standardized = get_language_from_json(language, plugin) if standardized is not None: return standardized # standardize language against default languages return get_language_from_json(language, 'default')
[ "def", "standardize_language", "(", "language", ",", "plugin", ")", ":", "if", "not", "language", ":", "return", "None", "# standardize language for this plugin", "if", "plugin", ":", "plugin", "=", "plugin", ".", "split", "(", "' '", ")", "[", "-", "1", "]", ".", "split", "(", "'/'", ")", "[", "0", "]", ".", "split", "(", "'-'", ")", "[", "0", "]", "standardized", "=", "get_language_from_json", "(", "language", ",", "plugin", ")", "if", "standardized", "is", "not", "None", ":", "return", "standardized", "# standardize language against default languages", "return", "get_language_from_json", "(", "language", ",", "'default'", ")" ]
Maps a string to the equivalent Pygments language. Returns the standardized language string.
[ "Maps", "a", "string", "to", "the", "equivalent", "Pygments", "language", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L228-L245
train
wakatime/wakatime
wakatime/stats.py
get_language_from_json
def get_language_from_json(language, key): """Finds the given language in a json file.""" file_name = os.path.join( os.path.dirname(__file__), 'languages', '{0}.json').format(key.lower()) if os.path.exists(file_name): try: with open(file_name, 'r', encoding='utf-8') as fh: languages = json.loads(fh.read()) if languages.get(language.lower()): return languages[language.lower()] except: log.traceback(logging.DEBUG) return None
python
def get_language_from_json(language, key): """Finds the given language in a json file.""" file_name = os.path.join( os.path.dirname(__file__), 'languages', '{0}.json').format(key.lower()) if os.path.exists(file_name): try: with open(file_name, 'r', encoding='utf-8') as fh: languages = json.loads(fh.read()) if languages.get(language.lower()): return languages[language.lower()] except: log.traceback(logging.DEBUG) return None
[ "def", "get_language_from_json", "(", "language", ",", "key", ")", ":", "file_name", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'languages'", ",", "'{0}.json'", ")", ".", "format", "(", "key", ".", "lower", "(", ")", ")", "if", "os", ".", "path", ".", "exists", "(", "file_name", ")", ":", "try", ":", "with", "open", "(", "file_name", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "fh", ":", "languages", "=", "json", ".", "loads", "(", "fh", ".", "read", "(", ")", ")", "if", "languages", ".", "get", "(", "language", ".", "lower", "(", ")", ")", ":", "return", "languages", "[", "language", ".", "lower", "(", ")", "]", "except", ":", "log", ".", "traceback", "(", "logging", ".", "DEBUG", ")", "return", "None" ]
Finds the given language in a json file.
[ "Finds", "the", "given", "language", "in", "a", "json", "file", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L268-L285
train
wakatime/wakatime
wakatime/stats.py
get_file_head
def get_file_head(file_name): """Returns the first 512000 bytes of the file's contents.""" text = None try: with open(file_name, 'r', encoding='utf-8') as fh: text = fh.read(512000) except: try: with open(file_name, 'r', encoding=sys.getfilesystemencoding()) as fh: text = fh.read(512000) # pragma: nocover except: log.traceback(logging.DEBUG) return text
python
def get_file_head(file_name): """Returns the first 512000 bytes of the file's contents.""" text = None try: with open(file_name, 'r', encoding='utf-8') as fh: text = fh.read(512000) except: try: with open(file_name, 'r', encoding=sys.getfilesystemencoding()) as fh: text = fh.read(512000) # pragma: nocover except: log.traceback(logging.DEBUG) return text
[ "def", "get_file_head", "(", "file_name", ")", ":", "text", "=", "None", "try", ":", "with", "open", "(", "file_name", ",", "'r'", ",", "encoding", "=", "'utf-8'", ")", "as", "fh", ":", "text", "=", "fh", ".", "read", "(", "512000", ")", "except", ":", "try", ":", "with", "open", "(", "file_name", ",", "'r'", ",", "encoding", "=", "sys", ".", "getfilesystemencoding", "(", ")", ")", "as", "fh", ":", "text", "=", "fh", ".", "read", "(", "512000", ")", "# pragma: nocover", "except", ":", "log", ".", "traceback", "(", "logging", ".", "DEBUG", ")", "return", "text" ]
Returns the first 512000 bytes of the file's contents.
[ "Returns", "the", "first", "512000", "bytes", "of", "the", "file", "s", "contents", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L288-L301
train
wakatime/wakatime
wakatime/stats.py
custom_pygments_guess_lexer_for_filename
def custom_pygments_guess_lexer_for_filename(_fn, _text, **options): """Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.""" fn = basename(_fn) primary = {} matching_lexers = set() for lexer in _iter_lexerclasses(): for filename in lexer.filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = True for filename in lexer.alias_filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = False if not matching_lexers: raise ClassNotFound('no lexer for filename %r found' % fn) if len(matching_lexers) == 1: return matching_lexers.pop()(**options) result = [] for lexer in matching_lexers: rv = lexer.analyse_text(_text) if rv == 1.0: return lexer(**options) result.append(customize_lexer_priority(_fn, rv, lexer)) matlab = list(filter(lambda x: x[2].name.lower() == 'matlab', result)) if len(matlab) > 0: objc = list(filter(lambda x: x[2].name.lower() == 'objective-c', result)) if objc and objc[0][0] == matlab[0][0]: raise SkipHeartbeat('Skipping because not enough language accuracy.') def type_sort(t): # sort by: # - analyse score # - is primary filename pattern? # - priority # - last resort: class name return (t[0], primary[t[2]], t[1], t[2].__name__) result.sort(key=type_sort) return result[-1][2](**options)
python
def custom_pygments_guess_lexer_for_filename(_fn, _text, **options): """Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.""" fn = basename(_fn) primary = {} matching_lexers = set() for lexer in _iter_lexerclasses(): for filename in lexer.filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = True for filename in lexer.alias_filenames: if _fn_matches(fn, filename): matching_lexers.add(lexer) primary[lexer] = False if not matching_lexers: raise ClassNotFound('no lexer for filename %r found' % fn) if len(matching_lexers) == 1: return matching_lexers.pop()(**options) result = [] for lexer in matching_lexers: rv = lexer.analyse_text(_text) if rv == 1.0: return lexer(**options) result.append(customize_lexer_priority(_fn, rv, lexer)) matlab = list(filter(lambda x: x[2].name.lower() == 'matlab', result)) if len(matlab) > 0: objc = list(filter(lambda x: x[2].name.lower() == 'objective-c', result)) if objc and objc[0][0] == matlab[0][0]: raise SkipHeartbeat('Skipping because not enough language accuracy.') def type_sort(t): # sort by: # - analyse score # - is primary filename pattern? # - priority # - last resort: class name return (t[0], primary[t[2]], t[1], t[2].__name__) result.sort(key=type_sort) return result[-1][2](**options)
[ "def", "custom_pygments_guess_lexer_for_filename", "(", "_fn", ",", "_text", ",", "*", "*", "options", ")", ":", "fn", "=", "basename", "(", "_fn", ")", "primary", "=", "{", "}", "matching_lexers", "=", "set", "(", ")", "for", "lexer", "in", "_iter_lexerclasses", "(", ")", ":", "for", "filename", "in", "lexer", ".", "filenames", ":", "if", "_fn_matches", "(", "fn", ",", "filename", ")", ":", "matching_lexers", ".", "add", "(", "lexer", ")", "primary", "[", "lexer", "]", "=", "True", "for", "filename", "in", "lexer", ".", "alias_filenames", ":", "if", "_fn_matches", "(", "fn", ",", "filename", ")", ":", "matching_lexers", ".", "add", "(", "lexer", ")", "primary", "[", "lexer", "]", "=", "False", "if", "not", "matching_lexers", ":", "raise", "ClassNotFound", "(", "'no lexer for filename %r found'", "%", "fn", ")", "if", "len", "(", "matching_lexers", ")", "==", "1", ":", "return", "matching_lexers", ".", "pop", "(", ")", "(", "*", "*", "options", ")", "result", "=", "[", "]", "for", "lexer", "in", "matching_lexers", ":", "rv", "=", "lexer", ".", "analyse_text", "(", "_text", ")", "if", "rv", "==", "1.0", ":", "return", "lexer", "(", "*", "*", "options", ")", "result", ".", "append", "(", "customize_lexer_priority", "(", "_fn", ",", "rv", ",", "lexer", ")", ")", "matlab", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "[", "2", "]", ".", "name", ".", "lower", "(", ")", "==", "'matlab'", ",", "result", ")", ")", "if", "len", "(", "matlab", ")", ">", "0", ":", "objc", "=", "list", "(", "filter", "(", "lambda", "x", ":", "x", "[", "2", "]", ".", "name", ".", "lower", "(", ")", "==", "'objective-c'", ",", "result", ")", ")", "if", "objc", "and", "objc", "[", "0", "]", "[", "0", "]", "==", "matlab", "[", "0", "]", "[", "0", "]", ":", "raise", "SkipHeartbeat", "(", "'Skipping because not enough language accuracy.'", ")", "def", "type_sort", "(", "t", ")", ":", "# sort by:", "# - analyse score", "# - is primary filename pattern?", "# - priority", "# - last resort: class name", "return", "(", "t", "[", "0", "]", ",", "primary", "[", "t", "[", "2", "]", "]", ",", "t", "[", "1", "]", ",", "t", "[", "2", "]", ".", "__name__", ")", "result", ".", "sort", "(", "key", "=", "type_sort", ")", "return", "result", "[", "-", "1", "]", "[", "2", "]", "(", "*", "*", "options", ")" ]
Overwrite pygments.lexers.guess_lexer_for_filename to customize the priority of different lexers based on popularity of languages.
[ "Overwrite", "pygments", ".", "lexers", ".", "guess_lexer_for_filename", "to", "customize", "the", "priority", "of", "different", "lexers", "based", "on", "popularity", "of", "languages", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L304-L346
train
wakatime/wakatime
wakatime/stats.py
customize_lexer_priority
def customize_lexer_priority(file_name, accuracy, lexer): """Customize lexer priority""" priority = lexer.priority lexer_name = lexer.name.lower().replace('sharp', '#') if lexer_name in LANGUAGES: priority = LANGUAGES[lexer_name] elif lexer_name == 'matlab': available_extensions = extensions_in_same_folder(file_name) if '.mat' in available_extensions: accuracy += 0.01 if '.h' not in available_extensions: accuracy += 0.01 elif lexer_name == 'objective-c': available_extensions = extensions_in_same_folder(file_name) if '.mat' in available_extensions: accuracy -= 0.01 else: accuracy += 0.01 if '.h' in available_extensions: accuracy += 0.01 return (accuracy, priority, lexer)
python
def customize_lexer_priority(file_name, accuracy, lexer): """Customize lexer priority""" priority = lexer.priority lexer_name = lexer.name.lower().replace('sharp', '#') if lexer_name in LANGUAGES: priority = LANGUAGES[lexer_name] elif lexer_name == 'matlab': available_extensions = extensions_in_same_folder(file_name) if '.mat' in available_extensions: accuracy += 0.01 if '.h' not in available_extensions: accuracy += 0.01 elif lexer_name == 'objective-c': available_extensions = extensions_in_same_folder(file_name) if '.mat' in available_extensions: accuracy -= 0.01 else: accuracy += 0.01 if '.h' in available_extensions: accuracy += 0.01 return (accuracy, priority, lexer)
[ "def", "customize_lexer_priority", "(", "file_name", ",", "accuracy", ",", "lexer", ")", ":", "priority", "=", "lexer", ".", "priority", "lexer_name", "=", "lexer", ".", "name", ".", "lower", "(", ")", ".", "replace", "(", "'sharp'", ",", "'#'", ")", "if", "lexer_name", "in", "LANGUAGES", ":", "priority", "=", "LANGUAGES", "[", "lexer_name", "]", "elif", "lexer_name", "==", "'matlab'", ":", "available_extensions", "=", "extensions_in_same_folder", "(", "file_name", ")", "if", "'.mat'", "in", "available_extensions", ":", "accuracy", "+=", "0.01", "if", "'.h'", "not", "in", "available_extensions", ":", "accuracy", "+=", "0.01", "elif", "lexer_name", "==", "'objective-c'", ":", "available_extensions", "=", "extensions_in_same_folder", "(", "file_name", ")", "if", "'.mat'", "in", "available_extensions", ":", "accuracy", "-=", "0.01", "else", ":", "accuracy", "+=", "0.01", "if", "'.h'", "in", "available_extensions", ":", "accuracy", "+=", "0.01", "return", "(", "accuracy", ",", "priority", ",", "lexer", ")" ]
Customize lexer priority
[ "Customize", "lexer", "priority" ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L349-L372
train
wakatime/wakatime
wakatime/stats.py
extensions_in_same_folder
def extensions_in_same_folder(file_name): """Returns a list of file extensions from the same folder as file_name.""" directory = os.path.dirname(file_name) files = os.listdir(directory) extensions = list(zip(*map(os.path.splitext, files)))[1] extensions = set([ext.lower() for ext in extensions]) return extensions
python
def extensions_in_same_folder(file_name): """Returns a list of file extensions from the same folder as file_name.""" directory = os.path.dirname(file_name) files = os.listdir(directory) extensions = list(zip(*map(os.path.splitext, files)))[1] extensions = set([ext.lower() for ext in extensions]) return extensions
[ "def", "extensions_in_same_folder", "(", "file_name", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "file_name", ")", "files", "=", "os", ".", "listdir", "(", "directory", ")", "extensions", "=", "list", "(", "zip", "(", "*", "map", "(", "os", ".", "path", ".", "splitext", ",", "files", ")", ")", ")", "[", "1", "]", "extensions", "=", "set", "(", "[", "ext", ".", "lower", "(", ")", "for", "ext", "in", "extensions", "]", ")", "return", "extensions" ]
Returns a list of file extensions from the same folder as file_name.
[ "Returns", "a", "list", "of", "file", "extensions", "from", "the", "same", "folder", "as", "file_name", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/stats.py#L375-L382
train
wakatime/wakatime
wakatime/packages/pygments/lexers/scripting.py
RexxLexer.analyse_text
def analyse_text(text): """ Check for inital comment and patterns that distinguish Rexx from other C-like languages. """ if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE): # Header matches MVS Rexx requirements, this is certainly a Rexx # script. return 1.0 elif text.startswith('/*'): # Header matches general Rexx requirements; the source code might # still be any language using C comments such as C++, C# or Java. lowerText = text.lower() result = sum(weight for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS if pattern.search(lowerText)) + 0.01 return min(result, 1.0)
python
def analyse_text(text): """ Check for inital comment and patterns that distinguish Rexx from other C-like languages. """ if re.search(r'/\*\**\s*rexx', text, re.IGNORECASE): # Header matches MVS Rexx requirements, this is certainly a Rexx # script. return 1.0 elif text.startswith('/*'): # Header matches general Rexx requirements; the source code might # still be any language using C comments such as C++, C# or Java. lowerText = text.lower() result = sum(weight for (pattern, weight) in RexxLexer.PATTERNS_AND_WEIGHTS if pattern.search(lowerText)) + 0.01 return min(result, 1.0)
[ "def", "analyse_text", "(", "text", ")", ":", "if", "re", ".", "search", "(", "r'/\\*\\**\\s*rexx'", ",", "text", ",", "re", ".", "IGNORECASE", ")", ":", "# Header matches MVS Rexx requirements, this is certainly a Rexx", "# script.", "return", "1.0", "elif", "text", ".", "startswith", "(", "'/*'", ")", ":", "# Header matches general Rexx requirements; the source code might", "# still be any language using C comments such as C++, C# or Java.", "lowerText", "=", "text", ".", "lower", "(", ")", "result", "=", "sum", "(", "weight", "for", "(", "pattern", ",", "weight", ")", "in", "RexxLexer", ".", "PATTERNS_AND_WEIGHTS", "if", "pattern", ".", "search", "(", "lowerText", ")", ")", "+", "0.01", "return", "min", "(", "result", ",", "1.0", ")" ]
Check for inital comment and patterns that distinguish Rexx from other C-like languages.
[ "Check", "for", "inital", "comment", "and", "patterns", "that", "distinguish", "Rexx", "from", "other", "C", "-", "like", "languages", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/scripting.py#L801-L817
train
wakatime/wakatime
wakatime/packages/pygments/lexers/scripting.py
EasytrieveLexer.analyse_text
def analyse_text(text): """ Perform a structural analysis for basic Easytrieve constructs. """ result = 0.0 lines = text.split('\n') hasEndProc = False hasHeaderComment = False hasFile = False hasJob = False hasProc = False hasParm = False hasReport = False def isCommentLine(line): return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None def isEmptyLine(line): return not bool(line.strip()) # Remove possible empty lines and header comments. while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])): if not isEmptyLine(lines[0]): hasHeaderComment = True del lines[0] if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]): # Looks like an Easytrieve macro. result = 0.4 if hasHeaderComment: result += 0.4 else: # Scan the source for lines starting with indicators. for line in lines: words = line.split() if (len(words) >= 2): firstWord = words[0] if not hasReport: if not hasJob: if not hasFile: if not hasParm: if firstWord == 'PARM': hasParm = True if firstWord == 'FILE': hasFile = True if firstWord == 'JOB': hasJob = True elif firstWord == 'PROC': hasProc = True elif firstWord == 'END-PROC': hasEndProc = True elif firstWord == 'REPORT': hasReport = True # Weight the findings. if hasJob and (hasProc == hasEndProc): if hasHeaderComment: result += 0.1 if hasParm: if hasProc: # Found PARM, JOB and PROC/END-PROC: # pretty sure this is Easytrieve. result += 0.8 else: # Found PARAM and JOB: probably this is Easytrieve result += 0.5 else: # Found JOB and possibly other keywords: might be Easytrieve result += 0.11 if hasParm: # Note: PARAM is not a proper English word, so this is # regarded a much better indicator for Easytrieve than # the other words. result += 0.2 if hasFile: result += 0.01 if hasReport: result += 0.01 assert 0.0 <= result <= 1.0 return result
python
def analyse_text(text): """ Perform a structural analysis for basic Easytrieve constructs. """ result = 0.0 lines = text.split('\n') hasEndProc = False hasHeaderComment = False hasFile = False hasJob = False hasProc = False hasParm = False hasReport = False def isCommentLine(line): return EasytrieveLexer._COMMENT_LINE_REGEX.match(lines[0]) is not None def isEmptyLine(line): return not bool(line.strip()) # Remove possible empty lines and header comments. while lines and (isEmptyLine(lines[0]) or isCommentLine(lines[0])): if not isEmptyLine(lines[0]): hasHeaderComment = True del lines[0] if EasytrieveLexer._MACRO_HEADER_REGEX.match(lines[0]): # Looks like an Easytrieve macro. result = 0.4 if hasHeaderComment: result += 0.4 else: # Scan the source for lines starting with indicators. for line in lines: words = line.split() if (len(words) >= 2): firstWord = words[0] if not hasReport: if not hasJob: if not hasFile: if not hasParm: if firstWord == 'PARM': hasParm = True if firstWord == 'FILE': hasFile = True if firstWord == 'JOB': hasJob = True elif firstWord == 'PROC': hasProc = True elif firstWord == 'END-PROC': hasEndProc = True elif firstWord == 'REPORT': hasReport = True # Weight the findings. if hasJob and (hasProc == hasEndProc): if hasHeaderComment: result += 0.1 if hasParm: if hasProc: # Found PARM, JOB and PROC/END-PROC: # pretty sure this is Easytrieve. result += 0.8 else: # Found PARAM and JOB: probably this is Easytrieve result += 0.5 else: # Found JOB and possibly other keywords: might be Easytrieve result += 0.11 if hasParm: # Note: PARAM is not a proper English word, so this is # regarded a much better indicator for Easytrieve than # the other words. result += 0.2 if hasFile: result += 0.01 if hasReport: result += 0.01 assert 0.0 <= result <= 1.0 return result
[ "def", "analyse_text", "(", "text", ")", ":", "result", "=", "0.0", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "hasEndProc", "=", "False", "hasHeaderComment", "=", "False", "hasFile", "=", "False", "hasJob", "=", "False", "hasProc", "=", "False", "hasParm", "=", "False", "hasReport", "=", "False", "def", "isCommentLine", "(", "line", ")", ":", "return", "EasytrieveLexer", ".", "_COMMENT_LINE_REGEX", ".", "match", "(", "lines", "[", "0", "]", ")", "is", "not", "None", "def", "isEmptyLine", "(", "line", ")", ":", "return", "not", "bool", "(", "line", ".", "strip", "(", ")", ")", "# Remove possible empty lines and header comments.", "while", "lines", "and", "(", "isEmptyLine", "(", "lines", "[", "0", "]", ")", "or", "isCommentLine", "(", "lines", "[", "0", "]", ")", ")", ":", "if", "not", "isEmptyLine", "(", "lines", "[", "0", "]", ")", ":", "hasHeaderComment", "=", "True", "del", "lines", "[", "0", "]", "if", "EasytrieveLexer", ".", "_MACRO_HEADER_REGEX", ".", "match", "(", "lines", "[", "0", "]", ")", ":", "# Looks like an Easytrieve macro.", "result", "=", "0.4", "if", "hasHeaderComment", ":", "result", "+=", "0.4", "else", ":", "# Scan the source for lines starting with indicators.", "for", "line", "in", "lines", ":", "words", "=", "line", ".", "split", "(", ")", "if", "(", "len", "(", "words", ")", ">=", "2", ")", ":", "firstWord", "=", "words", "[", "0", "]", "if", "not", "hasReport", ":", "if", "not", "hasJob", ":", "if", "not", "hasFile", ":", "if", "not", "hasParm", ":", "if", "firstWord", "==", "'PARM'", ":", "hasParm", "=", "True", "if", "firstWord", "==", "'FILE'", ":", "hasFile", "=", "True", "if", "firstWord", "==", "'JOB'", ":", "hasJob", "=", "True", "elif", "firstWord", "==", "'PROC'", ":", "hasProc", "=", "True", "elif", "firstWord", "==", "'END-PROC'", ":", "hasEndProc", "=", "True", "elif", "firstWord", "==", "'REPORT'", ":", "hasReport", "=", "True", "# Weight the findings.", "if", "hasJob", "and", "(", "hasProc", "==", "hasEndProc", ")", ":", "if", "hasHeaderComment", ":", "result", "+=", "0.1", "if", "hasParm", ":", "if", "hasProc", ":", "# Found PARM, JOB and PROC/END-PROC:", "# pretty sure this is Easytrieve.", "result", "+=", "0.8", "else", ":", "# Found PARAM and JOB: probably this is Easytrieve", "result", "+=", "0.5", "else", ":", "# Found JOB and possibly other keywords: might be Easytrieve", "result", "+=", "0.11", "if", "hasParm", ":", "# Note: PARAM is not a proper English word, so this is", "# regarded a much better indicator for Easytrieve than", "# the other words.", "result", "+=", "0.2", "if", "hasFile", ":", "result", "+=", "0.01", "if", "hasReport", ":", "result", "+=", "0.01", "assert", "0.0", "<=", "result", "<=", "1.0", "return", "result" ]
Perform a structural analysis for basic Easytrieve constructs.
[ "Perform", "a", "structural", "analysis", "for", "basic", "Easytrieve", "constructs", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/scripting.py#L1059-L1138
train
wakatime/wakatime
wakatime/packages/pygments/lexers/scripting.py
JclLexer.analyse_text
def analyse_text(text): """ Recognize JCL job by header. """ result = 0.0 lines = text.split('\n') if len(lines) > 0: if JclLexer._JOB_HEADER_PATTERN.match(lines[0]): result = 1.0 assert 0.0 <= result <= 1.0 return result
python
def analyse_text(text): """ Recognize JCL job by header. """ result = 0.0 lines = text.split('\n') if len(lines) > 0: if JclLexer._JOB_HEADER_PATTERN.match(lines[0]): result = 1.0 assert 0.0 <= result <= 1.0 return result
[ "def", "analyse_text", "(", "text", ")", ":", "result", "=", "0.0", "lines", "=", "text", ".", "split", "(", "'\\n'", ")", "if", "len", "(", "lines", ")", ">", "0", ":", "if", "JclLexer", ".", "_JOB_HEADER_PATTERN", ".", "match", "(", "lines", "[", "0", "]", ")", ":", "result", "=", "1.0", "assert", "0.0", "<=", "result", "<=", "1.0", "return", "result" ]
Recognize JCL job by header.
[ "Recognize", "JCL", "job", "by", "header", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/scripting.py#L1212-L1222
train
wakatime/wakatime
wakatime/packages/pygments/lexers/asm.py
_objdump_lexer_tokens
def _objdump_lexer_tokens(asm_lexer): """ Common objdump lexer tokens to wrap an ASM lexer. """ hex_re = r'[0-9A-Za-z]' return { 'root': [ # File name & format: ('(.*?)(:)( +file format )(.*?)$', bygroups(Name.Label, Punctuation, Text, String)), # Section header ('(Disassembly of section )(.*?)(:)$', bygroups(Text, Name.Label, Punctuation)), # Function labels # (With offset) ('('+hex_re+'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation, Number.Hex, Punctuation)), # (Without offset) ('('+hex_re+'+)( )(<)(.*?)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation)), # Code line with disassembled instructions ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *\t)([a-zA-Z].*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, using(asm_lexer))), # Code line with ascii ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *)(.*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, String)), # Continued code line, only raw opcodes without disassembled # instruction ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)$', bygroups(Text, Name.Label, Text, Number.Hex)), # Skipped a few bytes (r'\t\.\.\.$', Text), # Relocation line # (With offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)([-+])(0x'+hex_re+'+)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant, Punctuation, Number.Hex)), # (Without offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant)), (r'[^\n]+\n', Other) ] }
python
def _objdump_lexer_tokens(asm_lexer): """ Common objdump lexer tokens to wrap an ASM lexer. """ hex_re = r'[0-9A-Za-z]' return { 'root': [ # File name & format: ('(.*?)(:)( +file format )(.*?)$', bygroups(Name.Label, Punctuation, Text, String)), # Section header ('(Disassembly of section )(.*?)(:)$', bygroups(Text, Name.Label, Punctuation)), # Function labels # (With offset) ('('+hex_re+'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation, Number.Hex, Punctuation)), # (Without offset) ('('+hex_re+'+)( )(<)(.*?)(>:)$', bygroups(Number.Hex, Text, Punctuation, Name.Function, Punctuation)), # Code line with disassembled instructions ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *\t)([a-zA-Z].*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, using(asm_lexer))), # Code line with ascii ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)( *)(.*?)$', bygroups(Text, Name.Label, Text, Number.Hex, Text, String)), # Continued code line, only raw opcodes without disassembled # instruction ('( *)('+hex_re+r'+:)(\t)((?:'+hex_re+hex_re+' )+)$', bygroups(Text, Name.Label, Text, Number.Hex)), # Skipped a few bytes (r'\t\.\.\.$', Text), # Relocation line # (With offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)([-+])(0x'+hex_re+'+)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant, Punctuation, Number.Hex)), # (Without offset) (r'(\t\t\t)('+hex_re+r'+:)( )([^\t]+)(\t)(.*?)$', bygroups(Text, Name.Label, Text, Name.Property, Text, Name.Constant)), (r'[^\n]+\n', Other) ] }
[ "def", "_objdump_lexer_tokens", "(", "asm_lexer", ")", ":", "hex_re", "=", "r'[0-9A-Za-z]'", "return", "{", "'root'", ":", "[", "# File name & format:", "(", "'(.*?)(:)( +file format )(.*?)$'", ",", "bygroups", "(", "Name", ".", "Label", ",", "Punctuation", ",", "Text", ",", "String", ")", ")", ",", "# Section header", "(", "'(Disassembly of section )(.*?)(:)$'", ",", "bygroups", "(", "Text", ",", "Name", ".", "Label", ",", "Punctuation", ")", ")", ",", "# Function labels", "# (With offset)", "(", "'('", "+", "hex_re", "+", "'+)( )(<)(.*?)([-+])(0[xX][A-Za-z0-9]+)(>:)$'", ",", "bygroups", "(", "Number", ".", "Hex", ",", "Text", ",", "Punctuation", ",", "Name", ".", "Function", ",", "Punctuation", ",", "Number", ".", "Hex", ",", "Punctuation", ")", ")", ",", "# (Without offset)", "(", "'('", "+", "hex_re", "+", "'+)( )(<)(.*?)(>:)$'", ",", "bygroups", "(", "Number", ".", "Hex", ",", "Text", ",", "Punctuation", ",", "Name", ".", "Function", ",", "Punctuation", ")", ")", ",", "# Code line with disassembled instructions", "(", "'( *)('", "+", "hex_re", "+", "r'+:)(\\t)((?:'", "+", "hex_re", "+", "hex_re", "+", "' )+)( *\\t)([a-zA-Z].*?)$'", ",", "bygroups", "(", "Text", ",", "Name", ".", "Label", ",", "Text", ",", "Number", ".", "Hex", ",", "Text", ",", "using", "(", "asm_lexer", ")", ")", ")", ",", "# Code line with ascii", "(", "'( *)('", "+", "hex_re", "+", "r'+:)(\\t)((?:'", "+", "hex_re", "+", "hex_re", "+", "' )+)( *)(.*?)$'", ",", "bygroups", "(", "Text", ",", "Name", ".", "Label", ",", "Text", ",", "Number", ".", "Hex", ",", "Text", ",", "String", ")", ")", ",", "# Continued code line, only raw opcodes without disassembled", "# instruction", "(", "'( *)('", "+", "hex_re", "+", "r'+:)(\\t)((?:'", "+", "hex_re", "+", "hex_re", "+", "' )+)$'", ",", "bygroups", "(", "Text", ",", "Name", ".", "Label", ",", "Text", ",", "Number", ".", "Hex", ")", ")", ",", "# Skipped a few bytes", "(", "r'\\t\\.\\.\\.$'", ",", "Text", ")", ",", "# Relocation line", "# (With offset)", "(", "r'(\\t\\t\\t)('", "+", "hex_re", "+", "r'+:)( )([^\\t]+)(\\t)(.*?)([-+])(0x'", "+", "hex_re", "+", "'+)$'", ",", "bygroups", "(", "Text", ",", "Name", ".", "Label", ",", "Text", ",", "Name", ".", "Property", ",", "Text", ",", "Name", ".", "Constant", ",", "Punctuation", ",", "Number", ".", "Hex", ")", ")", ",", "# (Without offset)", "(", "r'(\\t\\t\\t)('", "+", "hex_re", "+", "r'+:)( )([^\\t]+)(\\t)(.*?)$'", ",", "bygroups", "(", "Text", ",", "Name", ".", "Label", ",", "Text", ",", "Name", ".", "Property", ",", "Text", ",", "Name", ".", "Constant", ")", ")", ",", "(", "r'[^\\n]+\\n'", ",", "Other", ")", "]", "}" ]
Common objdump lexer tokens to wrap an ASM lexer.
[ "Common", "objdump", "lexer", "tokens", "to", "wrap", "an", "ASM", "lexer", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/lexers/asm.py#L100-L146
train
wakatime/wakatime
wakatime/packages/urllib3/util/selectors.py
BaseSelector.get_key
def get_key(self, fileobj): """ Return the key associated with a registered file object. """ mapping = self.get_map() if mapping is None: raise RuntimeError("Selector is closed") try: return mapping[fileobj] except KeyError: raise KeyError("{0!r} is not registered".format(fileobj))
python
def get_key(self, fileobj): """ Return the key associated with a registered file object. """ mapping = self.get_map() if mapping is None: raise RuntimeError("Selector is closed") try: return mapping[fileobj] except KeyError: raise KeyError("{0!r} is not registered".format(fileobj))
[ "def", "get_key", "(", "self", ",", "fileobj", ")", ":", "mapping", "=", "self", ".", "get_map", "(", ")", "if", "mapping", "is", "None", ":", "raise", "RuntimeError", "(", "\"Selector is closed\"", ")", "try", ":", "return", "mapping", "[", "fileobj", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "\"{0!r} is not registered\"", ".", "format", "(", "fileobj", ")", ")" ]
Return the key associated with a registered file object.
[ "Return", "the", "key", "associated", "with", "a", "registered", "file", "object", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/urllib3/util/selectors.py#L256-L264
train
wakatime/wakatime
wakatime/packages/pygments/modeline.py
get_filetype_from_buffer
def get_filetype_from_buffer(buf, max_lines=5): """ Scan the buffer for modelines and return filetype if one is found. """ lines = buf.splitlines() for l in lines[-1:-max_lines-1:-1]: ret = get_filetype_from_line(l) if ret: return ret for i in range(max_lines, -1, -1): if i < len(lines): ret = get_filetype_from_line(lines[i]) if ret: return ret return None
python
def get_filetype_from_buffer(buf, max_lines=5): """ Scan the buffer for modelines and return filetype if one is found. """ lines = buf.splitlines() for l in lines[-1:-max_lines-1:-1]: ret = get_filetype_from_line(l) if ret: return ret for i in range(max_lines, -1, -1): if i < len(lines): ret = get_filetype_from_line(lines[i]) if ret: return ret return None
[ "def", "get_filetype_from_buffer", "(", "buf", ",", "max_lines", "=", "5", ")", ":", "lines", "=", "buf", ".", "splitlines", "(", ")", "for", "l", "in", "lines", "[", "-", "1", ":", "-", "max_lines", "-", "1", ":", "-", "1", "]", ":", "ret", "=", "get_filetype_from_line", "(", "l", ")", "if", "ret", ":", "return", "ret", "for", "i", "in", "range", "(", "max_lines", ",", "-", "1", ",", "-", "1", ")", ":", "if", "i", "<", "len", "(", "lines", ")", ":", "ret", "=", "get_filetype_from_line", "(", "lines", "[", "i", "]", ")", "if", "ret", ":", "return", "ret", "return", "None" ]
Scan the buffer for modelines and return filetype if one is found.
[ "Scan", "the", "buffer", "for", "modelines", "and", "return", "filetype", "if", "one", "is", "found", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/modeline.py#L29-L44
train
wakatime/wakatime
wakatime/packages/pygments/formatters/img.py
FontManager.get_font
def get_font(self, bold, oblique): """ Get the font based on bold and italic flags. """ if bold and oblique: return self.fonts['BOLDITALIC'] elif bold: return self.fonts['BOLD'] elif oblique: return self.fonts['ITALIC'] else: return self.fonts['NORMAL']
python
def get_font(self, bold, oblique): """ Get the font based on bold and italic flags. """ if bold and oblique: return self.fonts['BOLDITALIC'] elif bold: return self.fonts['BOLD'] elif oblique: return self.fonts['ITALIC'] else: return self.fonts['NORMAL']
[ "def", "get_font", "(", "self", ",", "bold", ",", "oblique", ")", ":", "if", "bold", "and", "oblique", ":", "return", "self", ".", "fonts", "[", "'BOLDITALIC'", "]", "elif", "bold", ":", "return", "self", ".", "fonts", "[", "'BOLD'", "]", "elif", "oblique", ":", "return", "self", ".", "fonts", "[", "'ITALIC'", "]", "else", ":", "return", "self", ".", "fonts", "[", "'NORMAL'", "]" ]
Get the font based on bold and italic flags.
[ "Get", "the", "font", "based", "on", "bold", "and", "italic", "flags", "." ]
74519ace04e8472f3a3993269963732b9946a01d
https://github.com/wakatime/wakatime/blob/74519ace04e8472f3a3993269963732b9946a01d/wakatime/packages/pygments/formatters/img.py#L199-L210
train