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... | 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... | [
"def",
"build",
"(",
"self",
",",
"shutit",
")",
":",
"shutit_pexpect_session",
"=",
"ShutItPexpectSession",
"(",
"shutit",
",",
"'target_child'",
",",
"'/bin/bash'",
")",
"target_child",
"=",
"shutit_pexpect_session",
".",
"pexpect_child",
"shutit_pexpect_session",
"... | 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=noninter... | 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=noninter... | [
"def",
"build",
"(",
"self",
",",
"shutit",
")",
":",
"if",
"shutit",
".",
"build",
"[",
"'delivery'",
"]",
"in",
"(",
"'docker'",
",",
"'dockerfile'",
")",
":",
"if",
"shutit",
".",
"get_current_shutit_pexpect_session_environment",
"(",
")",
".",
"install_t... | 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', 'angry@shutit.tk',
'shutit.core.alerting.emailer.s... | 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', 'angry@shutit.tk',
'shutit.core.alerting.emailer.s... | [
"def",
"__set_config",
"(",
"self",
",",
"cfg_section",
")",
":",
"defaults",
"=",
"[",
"'shutit.core.alerting.emailer.mailto'",
",",
"None",
",",
"'shutit.core.alerting.emailer.mailfrom'",
",",
"'angry@shutit.tk'",
",",
"'shutit.core.alerting.emailer.smtp_server'",
",",
"'... | 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.star... | 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.star... | [
"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'",
"]",
... | 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.... | 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.... | [
"def",
"__compose",
"(",
"self",
")",
":",
"msg",
"=",
"MIMEMultipart",
"(",
")",
"msg",
"[",
"'Subject'",
"]",
"=",
"self",
".",
"config",
"[",
"'shutit.core.alerting.emailer.subject'",
"]",
"msg",
"[",
"'To'",
"]",
"=",
"self",
".",
"config",
"[",
"'sh... | 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']:... | 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']:... | [
"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!'",
",... | 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",
"... | 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]
... | 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]
... | [
"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"... | 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_ob... | 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_ob... | [
"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",
"backgro... | 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... | 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... | [
"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",... | 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",
",",
... | 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)
r... | 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)
r... | [
"def",
"fetch_blob",
"(",
"cls",
",",
"username",
",",
"password",
",",
"multifactor_password",
"=",
"None",
",",
"client_id",
"=",
"None",
")",
":",
"session",
"=",
"fetcher",
".",
"login",
"(",
"username",
",",
"password",
",",
"multifactor_password",
",",... | 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))
... | 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))
... | [
"def",
"extract_chunks",
"(",
"blob",
")",
":",
"chunks",
"=",
"[",
"]",
"stream",
"=",
"BytesIO",
"(",
"blob",
".",
"bytes",
")",
"current_pos",
"=",
"stream",
".",
"tell",
"(",
")",
"stream",
".",
"seek",
"(",
"0",
",",
"2",
")",
"length",
"=",
... | 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 ... | 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 ... | [
"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",
... | 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... | 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'^Last... | 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'^Last... | [
"def",
"parse_PRIK",
"(",
"chunk",
",",
"encryption_key",
")",
":",
"decrypted",
"=",
"decode_aes256",
"(",
"'cbc'",
",",
"encryption_key",
"[",
":",
"16",
"]",
",",
"decode_hex",
"(",
"chunk",
".",
"payload",
")",
",",
"encryption_key",
")",
"hex_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 "|".... | 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 "|".... | [
"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 com... | 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",
",",
"'del... | 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':
... | 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':
... | [
"def",
"api_params",
"(",
"service",
",",
"file_id",
",",
"owner_token",
",",
"download_limit",
")",
":",
"service",
"+=",
"'api/params/%s'",
"%",
"file_id",
"r",
"=",
"requests",
".",
"post",
"(",
"service",
",",
"json",
"=",
"{",
"'owner_token'",
":",
"o... | 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/d... | 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/d... | [
"def",
"api_download",
"(",
"service",
",",
"fileId",
",",
"authorisation",
")",
":",
"data",
"=",
"tempfile",
".",
"SpooledTemporaryFile",
"(",
"max_size",
"=",
"SPOOL_SIZE",
",",
"mode",
"=",
"'w+b'",
")",
"headers",
"=",
"{",
"'Authorization'",
":",
"'sen... | 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()
# n... | 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()
# n... | [
"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",
"(",
"-... | 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",
")",
... | 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': o... | 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': o... | [
"def",
"api_password",
"(",
"service",
",",
"fileId",
",",
"ownerToken",
",",
"newAuthKey",
")",
":",
"service",
"+=",
"'api/password/%s'",
"%",
"fileId",
"auth",
"=",
"sendclient",
".",
"common",
".",
"unpadded_urlsafe_b64encode",
"(",
"newAuthKey",
")",
"r",
... | 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(r... | 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(r... | [
"def",
"set_password",
"(",
"url",
",",
"ownerToken",
",",
"password",
")",
":",
"service",
",",
"fileId",
",",
"key",
"=",
"sendclient",
".",
"common",
".",
"splitkeyurl",
"(",
"url",
")",
"rawKey",
"=",
"sendclient",
".",
"common",
".",
"unpadded_urlsafe... | 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') })
... | 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') })
... | [
"def",
"api_upload",
"(",
"service",
",",
"encData",
",",
"encMeta",
",",
"keys",
")",
":",
"service",
"+=",
"'api/upload'",
"files",
"=",
"requests_toolbelt",
".",
"MultipartEncoder",
"(",
"fields",
"=",
"{",
"'file'",
":",
"(",
"'blob'",
",",
"encData",
... | 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'''
fileNa... | 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'''
fileNa... | [
"def",
"send_file",
"(",
"service",
",",
"file",
",",
"fileName",
"=",
"None",
",",
"password",
"=",
"None",
",",
"ignoreVersion",
"=",
"False",
")",
":",
"if",
"checkServerVersion",
"(",
"service",
",",
"ignoreVersion",
"=",
"ignoreVersion",
")",
"==",
"F... | 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 sel... | 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 sel... | [
"def",
"fetch",
"(",
"self",
",",
"endpoint",
",",
"data",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"\"lastServerChangeId\"",
":",
"\"-1\"",
",",
"\"csrf\"",
":",
"self",
".",
"__csrf",
",",
"\"apiClient\"",
":",
"\"WEB\"",
"}",
"if",
"data",
"is",
... | 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",
... | 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",
... | [
"def",
"__identify_user",
"(",
"self",
",",
"username",
",",
"csrf",
")",
":",
"data",
"=",
"{",
"\"username\"",
":",
"username",
",",
"\"csrf\"",
":",
"csrf",
",",
"\"apiClient\"",
":",
"\"WEB\"",
",",
"\"bindDevice\"",
":",
"\"false\"",
",",
"\"skipLinkAcc... | 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 '... | 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 '... | [
"def",
"get_args",
"(",
"cls",
",",
"dist",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
"=",
"cls",
".",
"get_header",
"(",
")",
"spec",
"=",
"str",
"(",
"dist",
".",
"as_requirement",
"(",
")",
")",
"for",
... | 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)
t... | 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)
t... | [
"def",
"clean_pip_env",
"(",
")",
"->",
"Generator",
"[",
"None",
",",
"None",
",",
"None",
"]",
":",
"require_venv",
"=",
"os",
".",
"environ",
".",
"pop",
"(",
"PIP_REQUIRE_VIRTUALENV",
",",
"None",
")",
"try",
":",
"yield",
"finally",
":",
"if",
"re... | 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.... | 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.... | [
"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",
"# ... | `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 packa... | [
"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",
"("... | 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 = targe... | 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 = targe... | [
"def",
"extract_site_packages",
"(",
"archive",
",",
"target_path",
",",
"compile_pyc",
",",
"compile_workers",
"=",
"0",
",",
"force",
"=",
"False",
")",
":",
"parent",
"=",
"target_path",
".",
"parent",
"target_path_tmp",
"=",
"Path",
"(",
"parent",
",",
"... | 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... | 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... | [
"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",
... | 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.ex... | 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.ex... | [
"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",
":",
"sy... | 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_archi... | 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_archi... | [
"def",
"create_archive",
"(",
"source",
":",
"Path",
",",
"target",
":",
"Path",
",",
"interpreter",
":",
"str",
",",
"main",
":",
"str",
",",
"compressed",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"# Check that main has the right format.",
"mod",
... | 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)
els... | 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)
els... | [
"def",
"acquire_win",
"(",
"lock_file",
")",
":",
"# pragma: no cover",
"try",
":",
"fd",
"=",
"os",
".",
"open",
"(",
"lock_file",
",",
"OPEN_MODE",
")",
"except",
"OSError",
":",
"pass",
"else",
":",
"try",
":",
"msvcrt",
".",
"locking",
"(",
"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",
")"... | 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 cons... | 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 cons... | [
"def",
"find_entry_point",
"(",
"site_packages",
":",
"Path",
",",
"console_script",
":",
"str",
")",
"->",
"str",
":",
"config_parser",
"=",
"ConfigParser",
"(",
")",
"config_parser",
".",
"read",
"(",
"site_packages",
".",
"rglob",
"(",
"\"entry_points.txt\"",... | 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 dire... | [
"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_re... | 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_re... | [
"def",
"copy_bootstrap",
"(",
"bootstrap_target",
":",
"Path",
")",
"->",
"None",
":",
"for",
"bootstrap_file",
"in",
"importlib_resources",
".",
"contents",
"(",
"bootstrap",
")",
":",
"if",
"importlib_resources",
".",
"is_resource",
"(",
"bootstrap",
",",
"boo... | 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... | 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... | [
"def",
"_interpreter_path",
"(",
"append_version",
":",
"bool",
"=",
"False",
")",
"->",
"str",
":",
"base_dir",
"=",
"Path",
"(",
"getattr",
"(",
"sys",
",",
"\"real_prefix\"",
",",
"sys",
".",
"base_prefix",
")",
")",
".",
"resolve",
"(",
")",
"sys_exe... | 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 bui... | 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 bui... | [
"def",
"main",
"(",
"output_file",
":",
"str",
",",
"entry_point",
":",
"Optional",
"[",
"str",
"]",
",",
"console_script",
":",
"Optional",
"[",
"str",
"]",
",",
"python",
":",
"Optional",
"[",
"str",
"]",
",",
"site_packages",
":",
"Optional",
"[",
"... | 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",
"=",
"lo... | 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... | 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... | [
"async",
"def",
"read",
"(",
"self",
",",
"amt",
"=",
"None",
")",
":",
"# botocore to aiohttp mapping",
"chunk",
"=",
"await",
"self",
".",
"__wrapped__",
".",
"read",
"(",
"amt",
"if",
"amt",
"is",
"not",
"None",
"else",
"-",
"1",
")",
"self",
".",
... | 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 ... | 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 ... | [
"async",
"def",
"iter_lines",
"(",
"self",
",",
"chunk_size",
"=",
"1024",
")",
":",
"pending",
"=",
"b''",
"async",
"for",
"chunk",
"in",
"self",
".",
"iter_chunks",
"(",
"chunk_size",
")",
":",
"lines",
"=",
"(",
"pending",
"+",
"chunk",
")",
".",
... | 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... | 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... | [
"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"... | 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,... | 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,... | [
"def",
"get_items",
"(",
"start_num",
",",
"num_items",
")",
":",
"result",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"start_num",
",",
"start_num",
"+",
"num_items",
")",
":",
"result",
".",
"append",
"(",
"{",
"'pk'",
":",
"{",
"'S'",
":",
"... | 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... | 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... | [
"def",
"create_batch_write_structure",
"(",
"table_name",
",",
"start_num",
",",
"num_items",
")",
":",
"return",
"{",
"table_name",
":",
"[",
"{",
"'PutRequest'",
":",
"{",
"'Item'",
":",
"item",
"}",
"}",
"for",
"item",
"in",
"get_items",
"(",
"start_num",... | 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... | 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... | [
"def",
"get_paginator",
"(",
"self",
",",
"operation_name",
")",
":",
"if",
"not",
"self",
".",
"can_paginate",
"(",
"operation_name",
")",
":",
"raise",
"OperationNotPageableError",
"(",
"operation_name",
"=",
"operation_name",
")",
"else",
":",
"# substitute ite... | 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 ``clie... | [
"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 ob... | 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 ob... | [
"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"... | 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(quer... | 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(quer... | [
"def",
"url_fix",
"(",
"s",
",",
"charset",
"=",
"None",
")",
":",
"if",
"charset",
":",
"warnings",
".",
"warn",
"(",
"\"{}.url_fix() charset argument is deprecated\"",
".",
"format",
"(",
"__name__",
")",
",",
"DeprecationWarning",
")",
"scheme",
",",
"netlo... | 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
f... | 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
f... | [
"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_... | 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
... | [
"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``
"""
... | 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``
"""
... | [
"def",
"parse_request_body",
"(",
"self",
",",
"body",
")",
":",
"PARSING_FUNCTIONS",
"=",
"{",
"'application/json'",
":",
"json",
".",
"loads",
",",
"'text/json'",
":",
"json",
".",
"loads",
",",
"'application/x-www-form-urlencoded'",
":",
"self",
".",
"parse_q... | 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.st... | 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.st... | [
"def",
"fill_filekind",
"(",
"self",
",",
"fk",
")",
":",
"now",
"=",
"datetime",
".",
"utcnow",
"(",
")",
"headers",
"=",
"{",
"'status'",
":",
"self",
".",
"status",
",",
"'date'",
":",
"now",
".",
"strftime",
"(",
"'%a, %d %b %Y %H:%M:%S GMT'",
")",
... | 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 m... | 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 m... | [
"def",
"draw_text",
"(",
"stdscr",
",",
"text",
",",
"color",
"=",
"0",
",",
"fallback",
"=",
"None",
",",
"title",
"=",
"None",
")",
":",
"if",
"fallback",
"is",
"None",
":",
"fallback",
"=",
"text",
"y",
",",
"x",
"=",
"stdscr",
".",
"getmaxyx",
... | 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)... | 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)... | [
"def",
"format_seconds",
"(",
"seconds",
",",
"hide_seconds",
"=",
"False",
")",
":",
"if",
"seconds",
"<=",
"60",
":",
"return",
"str",
"(",
"seconds",
")",
"output",
"=",
"\"\"",
"for",
"period",
",",
"period_seconds",
"in",
"(",
"(",
"'y'",
",",
"31... | 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",
"Keyboa... | 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,... | 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,... | [
"def",
"pad_to_size",
"(",
"text",
",",
"x",
",",
"y",
")",
":",
"input_lines",
"=",
"text",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"\"\\n\"",
")",
"longest_input_line",
"=",
"max",
"(",
"map",
"(",
"len",
",",
"input_lines",
")",
")",
"number_o... | 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()... | 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()... | [
"def",
"parse_timestr",
"(",
"timestr",
")",
":",
"timedelta_secs",
"=",
"parse_timedelta",
"(",
"timestr",
")",
"sync_start",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"timedelta_secs",
":",
"target",
"=",
"datetime",
".",
"now",
"(",
")",
"+",
"timede... | 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... | 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... | [
"def",
"parse_timedelta",
"(",
"deltastr",
")",
":",
"matches",
"=",
"TIMEDELTA_REGEX",
".",
"match",
"(",
"deltastr",
")",
"if",
"not",
"matches",
":",
"return",
"None",
"components",
"=",
"{",
"}",
"for",
"name",
",",
"value",
"in",
"matches",
".",
"gr... | 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
@p... | 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
@p... | [
"def",
"_verify_signature",
"(",
"self",
",",
"message",
",",
"signature",
")",
":",
"if",
"self",
".",
"negotiate_flags",
"&",
"NegotiateFlags",
".",
"NTLMSSP_NEGOTIATE_EXTENDED_SESSIONSECURITY",
":",
"actual_checksum",
"=",
"signature",
"[",
"4",
":",
"12",
"]",... | 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) ==... | 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) ==... | [
"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",... | 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(strin... | 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(strin... | [
"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.s... | 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.s... | [
"def",
"open_resource",
"(",
"name",
")",
":",
"name_parts",
"=",
"name",
".",
"lstrip",
"(",
"'/'",
")",
".",
"split",
"(",
"'/'",
")",
"for",
"part",
"in",
"name_parts",
":",
"if",
"part",
"==",
"os",
".",
"path",
".",
"pardir",
"or",
"os",
".",
... | 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.... | 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.... | [
"def",
"FixedOffset",
"(",
"offset",
",",
"_tzinfos",
"=",
"{",
"}",
")",
":",
"if",
"offset",
"==",
"0",
":",
"return",
"UTC",
"info",
"=",
"_tzinfos",
".",
"get",
"(",
"offset",
")",
"if",
"info",
"is",
"None",
":",
"# We haven't seen this one before. ... | 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)
>... | [
"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(ar... | 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(ar... | [
"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",
"... | 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):
... | 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):
... | [
"def",
"get_style_defs",
"(",
"self",
",",
"arg",
"=",
"''",
")",
":",
"cp",
"=",
"self",
".",
"commandprefix",
"styles",
"=",
"[",
"]",
"for",
"name",
",",
"definition",
"in",
"iteritems",
"(",
"self",
".",
"cmd2def",
")",
":",
"styles",
".",
"appen... | 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",
... | 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]]
... | 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]]
... | [
"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",
... | 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 _for... | 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 _for... | [
"def",
"find_formatter_class",
"(",
"alias",
")",
":",
"for",
"module_name",
",",
"name",
",",
"aliases",
",",
"_",
",",
"_",
"in",
"itervalues",
"(",
"FORMATTERS",
")",
":",
"if",
"alias",
"in",
"aliases",
":",
"if",
"name",
"not",
"in",
"_formatter_cac... | 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",
")",
... | 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 Format... | 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 Format... | [
"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",
"(",
"ope... | 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.
U... | [
"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... | 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... | [
"def",
"get_formatter_for_filename",
"(",
"fn",
",",
"*",
"*",
"options",
")",
":",
"fn",
"=",
"basename",
"(",
"fn",
")",
"for",
"modname",
",",
"name",
",",
"_",
",",
"filenames",
",",
"_",
"in",
"itervalues",
"(",
"FORMATTERS",
")",
":",
"for",
"f... | 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_na... | 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_na... | [
"def",
"find_lexer_class",
"(",
"name",
")",
":",
"if",
"name",
"in",
"_lexer_cache",
":",
"return",
"_lexer_cache",
"[",
"name",
"]",
"# lookup builtin lexers",
"for",
"module_name",
",",
"lname",
",",
"aliases",
",",
"_",
",",
"_",
"in",
"itervalues",
"(",... | 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, ... | 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, ... | [
"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",
",",
"_",
",",... | 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
... | 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
... | [
"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",
"(",
... | 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 w... | [
"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 ... | 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 ... | [
"def",
"get_lexer_for_mimetype",
"(",
"_mime",
",",
"*",
"*",
"options",
")",
":",
"for",
"modname",
",",
"name",
",",
"_",
",",
"_",
",",
"mimetypes",
"in",
"itervalues",
"(",
"LEXERS",
")",
":",
"if",
"_mime",
"in",
"mimetypes",
":",
"if",
"name",
... | 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_plug... | 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_plug... | [
"def",
"_iter_lexerclasses",
"(",
"plugins",
"=",
"True",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"LEXERS",
")",
":",
"module_name",
",",
"name",
"=",
"LEXERS",
"[",
"key",
"]",
"[",
":",
"2",
"]",
"if",
"name",
"not",
"in",
"_lexer_cache",
":",... | 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,
'dependenci... | 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,
'dependenci... | [
"def",
"get_file_stats",
"(",
"file_name",
",",
"entity_type",
"=",
"'file'",
",",
"lineno",
"=",
"None",
",",
"cursorpos",
"=",
"None",
",",
"plugin",
"=",
"None",
",",
"language",
"=",
"None",
",",
"local_file",
"=",
"None",
")",
":",
"language",
"=",
... | 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... | 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... | [
"def",
"guess_language",
"(",
"file_name",
",",
"local_file",
")",
":",
"lexer",
"=",
"None",
"language",
"=",
"get_language_from_extension",
"(",
"file_name",
")",
"if",
"language",
":",
"lexer",
"=",
"get_lexer",
"(",
"language",
")",
"else",
":",
"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.
"""
... | 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.
"""
... | [
"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"... | 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 SkipHeartbe... | 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 SkipHeartbe... | [
"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",
... | 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.... | 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.... | [
"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",
"."... | 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 ==... | 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 ==... | [
"def",
"get_language_from_extension",
"(",
"file_name",
")",
":",
"filepart",
",",
"extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"pathpart",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"file_name",
")",
"if",
... | 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('-'... | 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('-'... | [
"def",
"standardize_language",
"(",
"language",
",",
"plugin",
")",
":",
"if",
"not",
"language",
":",
"return",
"None",
"# standardize language for this plugin",
"if",
"plugin",
":",
"plugin",
"=",
"plugin",
".",
"split",
"(",
"' '",
")",
"[",
"-",
"1",
"]"... | 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... | 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... | [
"def",
"get_language_from_json",
"(",
"language",
",",
"key",
")",
":",
"file_name",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'languages'",
",",
"'{0}.json'",
")",
".",
"format",
"(",
"key... | 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 f... | 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 f... | [
"def",
"get_file_head",
"(",
"file_name",
")",
":",
"text",
"=",
"None",
"try",
":",
"with",
"open",
"(",
"file_name",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"fh",
":",
"text",
"=",
"fh",
".",
"read",
"(",
"512000",
")",
"except",
... | 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()... | 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()... | [
"def",
"custom_pygments_guess_lexer_for_filename",
"(",
"_fn",
",",
"_text",
",",
"*",
"*",
"options",
")",
":",
"fn",
"=",
"basename",
"(",
"_fn",
")",
"primary",
"=",
"{",
"}",
"matching_lexers",
"=",
"set",
"(",
")",
"for",
"lexer",
"in",
"_iter_lexercl... | 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 = ... | 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 = ... | [
"def",
"customize_lexer_priority",
"(",
"file_name",
",",
"accuracy",
",",
"lexer",
")",
":",
"priority",
"=",
"lexer",
".",
"priority",
"lexer_name",
"=",
"lexer",
".",
"name",
".",
"lower",
"(",
")",
".",
"replace",
"(",
"'sharp'",
",",
"'#'",
")",
"if... | 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])
... | 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])
... | [
"def",
"extensions_in_same_folder",
"(",
"file_name",
")",
":",
"directory",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"file_name",
")",
"files",
"=",
"os",
".",
"listdir",
"(",
"directory",
")",
"extensions",
"=",
"list",
"(",
"zip",
"(",
"*",
"map",... | 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.
... | 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.
... | [
"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"... | 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 ... | 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 ... | [
"def",
"analyse_text",
"(",
"text",
")",
":",
"result",
"=",
"0.0",
"lines",
"=",
"text",
".",
"split",
"(",
"'\\n'",
")",
"hasEndProc",
"=",
"False",
"hasHeaderComment",
"=",
"False",
"hasFile",
"=",
"False",
"hasJob",
"=",
"False",
"hasProc",
"=",
"Fal... | 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",
"[",
... | 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)),
... | 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)),
... | [
"def",
"_objdump_lexer_tokens",
"(",
"asm_lexer",
")",
":",
"hex_re",
"=",
"r'[0-9A-Za-z]'",
"return",
"{",
"'root'",
":",
"[",
"# File name & format:",
"(",
"'(.*?)(:)( +file format )(.*?)$'",
",",
"bygroups",
"(",
"Name",
".",
"Label",
",",
"Punctuation",
",",
"... | 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!... | 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!... | [
"def",
"get_key",
"(",
"self",
",",
"fileobj",
")",
":",
"mapping",
"=",
"self",
".",
"get_map",
"(",
")",
"if",
"mapping",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"\"Selector is closed\"",
")",
"try",
":",
"return",
"mapping",
"[",
"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)... | 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)... | [
"def",
"get_filetype_from_buffer",
"(",
"buf",
",",
"max_lines",
"=",
"5",
")",
":",
"lines",
"=",
"buf",
".",
"splitlines",
"(",
")",
"for",
"l",
"in",
"lines",
"[",
"-",
"1",
":",
"-",
"max_lines",
"-",
"1",
":",
"-",
"1",
"]",
":",
"ret",
"=",... | 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:
... | 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:
... | [
"def",
"get_font",
"(",
"self",
",",
"bold",
",",
"oblique",
")",
":",
"if",
"bold",
"and",
"oblique",
":",
"return",
"self",
".",
"fonts",
"[",
"'BOLDITALIC'",
"]",
"elif",
"bold",
":",
"return",
"self",
".",
"fonts",
"[",
"'BOLD'",
"]",
"elif",
"ob... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.