id int32 0 252k | 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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
8,000 | crs4/pydoop | pydoop/app/submit.py | PydoopSubmitter.set_args | def set_args(self, args, unknown_args=None):
"""
Configure job, based on the arguments provided.
"""
if unknown_args is None:
unknown_args = []
self.logger.setLevel(getattr(logging, args.log_level))
parent = hdfs.path.dirname(hdfs.path.abspath(args.output.rst... | python | def set_args(self, args, unknown_args=None):
"""
Configure job, based on the arguments provided.
"""
if unknown_args is None:
unknown_args = []
self.logger.setLevel(getattr(logging, args.log_level))
parent = hdfs.path.dirname(hdfs.path.abspath(args.output.rst... | [
"def",
"set_args",
"(",
"self",
",",
"args",
",",
"unknown_args",
"=",
"None",
")",
":",
"if",
"unknown_args",
"is",
"None",
":",
"unknown_args",
"=",
"[",
"]",
"self",
".",
"logger",
".",
"setLevel",
"(",
"getattr",
"(",
"logging",
",",
"args",
".",
... | Configure job, based on the arguments provided. | [
"Configure",
"job",
"based",
"on",
"the",
"arguments",
"provided",
"."
] | f375be2a06f9c67eaae3ce6f605195dbca143b2b | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/app/submit.py#L136-L164 |
8,001 | crs4/pydoop | pydoop/app/submit.py | PydoopSubmitter.__warn_user_if_wd_maybe_unreadable | def __warn_user_if_wd_maybe_unreadable(self, abs_remote_path):
"""
Check directories above the remote module and issue a warning if
they are not traversable by all users.
The reasoning behind this is mainly aimed at set-ups with a
centralized Hadoop cluster, accessed by all user... | python | def __warn_user_if_wd_maybe_unreadable(self, abs_remote_path):
"""
Check directories above the remote module and issue a warning if
they are not traversable by all users.
The reasoning behind this is mainly aimed at set-ups with a
centralized Hadoop cluster, accessed by all user... | [
"def",
"__warn_user_if_wd_maybe_unreadable",
"(",
"self",
",",
"abs_remote_path",
")",
":",
"host",
",",
"port",
",",
"path",
"=",
"hdfs",
".",
"path",
".",
"split",
"(",
"abs_remote_path",
")",
"if",
"host",
"==",
"''",
"and",
"port",
"==",
"0",
":",
"#... | Check directories above the remote module and issue a warning if
they are not traversable by all users.
The reasoning behind this is mainly aimed at set-ups with a
centralized Hadoop cluster, accessed by all users, and where
the Hadoop task tracker user is not a superuser; an example
... | [
"Check",
"directories",
"above",
"the",
"remote",
"module",
"and",
"issue",
"a",
"warning",
"if",
"they",
"are",
"not",
"traversable",
"by",
"all",
"users",
"."
] | f375be2a06f9c67eaae3ce6f605195dbca143b2b | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/app/submit.py#L166-L202 |
8,002 | crs4/pydoop | pydoop/app/submit.py | PydoopSubmitter.__setup_remote_paths | def __setup_remote_paths(self):
"""
Actually create the working directory and copy the module into it.
Note: the script has to be readable by Hadoop; though this may not
generally be a problem on HDFS, where the Hadoop user is usually
the superuser, things may be different if ou... | python | def __setup_remote_paths(self):
"""
Actually create the working directory and copy the module into it.
Note: the script has to be readable by Hadoop; though this may not
generally be a problem on HDFS, where the Hadoop user is usually
the superuser, things may be different if ou... | [
"def",
"__setup_remote_paths",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"remote_wd: %s\"",
",",
"self",
".",
"remote_wd",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"remote_exe: %s\"",
",",
"self",
".",
"remote_exe",
")",
"s... | Actually create the working directory and copy the module into it.
Note: the script has to be readable by Hadoop; though this may not
generally be a problem on HDFS, where the Hadoop user is usually
the superuser, things may be different if our working directory is
on a shared POSIX fil... | [
"Actually",
"create",
"the",
"working",
"directory",
"and",
"copy",
"the",
"module",
"into",
"it",
"."
] | f375be2a06f9c67eaae3ce6f605195dbca143b2b | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/app/submit.py#L295-L325 |
8,003 | crs4/pydoop | dev_tools/docker/scripts/share_etc_hosts.py | docker_client | def docker_client():
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
cert_path = os.environ.get('DOCKER_CERT_PATH', '')
if cert_path == '':
cert_path = os.path.join(os.environ.get('HOME', ''), '.docker')... | python | def docker_client():
"""
Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client.
"""
cert_path = os.environ.get('DOCKER_CERT_PATH', '')
if cert_path == '':
cert_path = os.path.join(os.environ.get('HOME', ''), '.docker')... | [
"def",
"docker_client",
"(",
")",
":",
"cert_path",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'DOCKER_CERT_PATH'",
",",
"''",
")",
"if",
"cert_path",
"==",
"''",
":",
"cert_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"environ",
"."... | Returns a docker-py client configured using environment variables
according to the same logic as the official Docker client. | [
"Returns",
"a",
"docker",
"-",
"py",
"client",
"configured",
"using",
"environment",
"variables",
"according",
"to",
"the",
"same",
"logic",
"as",
"the",
"official",
"Docker",
"client",
"."
] | f375be2a06f9c67eaae3ce6f605195dbca143b2b | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/dev_tools/docker/scripts/share_etc_hosts.py#L44-L75 |
8,004 | crs4/pydoop | pydoop/utils/jvm.py | get_java_home | def get_java_home():
"""\
Try getting JAVA_HOME from system properties.
We are interested in the JDK home, containing include/jni.h, while the
java.home property points to the JRE home. If a JDK is installed, however,
the two are (usually) related: the JDK home is either the same directory
as t... | python | def get_java_home():
"""\
Try getting JAVA_HOME from system properties.
We are interested in the JDK home, containing include/jni.h, while the
java.home property points to the JRE home. If a JDK is installed, however,
the two are (usually) related: the JDK home is either the same directory
as t... | [
"def",
"get_java_home",
"(",
")",
":",
"error",
"=",
"RuntimeError",
"(",
"\"java home not found, try setting JAVA_HOME\"",
")",
"try",
":",
"return",
"os",
".",
"environ",
"[",
"\"JAVA_HOME\"",
"]",
"except",
"KeyError",
":",
"wd",
"=",
"tempfile",
".",
"mkdtem... | \
Try getting JAVA_HOME from system properties.
We are interested in the JDK home, containing include/jni.h, while the
java.home property points to the JRE home. If a JDK is installed, however,
the two are (usually) related: the JDK home is either the same directory
as the JRE home (recent java ver... | [
"\\",
"Try",
"getting",
"JAVA_HOME",
"from",
"system",
"properties",
"."
] | f375be2a06f9c67eaae3ce6f605195dbca143b2b | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/utils/jvm.py#L37-L71 |
8,005 | crs4/pydoop | pydoop/mapreduce/pipes.py | run_task | def run_task(factory, **kwargs):
"""\
Run a MapReduce task.
Available keyword arguments:
* ``raw_keys`` (default: :obj:`False`): pass map input keys to context
as byte strings (ignore any type information)
* ``raw_values`` (default: :obj:`False`): pass map input values to context
as by... | python | def run_task(factory, **kwargs):
"""\
Run a MapReduce task.
Available keyword arguments:
* ``raw_keys`` (default: :obj:`False`): pass map input keys to context
as byte strings (ignore any type information)
* ``raw_values`` (default: :obj:`False`): pass map input values to context
as by... | [
"def",
"run_task",
"(",
"factory",
",",
"*",
"*",
"kwargs",
")",
":",
"context",
"=",
"TaskContext",
"(",
"factory",
",",
"*",
"*",
"kwargs",
")",
"pstats_dir",
"=",
"kwargs",
".",
"get",
"(",
"\"pstats_dir\"",
",",
"os",
".",
"getenv",
"(",
"PSTATS_DI... | \
Run a MapReduce task.
Available keyword arguments:
* ``raw_keys`` (default: :obj:`False`): pass map input keys to context
as byte strings (ignore any type information)
* ``raw_values`` (default: :obj:`False`): pass map input values to context
as byte strings (ignore any type information)... | [
"\\",
"Run",
"a",
"MapReduce",
"task",
"."
] | f375be2a06f9c67eaae3ce6f605195dbca143b2b | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/mapreduce/pipes.py#L414-L462 |
8,006 | crs4/pydoop | pydoop/mapreduce/pipes.py | TaskContext.progress | def progress(self):
"""\
Report progress to the Java side.
This needs to flush the uplink stream, but too many flushes can
disrupt performance, so we actually talk to upstream once per second.
"""
now = time()
if now - self.last_progress_t > 1:
self.l... | python | def progress(self):
"""\
Report progress to the Java side.
This needs to flush the uplink stream, but too many flushes can
disrupt performance, so we actually talk to upstream once per second.
"""
now = time()
if now - self.last_progress_t > 1:
self.l... | [
"def",
"progress",
"(",
"self",
")",
":",
"now",
"=",
"time",
"(",
")",
"if",
"now",
"-",
"self",
".",
"last_progress_t",
">",
"1",
":",
"self",
".",
"last_progress_t",
"=",
"now",
"if",
"self",
".",
"status",
":",
"self",
".",
"uplink",
".",
"stat... | \
Report progress to the Java side.
This needs to flush the uplink stream, but too many flushes can
disrupt performance, so we actually talk to upstream once per second. | [
"\\",
"Report",
"progress",
"to",
"the",
"Java",
"side",
"."
] | f375be2a06f9c67eaae3ce6f605195dbca143b2b | https://github.com/crs4/pydoop/blob/f375be2a06f9c67eaae3ce6f605195dbca143b2b/pydoop/mapreduce/pipes.py#L210-L225 |
8,007 | Bouke/docx-mailmerge | mailmerge.py | MailMerge.merge_pages | def merge_pages(self, replacements):
"""
Deprecated method.
"""
warnings.warn("merge_pages has been deprecated in favour of merge_templates",
category=DeprecationWarning,
stacklevel=2)
self.merge_templates(replacements, "p... | python | def merge_pages(self, replacements):
"""
Deprecated method.
"""
warnings.warn("merge_pages has been deprecated in favour of merge_templates",
category=DeprecationWarning,
stacklevel=2)
self.merge_templates(replacements, "p... | [
"def",
"merge_pages",
"(",
"self",
",",
"replacements",
")",
":",
"warnings",
".",
"warn",
"(",
"\"merge_pages has been deprecated in favour of merge_templates\"",
",",
"category",
"=",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"self",
".",
"merge_templa... | Deprecated method. | [
"Deprecated",
"method",
"."
] | 6900b686794b4bf85b662488add8df0880114b99 | https://github.com/Bouke/docx-mailmerge/blob/6900b686794b4bf85b662488add8df0880114b99/mailmerge.py#L236-L243 |
8,008 | bashu/django-easy-maps | easy_maps/utils.py | importpath | def importpath(path, error_text=None):
"""
Import value by specified ``path``.
Value can represent module, class, object, attribute or method.
If ``error_text`` is not None and import will
raise ImproperlyConfigured with user friendly text.
"""
result = None
attrs = []
parts = path.... | python | def importpath(path, error_text=None):
"""
Import value by specified ``path``.
Value can represent module, class, object, attribute or method.
If ``error_text`` is not None and import will
raise ImproperlyConfigured with user friendly text.
"""
result = None
attrs = []
parts = path.... | [
"def",
"importpath",
"(",
"path",
",",
"error_text",
"=",
"None",
")",
":",
"result",
"=",
"None",
"attrs",
"=",
"[",
"]",
"parts",
"=",
"path",
".",
"split",
"(",
"'.'",
")",
"exception",
"=",
"None",
"while",
"parts",
":",
"try",
":",
"result",
"... | Import value by specified ``path``.
Value can represent module, class, object, attribute or method.
If ``error_text`` is not None and import will
raise ImproperlyConfigured with user friendly text. | [
"Import",
"value",
"by",
"specified",
"path",
".",
"Value",
"can",
"represent",
"module",
"class",
"object",
"attribute",
"or",
"method",
".",
"If",
"error_text",
"is",
"not",
"None",
"and",
"import",
"will",
"raise",
"ImproperlyConfigured",
"with",
"user",
"f... | 32f4f3274443219e8828d93d09a406bf2a126982 | https://github.com/bashu/django-easy-maps/blob/32f4f3274443219e8828d93d09a406bf2a126982/easy_maps/utils.py#L6-L37 |
8,009 | bitlabstudio/django-booking | booking/utils.py | get_booking | def get_booking(request):
"""
Returns the booking that is in progress for the current user or None
We assume that a user can only have one booking that is in-progress.
TODO: This implementation assumes that there is a status called
'inprogress' and that there should only be one such booking for a ... | python | def get_booking(request):
"""
Returns the booking that is in progress for the current user or None
We assume that a user can only have one booking that is in-progress.
TODO: This implementation assumes that there is a status called
'inprogress' and that there should only be one such booking for a ... | [
"def",
"get_booking",
"(",
"request",
")",
":",
"booking",
"=",
"None",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"try",
":",
"booking",
"=",
"Booking",
".",
"objects",
".",
"get",
"(",
"user",
"=",
"request",
".",
"user",
... | Returns the booking that is in progress for the current user or None
We assume that a user can only have one booking that is in-progress.
TODO: This implementation assumes that there is a status called
'inprogress' and that there should only be one such booking for a given
user. We need to see if this... | [
"Returns",
"the",
"booking",
"that",
"is",
"in",
"progress",
"for",
"the",
"current",
"user",
"or",
"None"
] | 7bb5fdddb28b52b62b86f1d05b19a7654b5ffe00 | https://github.com/bitlabstudio/django-booking/blob/7bb5fdddb28b52b62b86f1d05b19a7654b5ffe00/booking/utils.py#L7-L37 |
8,010 | bitlabstudio/django-booking | booking/utils.py | persist_booking | def persist_booking(booking, user):
"""
Ties an in-progress booking from a session to a user when the user logs in.
If we don't do this, the booking will be lost, because on a login, the
old session will be deleted and a new one will be created. Since the
booking has a FK to the session, it would b... | python | def persist_booking(booking, user):
"""
Ties an in-progress booking from a session to a user when the user logs in.
If we don't do this, the booking will be lost, because on a login, the
old session will be deleted and a new one will be created. Since the
booking has a FK to the session, it would b... | [
"def",
"persist_booking",
"(",
"booking",
",",
"user",
")",
":",
"if",
"booking",
"is",
"not",
"None",
":",
"existing_bookings",
"=",
"Booking",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
",",
"booking_status__slug",
"=",
"'inprogress'",
")",
... | Ties an in-progress booking from a session to a user when the user logs in.
If we don't do this, the booking will be lost, because on a login, the
old session will be deleted and a new one will be created. Since the
booking has a FK to the session, it would be deleted as well when the user
logs in.
... | [
"Ties",
"an",
"in",
"-",
"progress",
"booking",
"from",
"a",
"session",
"to",
"a",
"user",
"when",
"the",
"user",
"logs",
"in",
"."
] | 7bb5fdddb28b52b62b86f1d05b19a7654b5ffe00 | https://github.com/bitlabstudio/django-booking/blob/7bb5fdddb28b52b62b86f1d05b19a7654b5ffe00/booking/utils.py#L40-L68 |
8,011 | spotify/pyfg | pyFG/forticonfig.py | FortiConfig.compare_config | def compare_config(self, target, init=True, indent_level=0):
"""
This method will return all the necessary commands to get from the config we are in to the target
config.
Args:
* **target** (:class:`~pyFG.forticonfig.FortiConfig`) - Target config.
* **init** (boo... | python | def compare_config(self, target, init=True, indent_level=0):
"""
This method will return all the necessary commands to get from the config we are in to the target
config.
Args:
* **target** (:class:`~pyFG.forticonfig.FortiConfig`) - Target config.
* **init** (boo... | [
"def",
"compare_config",
"(",
"self",
",",
"target",
",",
"init",
"=",
"True",
",",
"indent_level",
"=",
"0",
")",
":",
"if",
"init",
":",
"fwd",
"=",
"self",
".",
"full_path_fwd",
"bwd",
"=",
"self",
".",
"full_path_bwd",
"else",
":",
"fwd",
"=",
"s... | This method will return all the necessary commands to get from the config we are in to the target
config.
Args:
* **target** (:class:`~pyFG.forticonfig.FortiConfig`) - Target config.
* **init** (bool) - This tells to the method if this is the first call to the method or if we ar... | [
"This",
"method",
"will",
"return",
"all",
"the",
"necessary",
"commands",
"to",
"get",
"from",
"the",
"config",
"we",
"are",
"in",
"to",
"the",
"target",
"config",
"."
] | 518668539146e7f998a37d75994a4278adf79897 | https://github.com/spotify/pyfg/blob/518668539146e7f998a37d75994a4278adf79897/pyFG/forticonfig.py#L103-L173 |
8,012 | spotify/pyfg | pyFG/forticonfig.py | FortiConfig.to_text | def to_text(self, relative=False, indent_level=0, clean_empty_block=False):
"""
This method returns the object model in text format. You should be able to copy&paste this text into any
device running a supported version of FortiOS.
Args:
- **relative** (bool):
... | python | def to_text(self, relative=False, indent_level=0, clean_empty_block=False):
"""
This method returns the object model in text format. You should be able to copy&paste this text into any
device running a supported version of FortiOS.
Args:
- **relative** (bool):
... | [
"def",
"to_text",
"(",
"self",
",",
"relative",
"=",
"False",
",",
"indent_level",
"=",
"0",
",",
"clean_empty_block",
"=",
"False",
")",
":",
"if",
"relative",
":",
"fwd",
"=",
"self",
".",
"rel_path_fwd",
"bwd",
"=",
"self",
".",
"rel_path_bwd",
"else"... | This method returns the object model in text format. You should be able to copy&paste this text into any
device running a supported version of FortiOS.
Args:
- **relative** (bool):
* If ``True`` the text returned will assume that you are one block away
* If ... | [
"This",
"method",
"returns",
"the",
"object",
"model",
"in",
"text",
"format",
".",
"You",
"should",
"be",
"able",
"to",
"copy&paste",
"this",
"text",
"into",
"any",
"device",
"running",
"a",
"supported",
"version",
"of",
"FortiOS",
"."
] | 518668539146e7f998a37d75994a4278adf79897 | https://github.com/spotify/pyfg/blob/518668539146e7f998a37d75994a4278adf79897/pyFG/forticonfig.py#L305-L341 |
8,013 | spotify/pyfg | pyFG/fortios.py | FortiOS.open | def open(self):
"""
Opens the ssh session with the device.
"""
logger.debug('Connecting to device %s, vdom %s' % (self.hostname, self.vdom))
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
cfg = {
'host... | python | def open(self):
"""
Opens the ssh session with the device.
"""
logger.debug('Connecting to device %s, vdom %s' % (self.hostname, self.vdom))
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
cfg = {
'host... | [
"def",
"open",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'Connecting to device %s, vdom %s'",
"%",
"(",
"self",
".",
"hostname",
",",
"self",
".",
"vdom",
")",
")",
"self",
".",
"ssh",
"=",
"paramiko",
".",
"SSHClient",
"(",
")",
"self",
"."... | Opens the ssh session with the device. | [
"Opens",
"the",
"ssh",
"session",
"with",
"the",
"device",
"."
] | 518668539146e7f998a37d75994a4278adf79897 | https://github.com/spotify/pyfg/blob/518668539146e7f998a37d75994a4278adf79897/pyFG/fortios.py#L68-L103 |
8,014 | spotify/pyfg | pyFG/fortios.py | FortiOS._read_wrapper | def _read_wrapper(data):
"""Ensure unicode always returned on read."""
# Paramiko (strangely) in PY3 returns an int here.
if isinstance(data, int):
data = chr(data)
# Ensure unicode
return py23_compat.text_type(data) | python | def _read_wrapper(data):
"""Ensure unicode always returned on read."""
# Paramiko (strangely) in PY3 returns an int here.
if isinstance(data, int):
data = chr(data)
# Ensure unicode
return py23_compat.text_type(data) | [
"def",
"_read_wrapper",
"(",
"data",
")",
":",
"# Paramiko (strangely) in PY3 returns an int here.",
"if",
"isinstance",
"(",
"data",
",",
"int",
")",
":",
"data",
"=",
"chr",
"(",
"data",
")",
"# Ensure unicode",
"return",
"py23_compat",
".",
"text_type",
"(",
... | Ensure unicode always returned on read. | [
"Ensure",
"unicode",
"always",
"returned",
"on",
"read",
"."
] | 518668539146e7f998a37d75994a4278adf79897 | https://github.com/spotify/pyfg/blob/518668539146e7f998a37d75994a4278adf79897/pyFG/fortios.py#L114-L120 |
8,015 | spotify/pyfg | pyFG/fortios.py | FortiOS._parse_batch_lastlog | def _parse_batch_lastlog(last_log):
"""
This static method will help reading the result of the commit, command by command.
Args:
last_log(list): A list containing, line by line, the result of committing the changes.
Returns:
A list of tuples that went wrong. The... | python | def _parse_batch_lastlog(last_log):
"""
This static method will help reading the result of the commit, command by command.
Args:
last_log(list): A list containing, line by line, the result of committing the changes.
Returns:
A list of tuples that went wrong. The... | [
"def",
"_parse_batch_lastlog",
"(",
"last_log",
")",
":",
"regexp",
"=",
"re",
".",
"compile",
"(",
"'(-?[0-9]\\d*):\\W+(.*)'",
")",
"wrong_commands",
"=",
"list",
"(",
")",
"for",
"line",
"in",
"last_log",
":",
"result",
"=",
"regexp",
".",
"match",
"(",
... | This static method will help reading the result of the commit, command by command.
Args:
last_log(list): A list containing, line by line, the result of committing the changes.
Returns:
A list of tuples that went wrong. The tuple will contain (*status_code*, *command*) | [
"This",
"static",
"method",
"will",
"help",
"reading",
"the",
"result",
"of",
"the",
"commit",
"command",
"by",
"command",
"."
] | 518668539146e7f998a37d75994a4278adf79897 | https://github.com/spotify/pyfg/blob/518668539146e7f998a37d75994a4278adf79897/pyFG/fortios.py#L349-L370 |
8,016 | spotify/pyfg | pyFG/fortios.py | FortiOS._reload_config | def _reload_config(self, reload_original_config):
"""
This command will update the running config from the live device.
Args:
* reload_original_config:
* If ``True`` the original config will be loaded with the running config before reloading the\
orig... | python | def _reload_config(self, reload_original_config):
"""
This command will update the running config from the live device.
Args:
* reload_original_config:
* If ``True`` the original config will be loaded with the running config before reloading the\
orig... | [
"def",
"_reload_config",
"(",
"self",
",",
"reload_original_config",
")",
":",
"# We don't want to reload the config under some circumstances",
"if",
"reload_original_config",
":",
"self",
".",
"original_config",
"=",
"self",
".",
"running_config",
"self",
".",
"original_co... | This command will update the running config from the live device.
Args:
* reload_original_config:
* If ``True`` the original config will be loaded with the running config before reloading the\
original config.
* If ``False`` the original config will r... | [
"This",
"command",
"will",
"update",
"the",
"running",
"config",
"from",
"the",
"live",
"device",
"."
] | 518668539146e7f998a37d75994a4278adf79897 | https://github.com/spotify/pyfg/blob/518668539146e7f998a37d75994a4278adf79897/pyFG/fortios.py#L372-L392 |
8,017 | mattjj/pyslds | pyslds/states.py | _SLDSStates.generate_states | def generate_states(self, initial_condition=None, with_noise=True, stateseq=None):
"""
Jointly sample the discrete and continuous states
"""
from pybasicbayes.util.stats import sample_discrete
# Generate from the prior and raise exception if unstable
T, K, n = self.T, sel... | python | def generate_states(self, initial_condition=None, with_noise=True, stateseq=None):
"""
Jointly sample the discrete and continuous states
"""
from pybasicbayes.util.stats import sample_discrete
# Generate from the prior and raise exception if unstable
T, K, n = self.T, sel... | [
"def",
"generate_states",
"(",
"self",
",",
"initial_condition",
"=",
"None",
",",
"with_noise",
"=",
"True",
",",
"stateseq",
"=",
"None",
")",
":",
"from",
"pybasicbayes",
".",
"util",
".",
"stats",
"import",
"sample_discrete",
"# Generate from the prior and rai... | Jointly sample the discrete and continuous states | [
"Jointly",
"sample",
"the",
"discrete",
"and",
"continuous",
"states"
] | c505c2bd05a5549d450b518f02493b68ed12e590 | https://github.com/mattjj/pyslds/blob/c505c2bd05a5549d450b518f02493b68ed12e590/pyslds/states.py#L35-L78 |
8,018 | mattjj/pyslds | pyslds/states.py | _SLDSStatesMaskedData.heldout_log_likelihood | def heldout_log_likelihood(self, test_mask=None):
"""
Compute the log likelihood of the masked data given the latent
discrete and continuous states.
"""
if test_mask is None:
# If a test mask is not supplied, use the negation of this object's mask
if self.... | python | def heldout_log_likelihood(self, test_mask=None):
"""
Compute the log likelihood of the masked data given the latent
discrete and continuous states.
"""
if test_mask is None:
# If a test mask is not supplied, use the negation of this object's mask
if self.... | [
"def",
"heldout_log_likelihood",
"(",
"self",
",",
"test_mask",
"=",
"None",
")",
":",
"if",
"test_mask",
"is",
"None",
":",
"# If a test mask is not supplied, use the negation of this object's mask",
"if",
"self",
".",
"mask",
"is",
"None",
":",
"return",
"0",
"els... | Compute the log likelihood of the masked data given the latent
discrete and continuous states. | [
"Compute",
"the",
"log",
"likelihood",
"of",
"the",
"masked",
"data",
"given",
"the",
"latent",
"discrete",
"and",
"continuous",
"states",
"."
] | c505c2bd05a5549d450b518f02493b68ed12e590 | https://github.com/mattjj/pyslds/blob/c505c2bd05a5549d450b518f02493b68ed12e590/pyslds/states.py#L853-L874 |
8,019 | mattjj/pyslds | pyslds/states.py | _SLDSStatesCountData.empirical_rate | def empirical_rate(data, sigma=3.0):
"""
Smooth count data to get an empirical rate
"""
from scipy.ndimage.filters import gaussian_filter1d
return 0.001 + gaussian_filter1d(data.astype(np.float), sigma, axis=0) | python | def empirical_rate(data, sigma=3.0):
"""
Smooth count data to get an empirical rate
"""
from scipy.ndimage.filters import gaussian_filter1d
return 0.001 + gaussian_filter1d(data.astype(np.float), sigma, axis=0) | [
"def",
"empirical_rate",
"(",
"data",
",",
"sigma",
"=",
"3.0",
")",
":",
"from",
"scipy",
".",
"ndimage",
".",
"filters",
"import",
"gaussian_filter1d",
"return",
"0.001",
"+",
"gaussian_filter1d",
"(",
"data",
".",
"astype",
"(",
"np",
".",
"float",
")",... | Smooth count data to get an empirical rate | [
"Smooth",
"count",
"data",
"to",
"get",
"an",
"empirical",
"rate"
] | c505c2bd05a5549d450b518f02493b68ed12e590 | https://github.com/mattjj/pyslds/blob/c505c2bd05a5549d450b518f02493b68ed12e590/pyslds/states.py#L1251-L1256 |
8,020 | mattjj/pyslds | pyslds/util.py | get_empirical_ar_params | def get_empirical_ar_params(train_datas, params):
"""
Estimate the parameters of an AR observation model
by fitting a single AR model to the entire dataset.
"""
assert isinstance(train_datas, list) and len(train_datas) > 0
datadimension = train_datas[0].shape[1]
assert params["nu_0"] > datad... | python | def get_empirical_ar_params(train_datas, params):
"""
Estimate the parameters of an AR observation model
by fitting a single AR model to the entire dataset.
"""
assert isinstance(train_datas, list) and len(train_datas) > 0
datadimension = train_datas[0].shape[1]
assert params["nu_0"] > datad... | [
"def",
"get_empirical_ar_params",
"(",
"train_datas",
",",
"params",
")",
":",
"assert",
"isinstance",
"(",
"train_datas",
",",
"list",
")",
"and",
"len",
"(",
"train_datas",
")",
">",
"0",
"datadimension",
"=",
"train_datas",
"[",
"0",
"]",
".",
"shape",
... | Estimate the parameters of an AR observation model
by fitting a single AR model to the entire dataset. | [
"Estimate",
"the",
"parameters",
"of",
"an",
"AR",
"observation",
"model",
"by",
"fitting",
"a",
"single",
"AR",
"model",
"to",
"the",
"entire",
"dataset",
"."
] | c505c2bd05a5549d450b518f02493b68ed12e590 | https://github.com/mattjj/pyslds/blob/c505c2bd05a5549d450b518f02493b68ed12e590/pyslds/util.py#L6-L32 |
8,021 | pastpages/savepagenow | savepagenow/api.py | capture | def capture(
target_url,
user_agent="savepagenow (https://github.com/pastpages/savepagenow)",
accept_cache=False
):
"""
Archives the provided URL using archive.org's Wayback Machine.
Returns the archive.org URL where the capture is stored.
Raises a CachedPage exception if archive.org decli... | python | def capture(
target_url,
user_agent="savepagenow (https://github.com/pastpages/savepagenow)",
accept_cache=False
):
"""
Archives the provided URL using archive.org's Wayback Machine.
Returns the archive.org URL where the capture is stored.
Raises a CachedPage exception if archive.org decli... | [
"def",
"capture",
"(",
"target_url",
",",
"user_agent",
"=",
"\"savepagenow (https://github.com/pastpages/savepagenow)\"",
",",
"accept_cache",
"=",
"False",
")",
":",
"# Put together the URL that will save our request",
"domain",
"=",
"\"https://web.archive.org\"",
"save_url",
... | Archives the provided URL using archive.org's Wayback Machine.
Returns the archive.org URL where the capture is stored.
Raises a CachedPage exception if archive.org declines to conduct a new
capture and returns a previous snapshot instead.
To silence that exception, pass into True to the ``accept_cac... | [
"Archives",
"the",
"provided",
"URL",
"using",
"archive",
".",
"org",
"s",
"Wayback",
"Machine",
"."
] | 9555ffb10905fe1b0d2452be2bd8a7d4338a8379 | https://github.com/pastpages/savepagenow/blob/9555ffb10905fe1b0d2452be2bd8a7d4338a8379/savepagenow/api.py#L8-L65 |
8,022 | pastpages/savepagenow | savepagenow/api.py | capture_or_cache | def capture_or_cache(
target_url,
user_agent="savepagenow (https://github.com/pastpages/savepagenow)"
):
"""
Archives the provided URL using archive.org's Wayback Machine, unless
the page has been recently captured.
Returns a tuple with the archive.org URL where the capture is stored,
along... | python | def capture_or_cache(
target_url,
user_agent="savepagenow (https://github.com/pastpages/savepagenow)"
):
"""
Archives the provided URL using archive.org's Wayback Machine, unless
the page has been recently captured.
Returns a tuple with the archive.org URL where the capture is stored,
along... | [
"def",
"capture_or_cache",
"(",
"target_url",
",",
"user_agent",
"=",
"\"savepagenow (https://github.com/pastpages/savepagenow)\"",
")",
":",
"try",
":",
"return",
"capture",
"(",
"target_url",
",",
"user_agent",
"=",
"user_agent",
",",
"accept_cache",
"=",
"False",
"... | Archives the provided URL using archive.org's Wayback Machine, unless
the page has been recently captured.
Returns a tuple with the archive.org URL where the capture is stored,
along with a boolean indicating if a new capture was conducted.
If the boolean is True, archive.org conducted a new capture. ... | [
"Archives",
"the",
"provided",
"URL",
"using",
"archive",
".",
"org",
"s",
"Wayback",
"Machine",
"unless",
"the",
"page",
"has",
"been",
"recently",
"captured",
"."
] | 9555ffb10905fe1b0d2452be2bd8a7d4338a8379 | https://github.com/pastpages/savepagenow/blob/9555ffb10905fe1b0d2452be2bd8a7d4338a8379/savepagenow/api.py#L68-L86 |
8,023 | quandyfactory/dicttoxml | dicttoxml.py | get_unique_id | def get_unique_id(element):
"""Returns a unique id for a given element"""
this_id = make_id(element)
dup = True
while dup:
if this_id not in ids:
dup = False
ids.append(this_id)
else:
this_id = make_id(element)
return ids[-1] | python | def get_unique_id(element):
"""Returns a unique id for a given element"""
this_id = make_id(element)
dup = True
while dup:
if this_id not in ids:
dup = False
ids.append(this_id)
else:
this_id = make_id(element)
return ids[-1] | [
"def",
"get_unique_id",
"(",
"element",
")",
":",
"this_id",
"=",
"make_id",
"(",
"element",
")",
"dup",
"=",
"True",
"while",
"dup",
":",
"if",
"this_id",
"not",
"in",
"ids",
":",
"dup",
"=",
"False",
"ids",
".",
"append",
"(",
"this_id",
")",
"else... | Returns a unique id for a given element | [
"Returns",
"a",
"unique",
"id",
"for",
"a",
"given",
"element"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L70-L80 |
8,024 | quandyfactory/dicttoxml | dicttoxml.py | get_xml_type | def get_xml_type(val):
"""Returns the data type for the xml type attribute"""
if type(val).__name__ in ('str', 'unicode'):
return 'str'
if type(val).__name__ in ('int', 'long'):
return 'int'
if type(val).__name__ == 'float':
return 'float'
if type(val).__name__ == 'bool':
... | python | def get_xml_type(val):
"""Returns the data type for the xml type attribute"""
if type(val).__name__ in ('str', 'unicode'):
return 'str'
if type(val).__name__ in ('int', 'long'):
return 'int'
if type(val).__name__ == 'float':
return 'float'
if type(val).__name__ == 'bool':
... | [
"def",
"get_xml_type",
"(",
"val",
")",
":",
"if",
"type",
"(",
"val",
")",
".",
"__name__",
"in",
"(",
"'str'",
",",
"'unicode'",
")",
":",
"return",
"'str'",
"if",
"type",
"(",
"val",
")",
".",
"__name__",
"in",
"(",
"'int'",
",",
"'long'",
")",
... | Returns the data type for the xml type attribute | [
"Returns",
"the",
"data",
"type",
"for",
"the",
"xml",
"type",
"attribute"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L83-L101 |
8,025 | quandyfactory/dicttoxml | dicttoxml.py | make_attrstring | def make_attrstring(attr):
"""Returns an attribute string in the form key="val" """
attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in attr.items()])
return '%s%s' % (' ' if attrstring != '' else '', attrstring) | python | def make_attrstring(attr):
"""Returns an attribute string in the form key="val" """
attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in attr.items()])
return '%s%s' % (' ' if attrstring != '' else '', attrstring) | [
"def",
"make_attrstring",
"(",
"attr",
")",
":",
"attrstring",
"=",
"' '",
".",
"join",
"(",
"[",
"'%s=\"%s\"'",
"%",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"attr",
".",
"items",
"(",
")",
"]",
")",
"return",
"'%s%s'",
"%",
"(",
"... | Returns an attribute string in the form key="val" | [
"Returns",
"an",
"attribute",
"string",
"in",
"the",
"form",
"key",
"=",
"val"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L115-L118 |
8,026 | quandyfactory/dicttoxml | dicttoxml.py | key_is_valid_xml | def key_is_valid_xml(key):
"""Checks that a key is a valid XML name"""
LOG.info('Inside key_is_valid_xml(). Testing "%s"' % (unicode_me(key)))
test_xml = '<?xml version="1.0" encoding="UTF-8" ?><%s>foo</%s>' % (key, key)
try:
parseString(test_xml)
return True
except Exception: # mini... | python | def key_is_valid_xml(key):
"""Checks that a key is a valid XML name"""
LOG.info('Inside key_is_valid_xml(). Testing "%s"' % (unicode_me(key)))
test_xml = '<?xml version="1.0" encoding="UTF-8" ?><%s>foo</%s>' % (key, key)
try:
parseString(test_xml)
return True
except Exception: # mini... | [
"def",
"key_is_valid_xml",
"(",
"key",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside key_is_valid_xml(). Testing \"%s\"'",
"%",
"(",
"unicode_me",
"(",
"key",
")",
")",
")",
"test_xml",
"=",
"'<?xml version=\"1.0\" encoding=\"UTF-8\" ?><%s>foo</%s>'",
"%",
"(",
"key",
... | Checks that a key is a valid XML name | [
"Checks",
"that",
"a",
"key",
"is",
"a",
"valid",
"XML",
"name"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L121-L129 |
8,027 | quandyfactory/dicttoxml | dicttoxml.py | make_valid_xml_name | def make_valid_xml_name(key, attr):
"""Tests an XML name and fixes it if invalid"""
LOG.info('Inside make_valid_xml_name(). Testing key "%s" with attr "%s"' % (
unicode_me(key), unicode_me(attr))
)
key = escape_xml(key)
attr = escape_xml(attr)
# pass through if key is already valid
... | python | def make_valid_xml_name(key, attr):
"""Tests an XML name and fixes it if invalid"""
LOG.info('Inside make_valid_xml_name(). Testing key "%s" with attr "%s"' % (
unicode_me(key), unicode_me(attr))
)
key = escape_xml(key)
attr = escape_xml(attr)
# pass through if key is already valid
... | [
"def",
"make_valid_xml_name",
"(",
"key",
",",
"attr",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside make_valid_xml_name(). Testing key \"%s\" with attr \"%s\"'",
"%",
"(",
"unicode_me",
"(",
"key",
")",
",",
"unicode_me",
"(",
"attr",
")",
")",
")",
"key",
"=",
... | Tests an XML name and fixes it if invalid | [
"Tests",
"an",
"XML",
"name",
"and",
"fixes",
"it",
"if",
"invalid"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L132-L155 |
8,028 | quandyfactory/dicttoxml | dicttoxml.py | convert | def convert(obj, ids, attr_type, item_func, cdata, parent='root'):
"""Routes the elements of an object to the right function to convert them
based on their data type"""
LOG.info('Inside convert(). obj type is: "%s", obj="%s"' % (type(obj).__name__, unicode_me(obj)))
item_name = item_func(pare... | python | def convert(obj, ids, attr_type, item_func, cdata, parent='root'):
"""Routes the elements of an object to the right function to convert them
based on their data type"""
LOG.info('Inside convert(). obj type is: "%s", obj="%s"' % (type(obj).__name__, unicode_me(obj)))
item_name = item_func(pare... | [
"def",
"convert",
"(",
"obj",
",",
"ids",
",",
"attr_type",
",",
"item_func",
",",
"cdata",
",",
"parent",
"=",
"'root'",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside convert(). obj type is: \"%s\", obj=\"%s\"'",
"%",
"(",
"type",
"(",
"obj",
")",
".",
"__n... | Routes the elements of an object to the right function to convert them
based on their data type | [
"Routes",
"the",
"elements",
"of",
"an",
"object",
"to",
"the",
"right",
"function",
"to",
"convert",
"them",
"based",
"on",
"their",
"data",
"type"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L168-L194 |
8,029 | quandyfactory/dicttoxml | dicttoxml.py | convert_dict | def convert_dict(obj, ids, parent, attr_type, item_func, cdata):
"""Converts a dict into an XML string."""
LOG.info('Inside convert_dict(): obj type is: "%s", obj="%s"' % (
type(obj).__name__, unicode_me(obj))
)
output = []
addline = output.append
item_name = item_func(parent)
... | python | def convert_dict(obj, ids, parent, attr_type, item_func, cdata):
"""Converts a dict into an XML string."""
LOG.info('Inside convert_dict(): obj type is: "%s", obj="%s"' % (
type(obj).__name__, unicode_me(obj))
)
output = []
addline = output.append
item_name = item_func(parent)
... | [
"def",
"convert_dict",
"(",
"obj",
",",
"ids",
",",
"parent",
",",
"attr_type",
",",
"item_func",
",",
"cdata",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside convert_dict(): obj type is: \"%s\", obj=\"%s\"'",
"%",
"(",
"type",
"(",
"obj",
")",
".",
"__name__",
... | Converts a dict into an XML string. | [
"Converts",
"a",
"dict",
"into",
"an",
"XML",
"string",
"."
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L197-L254 |
8,030 | quandyfactory/dicttoxml | dicttoxml.py | convert_list | def convert_list(items, ids, parent, attr_type, item_func, cdata):
"""Converts a list into an XML string."""
LOG.info('Inside convert_list()')
output = []
addline = output.append
item_name = item_func(parent)
if ids:
this_id = get_unique_id(parent)
for i, item in enumerate(items):... | python | def convert_list(items, ids, parent, attr_type, item_func, cdata):
"""Converts a list into an XML string."""
LOG.info('Inside convert_list()')
output = []
addline = output.append
item_name = item_func(parent)
if ids:
this_id = get_unique_id(parent)
for i, item in enumerate(items):... | [
"def",
"convert_list",
"(",
"items",
",",
"ids",
",",
"parent",
",",
"attr_type",
",",
"item_func",
",",
"cdata",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside convert_list()'",
")",
"output",
"=",
"[",
"]",
"addline",
"=",
"output",
".",
"append",
"item_n... | Converts a list into an XML string. | [
"Converts",
"a",
"list",
"into",
"an",
"XML",
"string",
"."
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L257-L321 |
8,031 | quandyfactory/dicttoxml | dicttoxml.py | convert_kv | def convert_kv(key, val, attr_type, attr={}, cdata=False):
"""Converts a number or string into an XML element"""
LOG.info('Inside convert_kv(): key="%s", val="%s", type(val) is: "%s"' % (
unicode_me(key), unicode_me(val), type(val).__name__)
)
key, attr = make_valid_xml_name(key, attr)
if ... | python | def convert_kv(key, val, attr_type, attr={}, cdata=False):
"""Converts a number or string into an XML element"""
LOG.info('Inside convert_kv(): key="%s", val="%s", type(val) is: "%s"' % (
unicode_me(key), unicode_me(val), type(val).__name__)
)
key, attr = make_valid_xml_name(key, attr)
if ... | [
"def",
"convert_kv",
"(",
"key",
",",
"val",
",",
"attr_type",
",",
"attr",
"=",
"{",
"}",
",",
"cdata",
"=",
"False",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside convert_kv(): key=\"%s\", val=\"%s\", type(val) is: \"%s\"'",
"%",
"(",
"unicode_me",
"(",
"key",... | Converts a number or string into an XML element | [
"Converts",
"a",
"number",
"or",
"string",
"into",
"an",
"XML",
"element"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L324-L339 |
8,032 | quandyfactory/dicttoxml | dicttoxml.py | convert_bool | def convert_bool(key, val, attr_type, attr={}, cdata=False):
"""Converts a boolean into an XML element"""
LOG.info('Inside convert_bool(): key="%s", val="%s", type(val) is: "%s"' % (
unicode_me(key), unicode_me(val), type(val).__name__)
)
key, attr = make_valid_xml_name(key, attr)
if attr_... | python | def convert_bool(key, val, attr_type, attr={}, cdata=False):
"""Converts a boolean into an XML element"""
LOG.info('Inside convert_bool(): key="%s", val="%s", type(val) is: "%s"' % (
unicode_me(key), unicode_me(val), type(val).__name__)
)
key, attr = make_valid_xml_name(key, attr)
if attr_... | [
"def",
"convert_bool",
"(",
"key",
",",
"val",
",",
"attr_type",
",",
"attr",
"=",
"{",
"}",
",",
"cdata",
"=",
"False",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside convert_bool(): key=\"%s\", val=\"%s\", type(val) is: \"%s\"'",
"%",
"(",
"unicode_me",
"(",
"k... | Converts a boolean into an XML element | [
"Converts",
"a",
"boolean",
"into",
"an",
"XML",
"element"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L342-L353 |
8,033 | quandyfactory/dicttoxml | dicttoxml.py | convert_none | def convert_none(key, val, attr_type, attr={}, cdata=False):
"""Converts a null value into an XML element"""
LOG.info('Inside convert_none(): key="%s"' % (unicode_me(key)))
key, attr = make_valid_xml_name(key, attr)
if attr_type:
attr['type'] = get_xml_type(val)
attrstring = make_attrstrin... | python | def convert_none(key, val, attr_type, attr={}, cdata=False):
"""Converts a null value into an XML element"""
LOG.info('Inside convert_none(): key="%s"' % (unicode_me(key)))
key, attr = make_valid_xml_name(key, attr)
if attr_type:
attr['type'] = get_xml_type(val)
attrstring = make_attrstrin... | [
"def",
"convert_none",
"(",
"key",
",",
"val",
",",
"attr_type",
",",
"attr",
"=",
"{",
"}",
",",
"cdata",
"=",
"False",
")",
":",
"LOG",
".",
"info",
"(",
"'Inside convert_none(): key=\"%s\"'",
"%",
"(",
"unicode_me",
"(",
"key",
")",
")",
")",
"key",... | Converts a null value into an XML element | [
"Converts",
"a",
"null",
"value",
"into",
"an",
"XML",
"element"
] | 2016fe9817ad03b26aa5f1a475f5b79ad6757b96 | https://github.com/quandyfactory/dicttoxml/blob/2016fe9817ad03b26aa5f1a475f5b79ad6757b96/dicttoxml.py#L356-L365 |
8,034 | gruns/icecream | icecream/icecream.py | getCallSourceLines | def getCallSourceLines(callFrame, icNames, icMethod):
"""Raises NoSourceAvailableError."""
code = callFrame.f_code
# inspect.getblock(), which is called internally by inspect.getsource(),
# only returns the first line of <code> when <code> represents a top-level
# module, not the entire module's so... | python | def getCallSourceLines(callFrame, icNames, icMethod):
"""Raises NoSourceAvailableError."""
code = callFrame.f_code
# inspect.getblock(), which is called internally by inspect.getsource(),
# only returns the first line of <code> when <code> represents a top-level
# module, not the entire module's so... | [
"def",
"getCallSourceLines",
"(",
"callFrame",
",",
"icNames",
",",
"icMethod",
")",
":",
"code",
"=",
"callFrame",
".",
"f_code",
"# inspect.getblock(), which is called internally by inspect.getsource(),",
"# only returns the first line of <code> when <code> represents a top-level",... | Raises NoSourceAvailableError. | [
"Raises",
"NoSourceAvailableError",
"."
] | cb4f3d50ec747637721fe58b80f2cc2a2baedabf | https://github.com/gruns/icecream/blob/cb4f3d50ec747637721fe58b80f2cc2a2baedabf/icecream/icecream.py#L275-L366 |
8,035 | Vaelor/python-mattermost-driver | src/mattermostdriver/driver.py | Driver.init_websocket | def init_websocket(self, event_handler, websocket_cls=Websocket):
"""
Will initialize the websocket connection to the mattermost server.
This should be run after login(), because the websocket needs to make
an authentification.
See https://api.mattermost.com/v4/#tag/WebSocket for which
websocket events ma... | python | def init_websocket(self, event_handler, websocket_cls=Websocket):
"""
Will initialize the websocket connection to the mattermost server.
This should be run after login(), because the websocket needs to make
an authentification.
See https://api.mattermost.com/v4/#tag/WebSocket for which
websocket events ma... | [
"def",
"init_websocket",
"(",
"self",
",",
"event_handler",
",",
"websocket_cls",
"=",
"Websocket",
")",
":",
"self",
".",
"websocket",
"=",
"websocket_cls",
"(",
"self",
".",
"options",
",",
"self",
".",
"client",
".",
"token",
")",
"loop",
"=",
"asyncio"... | Will initialize the websocket connection to the mattermost server.
This should be run after login(), because the websocket needs to make
an authentification.
See https://api.mattermost.com/v4/#tag/WebSocket for which
websocket events mattermost sends.
Example of a really simple event_handler function
..... | [
"Will",
"initialize",
"the",
"websocket",
"connection",
"to",
"the",
"mattermost",
"server",
"."
] | ad1a936130096e39c2e1b76d78913e5950e06ca5 | https://github.com/Vaelor/python-mattermost-driver/blob/ad1a936130096e39c2e1b76d78913e5950e06ca5/src/mattermostdriver/driver.py#L114-L140 |
8,036 | Vaelor/python-mattermost-driver | src/mattermostdriver/driver.py | Driver.login | def login(self):
"""
Logs the user in.
The log in information is saved in the client
- userid
- username
- cookies
:return: The raw response from the request
"""
if self.options['token']:
self.client.token = self.options['token']
result = self.users.get_user('me')
else:
response = self... | python | def login(self):
"""
Logs the user in.
The log in information is saved in the client
- userid
- username
- cookies
:return: The raw response from the request
"""
if self.options['token']:
self.client.token = self.options['token']
result = self.users.get_user('me')
else:
response = self... | [
"def",
"login",
"(",
"self",
")",
":",
"if",
"self",
".",
"options",
"[",
"'token'",
"]",
":",
"self",
".",
"client",
".",
"token",
"=",
"self",
".",
"options",
"[",
"'token'",
"]",
"result",
"=",
"self",
".",
"users",
".",
"get_user",
"(",
"'me'",... | Logs the user in.
The log in information is saved in the client
- userid
- username
- cookies
:return: The raw response from the request | [
"Logs",
"the",
"user",
"in",
"."
] | ad1a936130096e39c2e1b76d78913e5950e06ca5 | https://github.com/Vaelor/python-mattermost-driver/blob/ad1a936130096e39c2e1b76d78913e5950e06ca5/src/mattermostdriver/driver.py#L142-L178 |
8,037 | Vaelor/python-mattermost-driver | src/mattermostdriver/websocket.py | Websocket.connect | def connect(self, event_handler):
"""
Connect to the websocket and authenticate it.
When the authentication has finished, start the loop listening for messages,
sending a ping to the server to keep the connection alive.
:param event_handler: Every websocket event will be passed there. Takes one argument.
:... | python | def connect(self, event_handler):
"""
Connect to the websocket and authenticate it.
When the authentication has finished, start the loop listening for messages,
sending a ping to the server to keep the connection alive.
:param event_handler: Every websocket event will be passed there. Takes one argument.
:... | [
"def",
"connect",
"(",
"self",
",",
"event_handler",
")",
":",
"context",
"=",
"ssl",
".",
"create_default_context",
"(",
"purpose",
"=",
"ssl",
".",
"Purpose",
".",
"CLIENT_AUTH",
")",
"if",
"not",
"self",
".",
"options",
"[",
"'verify'",
"]",
":",
"con... | Connect to the websocket and authenticate it.
When the authentication has finished, start the loop listening for messages,
sending a ping to the server to keep the connection alive.
:param event_handler: Every websocket event will be passed there. Takes one argument.
:type event_handler: Function(message)
:r... | [
"Connect",
"to",
"the",
"websocket",
"and",
"authenticate",
"it",
".",
"When",
"the",
"authentication",
"has",
"finished",
"start",
"the",
"loop",
"listening",
"for",
"messages",
"sending",
"a",
"ping",
"to",
"the",
"server",
"to",
"keep",
"the",
"connection",... | ad1a936130096e39c2e1b76d78913e5950e06ca5 | https://github.com/Vaelor/python-mattermost-driver/blob/ad1a936130096e39c2e1b76d78913e5950e06ca5/src/mattermostdriver/websocket.py#L19-L51 |
8,038 | Vaelor/python-mattermost-driver | src/mattermostdriver/websocket.py | Websocket._authenticate_websocket | def _authenticate_websocket(self, websocket, event_handler):
"""
Sends a authentication challenge over a websocket.
This is not needed when we just send the cookie we got on login
when connecting to the websocket.
"""
log.debug('Authenticating websocket')
json_data = json.dumps({
"seq": 1,
"action":... | python | def _authenticate_websocket(self, websocket, event_handler):
"""
Sends a authentication challenge over a websocket.
This is not needed when we just send the cookie we got on login
when connecting to the websocket.
"""
log.debug('Authenticating websocket')
json_data = json.dumps({
"seq": 1,
"action":... | [
"def",
"_authenticate_websocket",
"(",
"self",
",",
"websocket",
",",
"event_handler",
")",
":",
"log",
".",
"debug",
"(",
"'Authenticating websocket'",
")",
"json_data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"seq\"",
":",
"1",
",",
"\"action\"",
":",
"\"au... | Sends a authentication challenge over a websocket.
This is not needed when we just send the cookie we got on login
when connecting to the websocket. | [
"Sends",
"a",
"authentication",
"challenge",
"over",
"a",
"websocket",
".",
"This",
"is",
"not",
"needed",
"when",
"we",
"just",
"send",
"the",
"cookie",
"we",
"got",
"on",
"login",
"when",
"connecting",
"to",
"the",
"websocket",
"."
] | ad1a936130096e39c2e1b76d78913e5950e06ca5 | https://github.com/Vaelor/python-mattermost-driver/blob/ad1a936130096e39c2e1b76d78913e5950e06ca5/src/mattermostdriver/websocket.py#L73-L100 |
8,039 | paulgb/runipy | runipy/notebook_runner.py | NotebookRunner.run_cell | def run_cell(self, cell):
"""Run a notebook cell and update the output of that cell in-place."""
logging.info('Running cell:\n%s\n', cell.input)
self.kc.execute(cell.input)
reply = self.kc.get_shell_msg()
status = reply['content']['status']
traceback_text = ''
if ... | python | def run_cell(self, cell):
"""Run a notebook cell and update the output of that cell in-place."""
logging.info('Running cell:\n%s\n', cell.input)
self.kc.execute(cell.input)
reply = self.kc.get_shell_msg()
status = reply['content']['status']
traceback_text = ''
if ... | [
"def",
"run_cell",
"(",
"self",
",",
"cell",
")",
":",
"logging",
".",
"info",
"(",
"'Running cell:\\n%s\\n'",
",",
"cell",
".",
"input",
")",
"self",
".",
"kc",
".",
"execute",
"(",
"cell",
".",
"input",
")",
"reply",
"=",
"self",
".",
"kc",
".",
... | Run a notebook cell and update the output of that cell in-place. | [
"Run",
"a",
"notebook",
"cell",
"and",
"update",
"the",
"output",
"of",
"that",
"cell",
"in",
"-",
"place",
"."
] | d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe | https://github.com/paulgb/runipy/blob/d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe/runipy/notebook_runner.py#L138-L226 |
8,040 | paulgb/runipy | runipy/notebook_runner.py | NotebookRunner.iter_code_cells | def iter_code_cells(self):
"""Iterate over the notebook cells containing code."""
for ws in self.nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
yield cell | python | def iter_code_cells(self):
"""Iterate over the notebook cells containing code."""
for ws in self.nb.worksheets:
for cell in ws.cells:
if cell.cell_type == 'code':
yield cell | [
"def",
"iter_code_cells",
"(",
"self",
")",
":",
"for",
"ws",
"in",
"self",
".",
"nb",
".",
"worksheets",
":",
"for",
"cell",
"in",
"ws",
".",
"cells",
":",
"if",
"cell",
".",
"cell_type",
"==",
"'code'",
":",
"yield",
"cell"
] | Iterate over the notebook cells containing code. | [
"Iterate",
"over",
"the",
"notebook",
"cells",
"containing",
"code",
"."
] | d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe | https://github.com/paulgb/runipy/blob/d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe/runipy/notebook_runner.py#L228-L233 |
8,041 | paulgb/runipy | runipy/notebook_runner.py | NotebookRunner.run_notebook | def run_notebook(self, skip_exceptions=False, progress_callback=None):
"""
Run all the notebook cells in order and update the outputs in-place.
If ``skip_exceptions`` is set, then if exceptions occur in a cell, the
subsequent cells are run (by default, the notebook execution stops).
... | python | def run_notebook(self, skip_exceptions=False, progress_callback=None):
"""
Run all the notebook cells in order and update the outputs in-place.
If ``skip_exceptions`` is set, then if exceptions occur in a cell, the
subsequent cells are run (by default, the notebook execution stops).
... | [
"def",
"run_notebook",
"(",
"self",
",",
"skip_exceptions",
"=",
"False",
",",
"progress_callback",
"=",
"None",
")",
":",
"for",
"i",
",",
"cell",
"in",
"enumerate",
"(",
"self",
".",
"iter_code_cells",
"(",
")",
")",
":",
"try",
":",
"self",
".",
"ru... | Run all the notebook cells in order and update the outputs in-place.
If ``skip_exceptions`` is set, then if exceptions occur in a cell, the
subsequent cells are run (by default, the notebook execution stops). | [
"Run",
"all",
"the",
"notebook",
"cells",
"in",
"order",
"and",
"update",
"the",
"outputs",
"in",
"-",
"place",
"."
] | d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe | https://github.com/paulgb/runipy/blob/d48c4c522bd1d66dcc5c1c09e70a92bfb58360fe/runipy/notebook_runner.py#L235-L249 |
8,042 | metacloud/gilt | gilt/config.py | config | def config(filename):
"""
Construct `Config` object and return a list.
:parse filename: A string containing the path to YAML file.
:return: list
"""
Config = collections.namedtuple('Config', [
'git',
'lock_file',
'version',
'name',
'src',
'dst',
... | python | def config(filename):
"""
Construct `Config` object and return a list.
:parse filename: A string containing the path to YAML file.
:return: list
"""
Config = collections.namedtuple('Config', [
'git',
'lock_file',
'version',
'name',
'src',
'dst',
... | [
"def",
"config",
"(",
"filename",
")",
":",
"Config",
"=",
"collections",
".",
"namedtuple",
"(",
"'Config'",
",",
"[",
"'git'",
",",
"'lock_file'",
",",
"'version'",
",",
"'name'",
",",
"'src'",
",",
"'dst'",
",",
"'files'",
",",
"'post_commands'",
",",
... | Construct `Config` object and return a list.
:parse filename: A string containing the path to YAML file.
:return: list | [
"Construct",
"Config",
"object",
"and",
"return",
"a",
"list",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L41-L59 |
8,043 | metacloud/gilt | gilt/config.py | _get_files_config | def _get_files_config(src_dir, files_list):
"""
Construct `FileConfig` object and return a list.
:param src_dir: A string containing the source directory.
:param files_list: A list of dicts containing the src/dst mapping of files
to overlay.
:return: list
"""
FilesConfig = collections.... | python | def _get_files_config(src_dir, files_list):
"""
Construct `FileConfig` object and return a list.
:param src_dir: A string containing the source directory.
:param files_list: A list of dicts containing the src/dst mapping of files
to overlay.
:return: list
"""
FilesConfig = collections.... | [
"def",
"_get_files_config",
"(",
"src_dir",
",",
"files_list",
")",
":",
"FilesConfig",
"=",
"collections",
".",
"namedtuple",
"(",
"'FilesConfig'",
",",
"[",
"'src'",
",",
"'dst'",
",",
"'post_commands'",
"]",
")",
"return",
"[",
"FilesConfig",
"(",
"*",
"*... | Construct `FileConfig` object and return a list.
:param src_dir: A string containing the source directory.
:param files_list: A list of dicts containing the src/dst mapping of files
to overlay.
:return: list | [
"Construct",
"FileConfig",
"object",
"and",
"return",
"a",
"list",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L62-L76 |
8,044 | metacloud/gilt | gilt/config.py | _get_config | def _get_config(filename):
"""
Parse the provided YAML file and return a dict.
:parse filename: A string containing the path to YAML file.
:return: dict
"""
i = interpolation.Interpolator(interpolation.TemplateWithDefaults,
os.environ)
with open(filename,... | python | def _get_config(filename):
"""
Parse the provided YAML file and return a dict.
:parse filename: A string containing the path to YAML file.
:return: dict
"""
i = interpolation.Interpolator(interpolation.TemplateWithDefaults,
os.environ)
with open(filename,... | [
"def",
"_get_config",
"(",
"filename",
")",
":",
"i",
"=",
"interpolation",
".",
"Interpolator",
"(",
"interpolation",
".",
"TemplateWithDefaults",
",",
"os",
".",
"environ",
")",
"with",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"stream",
":",
"try"... | Parse the provided YAML file and return a dict.
:parse filename: A string containing the path to YAML file.
:return: dict | [
"Parse",
"the",
"provided",
"YAML",
"file",
"and",
"return",
"a",
"dict",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L126-L142 |
8,045 | metacloud/gilt | gilt/config.py | _get_dst_dir | def _get_dst_dir(dst_dir):
"""
Prefix the provided string with working directory and return a
str.
:param dst_dir: A string to be prefixed with the working dir.
:return: str
"""
wd = os.getcwd()
_makedirs(dst_dir)
return os.path.join(wd, dst_dir) | python | def _get_dst_dir(dst_dir):
"""
Prefix the provided string with working directory and return a
str.
:param dst_dir: A string to be prefixed with the working dir.
:return: str
"""
wd = os.getcwd()
_makedirs(dst_dir)
return os.path.join(wd, dst_dir) | [
"def",
"_get_dst_dir",
"(",
"dst_dir",
")",
":",
"wd",
"=",
"os",
".",
"getcwd",
"(",
")",
"_makedirs",
"(",
"dst_dir",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"wd",
",",
"dst_dir",
")"
] | Prefix the provided string with working directory and return a
str.
:param dst_dir: A string to be prefixed with the working dir.
:return: str | [
"Prefix",
"the",
"provided",
"string",
"with",
"working",
"directory",
"and",
"return",
"a",
"str",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L145-L156 |
8,046 | metacloud/gilt | gilt/config.py | _makedirs | def _makedirs(path):
"""
Create a base directory of the provided path and return None.
:param path: A string containing a path to be deconstructed and basedir
created.
:return: None
"""
dirname, _ = os.path.split(path)
try:
os.makedirs(dirname)
except OSError as exc:
... | python | def _makedirs(path):
"""
Create a base directory of the provided path and return None.
:param path: A string containing a path to be deconstructed and basedir
created.
:return: None
"""
dirname, _ = os.path.split(path)
try:
os.makedirs(dirname)
except OSError as exc:
... | [
"def",
"_makedirs",
"(",
"path",
")",
":",
"dirname",
",",
"_",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"try",
":",
"os",
".",
"makedirs",
"(",
"dirname",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"=="... | Create a base directory of the provided path and return None.
:param path: A string containing a path to be deconstructed and basedir
created.
:return: None | [
"Create",
"a",
"base",
"directory",
"of",
"the",
"provided",
"path",
"and",
"return",
"None",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/config.py#L193-L208 |
8,047 | metacloud/gilt | gilt/shell.py | main | def main(ctx, config, debug): # pragma: no cover
""" gilt - A GIT layering tool. """
ctx.obj = {}
ctx.obj['args'] = {}
ctx.obj['args']['debug'] = debug
ctx.obj['args']['config'] = config | python | def main(ctx, config, debug): # pragma: no cover
""" gilt - A GIT layering tool. """
ctx.obj = {}
ctx.obj['args'] = {}
ctx.obj['args']['debug'] = debug
ctx.obj['args']['config'] = config | [
"def",
"main",
"(",
"ctx",
",",
"config",
",",
"debug",
")",
":",
"# pragma: no cover",
"ctx",
".",
"obj",
"=",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'args'",
"]",
"=",
"{",
"}",
"ctx",
".",
"obj",
"[",
"'args'",
"]",
"[",
"'debug'",
"]",
"=",
"de... | gilt - A GIT layering tool. | [
"gilt",
"-",
"A",
"GIT",
"layering",
"tool",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/shell.py#L50-L55 |
8,048 | metacloud/gilt | gilt/shell.py | overlay | def overlay(ctx): # pragma: no cover
""" Install gilt dependencies """
args = ctx.obj.get('args')
filename = args.get('config')
debug = args.get('debug')
_setup(filename)
for c in config.config(filename):
with fasteners.InterProcessLock(c.lock_file):
util.print_info('{}:'.f... | python | def overlay(ctx): # pragma: no cover
""" Install gilt dependencies """
args = ctx.obj.get('args')
filename = args.get('config')
debug = args.get('debug')
_setup(filename)
for c in config.config(filename):
with fasteners.InterProcessLock(c.lock_file):
util.print_info('{}:'.f... | [
"def",
"overlay",
"(",
"ctx",
")",
":",
"# pragma: no cover",
"args",
"=",
"ctx",
".",
"obj",
".",
"get",
"(",
"'args'",
")",
"filename",
"=",
"args",
".",
"get",
"(",
"'config'",
")",
"debug",
"=",
"args",
".",
"get",
"(",
"'debug'",
")",
"_setup",
... | Install gilt dependencies | [
"Install",
"gilt",
"dependencies"
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/shell.py#L60-L87 |
8,049 | metacloud/gilt | gilt/git.py | clone | def clone(name, repository, destination, debug=False):
"""
Clone the specified repository into a temporary directory and return None.
:param name: A string containing the name of the repository being cloned.
:param repository: A string containing the repository to clone.
:param destination: A strin... | python | def clone(name, repository, destination, debug=False):
"""
Clone the specified repository into a temporary directory and return None.
:param name: A string containing the name of the repository being cloned.
:param repository: A string containing the repository to clone.
:param destination: A strin... | [
"def",
"clone",
"(",
"name",
",",
"repository",
",",
"destination",
",",
"debug",
"=",
"False",
")",
":",
"msg",
"=",
"' - cloning {} to {}'",
".",
"format",
"(",
"name",
",",
"destination",
")",
"util",
".",
"print_info",
"(",
"msg",
")",
"cmd",
"=",
... | Clone the specified repository into a temporary directory and return None.
:param name: A string containing the name of the repository being cloned.
:param repository: A string containing the repository to clone.
:param destination: A string containing the directory to clone the
repository into.
:... | [
"Clone",
"the",
"specified",
"repository",
"into",
"a",
"temporary",
"directory",
"and",
"return",
"None",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L32-L46 |
8,050 | metacloud/gilt | gilt/git.py | _get_version | def _get_version(version, debug=False):
"""
Handle switching to the specified version and return None.
1. Fetch the origin.
2. Checkout the specified version.
3. Clean the repository before we begin.
4. Pull the origin when a branch; _not_ a commit id.
:param version: A string containing t... | python | def _get_version(version, debug=False):
"""
Handle switching to the specified version and return None.
1. Fetch the origin.
2. Checkout the specified version.
3. Clean the repository before we begin.
4. Pull the origin when a branch; _not_ a commit id.
:param version: A string containing t... | [
"def",
"_get_version",
"(",
"version",
",",
"debug",
"=",
"False",
")",
":",
"if",
"not",
"any",
"(",
"(",
"_has_branch",
"(",
"version",
",",
"debug",
")",
",",
"_has_tag",
"(",
"version",
",",
"debug",
")",
",",
"_has_commit",
"(",
"version",
",",
... | Handle switching to the specified version and return None.
1. Fetch the origin.
2. Checkout the specified version.
3. Clean the repository before we begin.
4. Pull the origin when a branch; _not_ a commit id.
:param version: A string containing the branch/tag/sha to be exported.
:param debug: ... | [
"Handle",
"switching",
"to",
"the",
"specified",
"version",
"and",
"return",
"None",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L109-L133 |
8,051 | metacloud/gilt | gilt/git.py | _has_commit | def _has_commit(version, debug=False):
"""
Determine a version is a local git commit sha or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool
"""
if _has_tag(version, debug) or _has_branch(versi... | python | def _has_commit(version, debug=False):
"""
Determine a version is a local git commit sha or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool
"""
if _has_tag(version, debug) or _has_branch(versi... | [
"def",
"_has_commit",
"(",
"version",
",",
"debug",
"=",
"False",
")",
":",
"if",
"_has_tag",
"(",
"version",
",",
"debug",
")",
"or",
"_has_branch",
"(",
"version",
",",
"debug",
")",
":",
"return",
"False",
"cmd",
"=",
"sh",
".",
"git",
".",
"bake"... | Determine a version is a local git commit sha or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool | [
"Determine",
"a",
"version",
"is",
"a",
"local",
"git",
"commit",
"sha",
"or",
"not",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L136-L151 |
8,052 | metacloud/gilt | gilt/git.py | _has_tag | def _has_tag(version, debug=False):
"""
Determine a version is a local git tag name or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool
"""
cmd = sh.git.bake('show-ref', '--verify', '--quiet',
... | python | def _has_tag(version, debug=False):
"""
Determine a version is a local git tag name or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool
"""
cmd = sh.git.bake('show-ref', '--verify', '--quiet',
... | [
"def",
"_has_tag",
"(",
"version",
",",
"debug",
"=",
"False",
")",
":",
"cmd",
"=",
"sh",
".",
"git",
".",
"bake",
"(",
"'show-ref'",
",",
"'--verify'",
",",
"'--quiet'",
",",
"\"refs/tags/{}\"",
".",
"format",
"(",
"version",
")",
")",
"try",
":",
... | Determine a version is a local git tag name or not.
:param version: A string containing the branch/tag/sha to be determined.
:param debug: An optional bool to toggle debug output.
:return: bool | [
"Determine",
"a",
"version",
"is",
"a",
"local",
"git",
"tag",
"name",
"or",
"not",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/git.py#L154-L168 |
8,053 | metacloud/gilt | gilt/util.py | run_command | def run_command(cmd, debug=False):
"""
Execute the given command and return None.
:param cmd: A `sh.Command` object to execute.
:param debug: An optional bool to toggle debug output.
:return: None
"""
if debug:
msg = ' PWD: {}'.format(os.getcwd())
print_warn(msg)
ms... | python | def run_command(cmd, debug=False):
"""
Execute the given command and return None.
:param cmd: A `sh.Command` object to execute.
:param debug: An optional bool to toggle debug output.
:return: None
"""
if debug:
msg = ' PWD: {}'.format(os.getcwd())
print_warn(msg)
ms... | [
"def",
"run_command",
"(",
"cmd",
",",
"debug",
"=",
"False",
")",
":",
"if",
"debug",
":",
"msg",
"=",
"' PWD: {}'",
".",
"format",
"(",
"os",
".",
"getcwd",
"(",
")",
")",
"print_warn",
"(",
"msg",
")",
"msg",
"=",
"' COMMAND: {}'",
".",
"format"... | Execute the given command and return None.
:param cmd: A `sh.Command` object to execute.
:param debug: An optional bool to toggle debug output.
:return: None | [
"Execute",
"the",
"given",
"command",
"and",
"return",
"None",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/util.py#L46-L59 |
8,054 | metacloud/gilt | gilt/util.py | build_sh_cmd | def build_sh_cmd(cmd, cwd=None):
"""Build a `sh.Command` from a string.
:param cmd: String with the command to convert.
:param cwd: Optional path to use as working directory.
:return: `sh.Command`
"""
args = cmd.split()
return getattr(sh, args[0]).bake(_cwd=cwd, *args[1:]) | python | def build_sh_cmd(cmd, cwd=None):
"""Build a `sh.Command` from a string.
:param cmd: String with the command to convert.
:param cwd: Optional path to use as working directory.
:return: `sh.Command`
"""
args = cmd.split()
return getattr(sh, args[0]).bake(_cwd=cwd, *args[1:]) | [
"def",
"build_sh_cmd",
"(",
"cmd",
",",
"cwd",
"=",
"None",
")",
":",
"args",
"=",
"cmd",
".",
"split",
"(",
")",
"return",
"getattr",
"(",
"sh",
",",
"args",
"[",
"0",
"]",
")",
".",
"bake",
"(",
"_cwd",
"=",
"cwd",
",",
"*",
"args",
"[",
"1... | Build a `sh.Command` from a string.
:param cmd: String with the command to convert.
:param cwd: Optional path to use as working directory.
:return: `sh.Command` | [
"Build",
"a",
"sh",
".",
"Command",
"from",
"a",
"string",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/util.py#L62-L70 |
8,055 | metacloud/gilt | gilt/util.py | copy | def copy(src, dst):
"""
Handle the copying of a file or directory.
The destination basedir _must_ exist.
:param src: A string containing the path of the source to copy. If the
source ends with a '/', will become a recursive directory copy of source.
:param dst: A string containing the path t... | python | def copy(src, dst):
"""
Handle the copying of a file or directory.
The destination basedir _must_ exist.
:param src: A string containing the path of the source to copy. If the
source ends with a '/', will become a recursive directory copy of source.
:param dst: A string containing the path t... | [
"def",
"copy",
"(",
"src",
",",
"dst",
")",
":",
"try",
":",
"shutil",
".",
"copytree",
"(",
"src",
",",
"dst",
")",
"except",
"OSError",
"as",
"exc",
":",
"if",
"exc",
".",
"errno",
"==",
"errno",
".",
"ENOTDIR",
":",
"shutil",
".",
"copy",
"(",... | Handle the copying of a file or directory.
The destination basedir _must_ exist.
:param src: A string containing the path of the source to copy. If the
source ends with a '/', will become a recursive directory copy of source.
:param dst: A string containing the path to the destination. If the
... | [
"Handle",
"the",
"copying",
"of",
"a",
"file",
"or",
"directory",
"."
] | 234eec23fe2f8144369d0ec3b35ad2fef508b8d1 | https://github.com/metacloud/gilt/blob/234eec23fe2f8144369d0ec3b35ad2fef508b8d1/gilt/util.py#L83-L101 |
8,056 | yhat/db.py | db/table.py | Table.to_dict | def to_dict(self):
"""Serialize representation of the table for local caching."""
return {'schema': self.schema, 'name': self.name, 'columns': [col.to_dict() for col in self._columns],
'foreign_keys': self.foreign_keys.to_dict(), 'ref_keys': self.ref_keys.to_dict()} | python | def to_dict(self):
"""Serialize representation of the table for local caching."""
return {'schema': self.schema, 'name': self.name, 'columns': [col.to_dict() for col in self._columns],
'foreign_keys': self.foreign_keys.to_dict(), 'ref_keys': self.ref_keys.to_dict()} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'schema'",
":",
"self",
".",
"schema",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'columns'",
":",
"[",
"col",
".",
"to_dict",
"(",
")",
"for",
"col",
"in",
"self",
".",
"_columns",
"]",
... | Serialize representation of the table for local caching. | [
"Serialize",
"representation",
"of",
"the",
"table",
"for",
"local",
"caching",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/table.py#L348-L351 |
8,057 | yhat/db.py | db/db.py | list_profiles | def list_profiles():
"""
Lists all of the database profiles available
Examples
--------
No doctest, covered by unittest
list_profiles()
{'demo': {u'dbname': None,
u'dbtype': u'sqlite',
u'filename': u'/Users/glamp/repos/yhat/opensource/db.py/db/data/chinook.sqlite',
u'host... | python | def list_profiles():
"""
Lists all of the database profiles available
Examples
--------
No doctest, covered by unittest
list_profiles()
{'demo': {u'dbname': None,
u'dbtype': u'sqlite',
u'filename': u'/Users/glamp/repos/yhat/opensource/db.py/db/data/chinook.sqlite',
u'host... | [
"def",
"list_profiles",
"(",
")",
":",
"profiles",
"=",
"{",
"}",
"user",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"for",
"f",
"in",
"os",
".",
"listdir",
"(",
"user",
")",
":",
"if",
"f",
".",
"startswith",
"(",
"\".db.py_\"",... | Lists all of the database profiles available
Examples
--------
No doctest, covered by unittest
list_profiles()
{'demo': {u'dbname': None,
u'dbtype': u'sqlite',
u'filename': u'/Users/glamp/repos/yhat/opensource/db.py/db/data/chinook.sqlite',
u'hostname': u'localhost',
u'pass... | [
"Lists",
"all",
"of",
"the",
"database",
"profiles",
"available"
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L1059-L1094 |
8,058 | yhat/db.py | db/db.py | remove_profile | def remove_profile(name, s3=False):
"""
Removes a profile from your config
"""
user = os.path.expanduser("~")
if s3:
f = os.path.join(user, S3_PROFILE_ID + name)
else:
f = os.path.join(user, DBPY_PROFILE_ID + name)
try:
try:
open(f)
except:
... | python | def remove_profile(name, s3=False):
"""
Removes a profile from your config
"""
user = os.path.expanduser("~")
if s3:
f = os.path.join(user, S3_PROFILE_ID + name)
else:
f = os.path.join(user, DBPY_PROFILE_ID + name)
try:
try:
open(f)
except:
... | [
"def",
"remove_profile",
"(",
"name",
",",
"s3",
"=",
"False",
")",
":",
"user",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"if",
"s3",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"user",
",",
"S3_PROFILE_ID",
"+",
"nam... | Removes a profile from your config | [
"Removes",
"a",
"profile",
"from",
"your",
"config"
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L1097-L1114 |
8,059 | yhat/db.py | db/db.py | DB.tables | def tables(self):
"""A lazy loaded reference to the table metadata for the DB."""
if len(self._tables) == 0:
self.refresh_schema(self._exclude_system_tables, self._use_cache)
return self._tables | python | def tables(self):
"""A lazy loaded reference to the table metadata for the DB."""
if len(self._tables) == 0:
self.refresh_schema(self._exclude_system_tables, self._use_cache)
return self._tables | [
"def",
"tables",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_tables",
")",
"==",
"0",
":",
"self",
".",
"refresh_schema",
"(",
"self",
".",
"_exclude_system_tables",
",",
"self",
".",
"_use_cache",
")",
"return",
"self",
".",
"_tables"
] | A lazy loaded reference to the table metadata for the DB. | [
"A",
"lazy",
"loaded",
"reference",
"to",
"the",
"table",
"metadata",
"for",
"the",
"DB",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L262-L266 |
8,060 | yhat/db.py | db/db.py | DB.save_credentials | def save_credentials(self, profile="default"):
"""
Save your database credentials so you don't have to save them in script.
Parameters
----------
profile: str
(optional) identifier/name for your database (i.e. "dw", "prod")
from db import DB
import p... | python | def save_credentials(self, profile="default"):
"""
Save your database credentials so you don't have to save them in script.
Parameters
----------
profile: str
(optional) identifier/name for your database (i.e. "dw", "prod")
from db import DB
import p... | [
"def",
"save_credentials",
"(",
"self",
",",
"profile",
"=",
"\"default\"",
")",
":",
"f",
"=",
"profile_path",
"(",
"DBPY_PROFILE_ID",
",",
"profile",
")",
"dump_to_json",
"(",
"f",
",",
"self",
".",
"credentials",
")"
] | Save your database credentials so you don't have to save them in script.
Parameters
----------
profile: str
(optional) identifier/name for your database (i.e. "dw", "prod")
from db import DB
import pymysql
db = DB(username="hank", password="foo", hostname="p... | [
"Save",
"your",
"database",
"credentials",
"so",
"you",
"don",
"t",
"have",
"to",
"save",
"them",
"in",
"script",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L307-L329 |
8,061 | yhat/db.py | db/db.py | DB.save_metadata | def save_metadata(self, profile="default"):
"""Save the database credentials, plus the database properties to your db.py profile."""
if len(self.tables) > 0:
f = profile_path(DBPY_PROFILE_ID, profile)
dump_to_json(f, self.to_dict()) | python | def save_metadata(self, profile="default"):
"""Save the database credentials, plus the database properties to your db.py profile."""
if len(self.tables) > 0:
f = profile_path(DBPY_PROFILE_ID, profile)
dump_to_json(f, self.to_dict()) | [
"def",
"save_metadata",
"(",
"self",
",",
"profile",
"=",
"\"default\"",
")",
":",
"if",
"len",
"(",
"self",
".",
"tables",
")",
">",
"0",
":",
"f",
"=",
"profile_path",
"(",
"DBPY_PROFILE_ID",
",",
"profile",
")",
"dump_to_json",
"(",
"f",
",",
"self"... | Save the database credentials, plus the database properties to your db.py profile. | [
"Save",
"the",
"database",
"credentials",
"plus",
"the",
"database",
"properties",
"to",
"your",
"db",
".",
"py",
"profile",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L338-L342 |
8,062 | yhat/db.py | db/db.py | DB.credentials | def credentials(self):
"""Dict representation of all credentials for the database."""
if self.filename:
db_filename = os.path.join(os.getcwd(), self.filename)
else:
db_filename = None
return {
"username": self.username,
"password": self.pa... | python | def credentials(self):
"""Dict representation of all credentials for the database."""
if self.filename:
db_filename = os.path.join(os.getcwd(), self.filename)
else:
db_filename = None
return {
"username": self.username,
"password": self.pa... | [
"def",
"credentials",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
":",
"db_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getcwd",
"(",
")",
",",
"self",
".",
"filename",
")",
"else",
":",
"db_filename",
"=",
"None",
"re... | Dict representation of all credentials for the database. | [
"Dict",
"representation",
"of",
"all",
"credentials",
"for",
"the",
"database",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L345-L363 |
8,063 | yhat/db.py | db/db.py | DB.find_table | def find_table(self, search):
"""
Aggresively search through your database's schema for a table.
Parameters
-----------
search: str
glob pattern for what you're looking for
Examples
----------
>>> from db import DemoDB
>>> db = DemoDB(... | python | def find_table(self, search):
"""
Aggresively search through your database's schema for a table.
Parameters
-----------
search: str
glob pattern for what you're looking for
Examples
----------
>>> from db import DemoDB
>>> db = DemoDB(... | [
"def",
"find_table",
"(",
"self",
",",
"search",
")",
":",
"tables",
"=",
"[",
"]",
"for",
"table",
"in",
"self",
".",
"tables",
":",
"if",
"glob",
".",
"fnmatch",
".",
"fnmatch",
"(",
"table",
".",
"name",
",",
"search",
")",
":",
"tables",
".",
... | Aggresively search through your database's schema for a table.
Parameters
-----------
search: str
glob pattern for what you're looking for
Examples
----------
>>> from db import DemoDB
>>> db = DemoDB()
>>> db.find_table("A*")
+-------... | [
"Aggresively",
"search",
"through",
"your",
"database",
"s",
"schema",
"for",
"a",
"table",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L365-L394 |
8,064 | yhat/db.py | db/db.py | DB.find_column | def find_column(self, search, data_type=None):
"""
Aggresively search through your database's schema for a column.
Parameters
-----------
search: str
glob pattern for what you're looking for
data_type: str, list
(optional) specify which data type(s)... | python | def find_column(self, search, data_type=None):
"""
Aggresively search through your database's schema for a column.
Parameters
-----------
search: str
glob pattern for what you're looking for
data_type: str, list
(optional) specify which data type(s)... | [
"def",
"find_column",
"(",
"self",
",",
"search",
",",
"data_type",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"data_type",
",",
"str",
")",
":",
"data_type",
"=",
"[",
"data_type",
"]",
"cols",
"=",
"[",
"]",
"for",
"table",
"in",
"self",
".",
... | Aggresively search through your database's schema for a column.
Parameters
-----------
search: str
glob pattern for what you're looking for
data_type: str, list
(optional) specify which data type(s) you want to return
Examples
----------
>>... | [
"Aggresively",
"search",
"through",
"your",
"database",
"s",
"schema",
"for",
"a",
"column",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L396-L508 |
8,065 | yhat/db.py | db/db.py | DB.query | def query(self, q, data=None, union=True, limit=None):
"""
Query your database with a raw string.
Parameters
----------
q: str
Query string to execute
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
... | python | def query(self, q, data=None, union=True, limit=None):
"""
Query your database with a raw string.
Parameters
----------
q: str
Query string to execute
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
... | [
"def",
"query",
"(",
"self",
",",
"q",
",",
"data",
"=",
"None",
",",
"union",
"=",
"True",
",",
"limit",
"=",
"None",
")",
":",
"if",
"data",
":",
"q",
"=",
"self",
".",
"_apply_handlebars",
"(",
"q",
",",
"data",
",",
"union",
")",
"if",
"lim... | Query your database with a raw string.
Parameters
----------
q: str
Query string to execute
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
template and rendered using handlebars.
union: bool
W... | [
"Query",
"your",
"database",
"with",
"a",
"raw",
"string",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L541-L702 |
8,066 | yhat/db.py | db/db.py | DB.query_from_file | def query_from_file(self, filename, data=None, union=True, limit=None):
"""
Query your database from a file.
Parameters
----------
filename: str
A SQL script
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
... | python | def query_from_file(self, filename, data=None, union=True, limit=None):
"""
Query your database from a file.
Parameters
----------
filename: str
A SQL script
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
... | [
"def",
"query_from_file",
"(",
"self",
",",
"filename",
",",
"data",
"=",
"None",
",",
"union",
"=",
"True",
",",
"limit",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fp",
":",
"q",
"=",
"fp",
".",
"read",
"(",
")",
"retur... | Query your database from a file.
Parameters
----------
filename: str
A SQL script
data: list, dict
Optional argument for handlebars-queries. Data will be passed to the
template and rendered using handlebars.
union: bool
Whether or ... | [
"Query",
"your",
"database",
"from",
"a",
"file",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L704-L771 |
8,067 | yhat/db.py | db/db.py | DB.refresh_schema | def refresh_schema(self, exclude_system_tables=True, use_cache=False):
"""
Pulls your database's schema again and looks for any new tables and
columns.
"""
col_meta, table_meta = self._get_db_metadata(exclude_system_tables, use_cache)
tables = self._gen_tables_from_col_t... | python | def refresh_schema(self, exclude_system_tables=True, use_cache=False):
"""
Pulls your database's schema again and looks for any new tables and
columns.
"""
col_meta, table_meta = self._get_db_metadata(exclude_system_tables, use_cache)
tables = self._gen_tables_from_col_t... | [
"def",
"refresh_schema",
"(",
"self",
",",
"exclude_system_tables",
"=",
"True",
",",
"use_cache",
"=",
"False",
")",
":",
"col_meta",
",",
"table_meta",
"=",
"self",
".",
"_get_db_metadata",
"(",
"exclude_system_tables",
",",
"use_cache",
")",
"tables",
"=",
... | Pulls your database's schema again and looks for any new tables and
columns. | [
"Pulls",
"your",
"database",
"s",
"schema",
"again",
"and",
"looks",
"for",
"any",
"new",
"tables",
"and",
"columns",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L809-L854 |
8,068 | yhat/db.py | db/db.py | DB.to_dict | def to_dict(self):
"""Dict representation of the database as credentials plus tables dict representation."""
db_dict = self.credentials
db_dict.update(self.tables.to_dict())
return db_dict | python | def to_dict(self):
"""Dict representation of the database as credentials plus tables dict representation."""
db_dict = self.credentials
db_dict.update(self.tables.to_dict())
return db_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"db_dict",
"=",
"self",
".",
"credentials",
"db_dict",
".",
"update",
"(",
"self",
".",
"tables",
".",
"to_dict",
"(",
")",
")",
"return",
"db_dict"
] | Dict representation of the database as credentials plus tables dict representation. | [
"Dict",
"representation",
"of",
"the",
"database",
"as",
"credentials",
"plus",
"tables",
"dict",
"representation",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/db.py#L1052-L1056 |
8,069 | yhat/db.py | db/utils.py | profile_path | def profile_path(profile_id, profile):
"""Create full path to given provide for the current user."""
user = os.path.expanduser("~")
return os.path.join(user, profile_id + profile) | python | def profile_path(profile_id, profile):
"""Create full path to given provide for the current user."""
user = os.path.expanduser("~")
return os.path.join(user, profile_id + profile) | [
"def",
"profile_path",
"(",
"profile_id",
",",
"profile",
")",
":",
"user",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"user",
",",
"profile_id",
"+",
"profile",
")"
] | Create full path to given provide for the current user. | [
"Create",
"full",
"path",
"to",
"given",
"provide",
"for",
"the",
"current",
"user",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/utils.py#L5-L8 |
8,070 | yhat/db.py | db/utils.py | load_from_json | def load_from_json(file_path):
"""Load the stored data from json, and return as a dict."""
if os.path.exists(file_path):
raw_data = open(file_path, 'rb').read()
return json.loads(base64.decodestring(raw_data).decode('utf-8')) | python | def load_from_json(file_path):
"""Load the stored data from json, and return as a dict."""
if os.path.exists(file_path):
raw_data = open(file_path, 'rb').read()
return json.loads(base64.decodestring(raw_data).decode('utf-8')) | [
"def",
"load_from_json",
"(",
"file_path",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"raw_data",
"=",
"open",
"(",
"file_path",
",",
"'rb'",
")",
".",
"read",
"(",
")",
"return",
"json",
".",
"loads",
"(",
"base64"... | Load the stored data from json, and return as a dict. | [
"Load",
"the",
"stored",
"data",
"from",
"json",
"and",
"return",
"as",
"a",
"dict",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/utils.py#L13-L17 |
8,071 | yhat/db.py | db/s3.py | S3.save_credentials | def save_credentials(self, profile):
"""
Saves credentials to a dotfile so you can open them grab them later.
Parameters
----------
profile: str
name for your profile (i.e. "dev", "prod")
"""
filename = profile_path(S3_PROFILE_ID, profile)
cre... | python | def save_credentials(self, profile):
"""
Saves credentials to a dotfile so you can open them grab them later.
Parameters
----------
profile: str
name for your profile (i.e. "dev", "prod")
"""
filename = profile_path(S3_PROFILE_ID, profile)
cre... | [
"def",
"save_credentials",
"(",
"self",
",",
"profile",
")",
":",
"filename",
"=",
"profile_path",
"(",
"S3_PROFILE_ID",
",",
"profile",
")",
"creds",
"=",
"{",
"\"access_key\"",
":",
"self",
".",
"access_key",
",",
"\"secret_key\"",
":",
"self",
".",
"secre... | Saves credentials to a dotfile so you can open them grab them later.
Parameters
----------
profile: str
name for your profile (i.e. "dev", "prod") | [
"Saves",
"credentials",
"to",
"a",
"dotfile",
"so",
"you",
"can",
"open",
"them",
"grab",
"them",
"later",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/s3.py#L16-L30 |
8,072 | yhat/db.py | db/column.py | Column.to_dict | def to_dict(self):
"""
Serialize representation of the column for local caching.
"""
return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type} | python | def to_dict(self):
"""
Serialize representation of the column for local caching.
"""
return {'schema': self.schema, 'table': self.table, 'name': self.name, 'type': self.type} | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'schema'",
":",
"self",
".",
"schema",
",",
"'table'",
":",
"self",
".",
"table",
",",
"'name'",
":",
"self",
".",
"name",
",",
"'type'",
":",
"self",
".",
"type",
"}"
] | Serialize representation of the column for local caching. | [
"Serialize",
"representation",
"of",
"the",
"column",
"for",
"local",
"caching",
"."
] | df2dbb8ef947c2d4253d31f29eb58c4084daffc5 | https://github.com/yhat/db.py/blob/df2dbb8ef947c2d4253d31f29eb58c4084daffc5/db/column.py#L192-L196 |
8,073 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.rate_limit | def rate_limit(self, rate_limit):
""" Turn on or off rate limiting """
self._rate_limit = bool(rate_limit)
self._rate_limit_last_call = None
self.clear_memoized() | python | def rate_limit(self, rate_limit):
""" Turn on or off rate limiting """
self._rate_limit = bool(rate_limit)
self._rate_limit_last_call = None
self.clear_memoized() | [
"def",
"rate_limit",
"(",
"self",
",",
"rate_limit",
")",
":",
"self",
".",
"_rate_limit",
"=",
"bool",
"(",
"rate_limit",
")",
"self",
".",
"_rate_limit_last_call",
"=",
"None",
"self",
".",
"clear_memoized",
"(",
")"
] | Turn on or off rate limiting | [
"Turn",
"on",
"or",
"off",
"rate",
"limiting"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L136-L140 |
8,074 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.language | def language(self, lang):
""" Set the language to use; attempts to change the API URL """
lang = lang.lower()
if self._lang == lang:
return
url = self._api_url
tmp = url.replace("/{0}.".format(self._lang), "/{0}.".format(lang))
self._api_url = tmp
se... | python | def language(self, lang):
""" Set the language to use; attempts to change the API URL """
lang = lang.lower()
if self._lang == lang:
return
url = self._api_url
tmp = url.replace("/{0}.".format(self._lang), "/{0}.".format(lang))
self._api_url = tmp
se... | [
"def",
"language",
"(",
"self",
",",
"lang",
")",
":",
"lang",
"=",
"lang",
".",
"lower",
"(",
")",
"if",
"self",
".",
"_lang",
"==",
"lang",
":",
"return",
"url",
"=",
"self",
".",
"_api_url",
"tmp",
"=",
"url",
".",
"replace",
"(",
"\"/{0}.\"",
... | Set the language to use; attempts to change the API URL | [
"Set",
"the",
"language",
"to",
"use",
";",
"attempts",
"to",
"change",
"the",
"API",
"URL"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L197-L208 |
8,075 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.refresh_interval | def refresh_interval(self, refresh_interval):
""" Set the new cache refresh interval """
if isinstance(refresh_interval, int) and refresh_interval > 0:
self._refresh_interval = refresh_interval
else:
self._refresh_interval = None | python | def refresh_interval(self, refresh_interval):
""" Set the new cache refresh interval """
if isinstance(refresh_interval, int) and refresh_interval > 0:
self._refresh_interval = refresh_interval
else:
self._refresh_interval = None | [
"def",
"refresh_interval",
"(",
"self",
",",
"refresh_interval",
")",
":",
"if",
"isinstance",
"(",
"refresh_interval",
",",
"int",
")",
"and",
"refresh_interval",
">",
"0",
":",
"self",
".",
"_refresh_interval",
"=",
"refresh_interval",
"else",
":",
"self",
"... | Set the new cache refresh interval | [
"Set",
"the",
"new",
"cache",
"refresh",
"interval"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L262-L267 |
8,076 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.login | def login(self, username, password, strict=True):
""" Login as specified user
Args:
username (str): The username to log in with
password (str): The password for the user
strict (bool): `True` to thow an error on failure
Returns:
... | python | def login(self, username, password, strict=True):
""" Login as specified user
Args:
username (str): The username to log in with
password (str): The password for the user
strict (bool): `True` to thow an error on failure
Returns:
... | [
"def",
"login",
"(",
"self",
",",
"username",
",",
"password",
",",
"strict",
"=",
"True",
")",
":",
"# get login token",
"params",
"=",
"{",
"\"action\"",
":",
"\"query\"",
",",
"\"meta\"",
":",
"\"tokens\"",
",",
"\"type\"",
":",
"\"login\"",
",",
"\"for... | Login as specified user
Args:
username (str): The username to log in with
password (str): The password for the user
strict (bool): `True` to thow an error on failure
Returns:
bool: `True` if successfully logged in; `False` otherwis... | [
"Login",
"as",
"specified",
"user"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L269-L314 |
8,077 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.set_api_url | def set_api_url(self, api_url="https://{lang}.wikipedia.org/w/api.php", lang="en"):
""" Set the API URL and language
Args:
api_url (str): API URL to use
lang (str): Language of the API URL
Raises:
:py:func:`mediawiki.exceptions.MediaWikiAP... | python | def set_api_url(self, api_url="https://{lang}.wikipedia.org/w/api.php", lang="en"):
""" Set the API URL and language
Args:
api_url (str): API URL to use
lang (str): Language of the API URL
Raises:
:py:func:`mediawiki.exceptions.MediaWikiAP... | [
"def",
"set_api_url",
"(",
"self",
",",
"api_url",
"=",
"\"https://{lang}.wikipedia.org/w/api.php\"",
",",
"lang",
"=",
"\"en\"",
")",
":",
"old_api_url",
"=",
"self",
".",
"_api_url",
"old_lang",
"=",
"self",
".",
"_lang",
"self",
".",
"_lang",
"=",
"lang",
... | Set the API URL and language
Args:
api_url (str): API URL to use
lang (str): Language of the API URL
Raises:
:py:func:`mediawiki.exceptions.MediaWikiAPIURLError`: if the \
url is not a valid MediaWiki site | [
"Set",
"the",
"API",
"URL",
"and",
"language"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L317-L338 |
8,078 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki._reset_session | def _reset_session(self):
""" Set session information """
headers = {"User-Agent": self._user_agent}
self._session = requests.Session()
self._session.headers.update(headers)
self._is_logged_in = False | python | def _reset_session(self):
""" Set session information """
headers = {"User-Agent": self._user_agent}
self._session = requests.Session()
self._session.headers.update(headers)
self._is_logged_in = False | [
"def",
"_reset_session",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"\"User-Agent\"",
":",
"self",
".",
"_user_agent",
"}",
"self",
".",
"_session",
"=",
"requests",
".",
"Session",
"(",
")",
"self",
".",
"_session",
".",
"headers",
".",
"update",
"(",
... | Set session information | [
"Set",
"session",
"information"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L340-L345 |
8,079 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.random | def random(self, pages=1):
""" Request a random page title or list of random titles
Args:
pages (int): Number of random pages to return
Returns:
list or int: A list of random page titles or a random page \
title if pages = 1 "... | python | def random(self, pages=1):
""" Request a random page title or list of random titles
Args:
pages (int): Number of random pages to return
Returns:
list or int: A list of random page titles or a random page \
title if pages = 1 "... | [
"def",
"random",
"(",
"self",
",",
"pages",
"=",
"1",
")",
":",
"if",
"pages",
"is",
"None",
"or",
"pages",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Number of pages must be greater than 0\"",
")",
"query_params",
"=",
"{",
"\"list\"",
":",
"\"random\"",... | Request a random page title or list of random titles
Args:
pages (int): Number of random pages to return
Returns:
list or int: A list of random page titles or a random page \
title if pages = 1 | [
"Request",
"a",
"random",
"page",
"title",
"or",
"list",
"of",
"random",
"titles"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L371-L389 |
8,080 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.search | def search(self, query, results=10, suggestion=False):
""" Search for similar titles
Args:
query (str): Page title
results (int): Number of pages to return
suggestion (bool): Use suggestion
Returns:
tuple or list: tuple (li... | python | def search(self, query, results=10, suggestion=False):
""" Search for similar titles
Args:
query (str): Page title
results (int): Number of pages to return
suggestion (bool): Use suggestion
Returns:
tuple or list: tuple (li... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"results",
"=",
"10",
",",
"suggestion",
"=",
"False",
")",
":",
"self",
".",
"_check_query",
"(",
"query",
",",
"\"Query must be specified\"",
")",
"search_params",
"=",
"{",
"\"list\"",
":",
"\"search\"",
... | Search for similar titles
Args:
query (str): Page title
results (int): Number of pages to return
suggestion (bool): Use suggestion
Returns:
tuple or list: tuple (list results, suggestion) if \
suggest... | [
"Search",
"for",
"similar",
"titles"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L392-L426 |
8,081 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.suggest | def suggest(self, query):
""" Gather suggestions based on the provided title or None if no
suggestions found
Args:
query (str): Page title
Returns:
String or None: Suggested page title or **None** if no \
sugges... | python | def suggest(self, query):
""" Gather suggestions based on the provided title or None if no
suggestions found
Args:
query (str): Page title
Returns:
String or None: Suggested page title or **None** if no \
sugges... | [
"def",
"suggest",
"(",
"self",
",",
"query",
")",
":",
"res",
",",
"suggest",
"=",
"self",
".",
"search",
"(",
"query",
",",
"results",
"=",
"1",
",",
"suggestion",
"=",
"True",
")",
"try",
":",
"title",
"=",
"suggest",
"or",
"res",
"[",
"0",
"]"... | Gather suggestions based on the provided title or None if no
suggestions found
Args:
query (str): Page title
Returns:
String or None: Suggested page title or **None** if no \
suggestion found | [
"Gather",
"suggestions",
"based",
"on",
"the",
"provided",
"title",
"or",
"None",
"if",
"no",
"suggestions",
"found"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L429-L443 |
8,082 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.geosearch | def geosearch(
self,
latitude=None,
longitude=None,
radius=1000,
title=None,
auto_suggest=True,
results=10,
):
""" Search for pages that relate to the provided geocoords or near
the page
Args:
latitude (Decimal ... | python | def geosearch(
self,
latitude=None,
longitude=None,
radius=1000,
title=None,
auto_suggest=True,
results=10,
):
""" Search for pages that relate to the provided geocoords or near
the page
Args:
latitude (Decimal ... | [
"def",
"geosearch",
"(",
"self",
",",
"latitude",
"=",
"None",
",",
"longitude",
"=",
"None",
",",
"radius",
"=",
"1000",
",",
"title",
"=",
"None",
",",
"auto_suggest",
"=",
"True",
",",
"results",
"=",
"10",
",",
")",
":",
"def",
"test_lat_long",
"... | Search for pages that relate to the provided geocoords or near
the page
Args:
latitude (Decimal or None): Latitude geocoord; must be \
coercable to decimal
longitude (Decimal or None): Longitude geocoord; must be \
... | [
"Search",
"for",
"pages",
"that",
"relate",
"to",
"the",
"provided",
"geocoords",
"or",
"near",
"the",
"page"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L446-L505 |
8,083 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.opensearch | def opensearch(self, query, results=10, redirect=True):
""" Execute a MediaWiki opensearch request, similar to search box
suggestions and conforming to the OpenSearch specification
Args:
query (str): Title to search for
results (int): Number of pages with... | python | def opensearch(self, query, results=10, redirect=True):
""" Execute a MediaWiki opensearch request, similar to search box
suggestions and conforming to the OpenSearch specification
Args:
query (str): Title to search for
results (int): Number of pages with... | [
"def",
"opensearch",
"(",
"self",
",",
"query",
",",
"results",
"=",
"10",
",",
"redirect",
"=",
"True",
")",
":",
"self",
".",
"_check_query",
"(",
"query",
",",
"\"Query must be specified\"",
")",
"query_params",
"=",
"{",
"\"action\"",
":",
"\"opensearch\... | Execute a MediaWiki opensearch request, similar to search box
suggestions and conforming to the OpenSearch specification
Args:
query (str): Title to search for
results (int): Number of pages within the radius to return
redirect (bool): If **False*... | [
"Execute",
"a",
"MediaWiki",
"opensearch",
"request",
"similar",
"to",
"search",
"box",
"suggestions",
"and",
"conforming",
"to",
"the",
"OpenSearch",
"specification"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L508-L540 |
8,084 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.prefixsearch | def prefixsearch(self, prefix, results=10):
""" Perform a prefix search using the provided prefix string
Args:
prefix (str): Prefix string to use for search
results (int): Number of pages with the prefix to return
Returns:
list: List of pa... | python | def prefixsearch(self, prefix, results=10):
""" Perform a prefix search using the provided prefix string
Args:
prefix (str): Prefix string to use for search
results (int): Number of pages with the prefix to return
Returns:
list: List of pa... | [
"def",
"prefixsearch",
"(",
"self",
",",
"prefix",
",",
"results",
"=",
"10",
")",
":",
"self",
".",
"_check_query",
"(",
"prefix",
",",
"\"Prefix must be specified\"",
")",
"query_params",
"=",
"{",
"\"list\"",
":",
"\"prefixsearch\"",
",",
"\"pssearch\"",
":... | Perform a prefix search using the provided prefix string
Args:
prefix (str): Prefix string to use for search
results (int): Number of pages with the prefix to return
Returns:
list: List of page titles
Note:
**Per the do... | [
"Perform",
"a",
"prefix",
"search",
"using",
"the",
"provided",
"prefix",
"string"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L543-L572 |
8,085 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.summary | def summary(self, title, sentences=0, chars=0, auto_suggest=True, redirect=True):
""" Get the summary for the title in question
Args:
title (str): Page title to summarize
sentences (int): Number of sentences to return in summary
chars (int): Number of... | python | def summary(self, title, sentences=0, chars=0, auto_suggest=True, redirect=True):
""" Get the summary for the title in question
Args:
title (str): Page title to summarize
sentences (int): Number of sentences to return in summary
chars (int): Number of... | [
"def",
"summary",
"(",
"self",
",",
"title",
",",
"sentences",
"=",
"0",
",",
"chars",
"=",
"0",
",",
"auto_suggest",
"=",
"True",
",",
"redirect",
"=",
"True",
")",
":",
"page_info",
"=",
"self",
".",
"page",
"(",
"title",
",",
"auto_suggest",
"=",
... | Get the summary for the title in question
Args:
title (str): Page title to summarize
sentences (int): Number of sentences to return in summary
chars (int): Number of characters to return in summary
auto_suggest (bool): Run auto-suggest on titl... | [
"Get",
"the",
"summary",
"for",
"the",
"title",
"in",
"question"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L575-L591 |
8,086 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.categorytree | def categorytree(self, category, depth=5):
""" Generate the Category Tree for the given categories
Args:
category(str or list of strings): Category name(s)
depth(int): Depth to traverse the tree
Returns:
dict: Category tree structure
... | python | def categorytree(self, category, depth=5):
""" Generate the Category Tree for the given categories
Args:
category(str or list of strings): Category name(s)
depth(int): Depth to traverse the tree
Returns:
dict: Category tree structure
... | [
"def",
"categorytree",
"(",
"self",
",",
"category",
",",
"depth",
"=",
"5",
")",
":",
"def",
"__cat_tree_rec",
"(",
"cat",
",",
"depth",
",",
"tree",
",",
"level",
",",
"categories",
",",
"links",
")",
":",
"\"\"\" recursive function to build out the tree \"\... | Generate the Category Tree for the given categories
Args:
category(str or list of strings): Category name(s)
depth(int): Depth to traverse the tree
Returns:
dict: Category tree structure
Note:
Set depth to **None** to g... | [
"Generate",
"the",
"Category",
"Tree",
"for",
"the",
"given",
"categories"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L662-L770 |
8,087 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.page | def page(
self, title=None, pageid=None, auto_suggest=True, redirect=True, preload=False
):
""" Get MediaWiki page based on the provided title or pageid
Args:
title (str): Page title
pageid (int): MediaWiki page identifier
auto-suggest (bo... | python | def page(
self, title=None, pageid=None, auto_suggest=True, redirect=True, preload=False
):
""" Get MediaWiki page based on the provided title or pageid
Args:
title (str): Page title
pageid (int): MediaWiki page identifier
auto-suggest (bo... | [
"def",
"page",
"(",
"self",
",",
"title",
"=",
"None",
",",
"pageid",
"=",
"None",
",",
"auto_suggest",
"=",
"True",
",",
"redirect",
"=",
"True",
",",
"preload",
"=",
"False",
")",
":",
"if",
"(",
"title",
"is",
"None",
"or",
"title",
".",
"strip"... | Get MediaWiki page based on the provided title or pageid
Args:
title (str): Page title
pageid (int): MediaWiki page identifier
auto-suggest (bool): **True:** Allow page title auto-suggest
redirect (bool): **True:** Follow page redirects
... | [
"Get",
"MediaWiki",
"page",
"based",
"on",
"the",
"provided",
"title",
"or",
"pageid"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L772-L802 |
8,088 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki.wiki_request | def wiki_request(self, params):
""" Make a request to the MediaWiki API using the given search
parameters
Args:
params (dict): Request parameters
Returns:
A parsed dict of the JSON response
Note:
Useful when wanting... | python | def wiki_request(self, params):
""" Make a request to the MediaWiki API using the given search
parameters
Args:
params (dict): Request parameters
Returns:
A parsed dict of the JSON response
Note:
Useful when wanting... | [
"def",
"wiki_request",
"(",
"self",
",",
"params",
")",
":",
"params",
"[",
"\"format\"",
"]",
"=",
"\"json\"",
"if",
"\"action\"",
"not",
"in",
"params",
":",
"params",
"[",
"\"action\"",
"]",
"=",
"\"query\"",
"limit",
"=",
"self",
".",
"_rate_limit",
... | Make a request to the MediaWiki API using the given search
parameters
Args:
params (dict): Request parameters
Returns:
A parsed dict of the JSON response
Note:
Useful when wanting to query the MediaWiki site for some \
... | [
"Make",
"a",
"request",
"to",
"the",
"MediaWiki",
"API",
"using",
"the",
"given",
"search",
"parameters"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L804-L832 |
8,089 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki._get_site_info | def _get_site_info(self):
""" Parse out the Wikimedia site information including
API Version and Extensions """
response = self.wiki_request(
{"meta": "siteinfo", "siprop": "extensions|general"}
)
# parse what we need out here!
query = response.get("query", N... | python | def _get_site_info(self):
""" Parse out the Wikimedia site information including
API Version and Extensions """
response = self.wiki_request(
{"meta": "siteinfo", "siprop": "extensions|general"}
)
# parse what we need out here!
query = response.get("query", N... | [
"def",
"_get_site_info",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"wiki_request",
"(",
"{",
"\"meta\"",
":",
"\"siteinfo\"",
",",
"\"siprop\"",
":",
"\"extensions|general\"",
"}",
")",
"# parse what we need out here!",
"query",
"=",
"response",
".",
... | Parse out the Wikimedia site information including
API Version and Extensions | [
"Parse",
"out",
"the",
"Wikimedia",
"site",
"information",
"including",
"API",
"Version",
"and",
"Extensions"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L835-L869 |
8,090 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki._check_error_response | def _check_error_response(response, query):
""" check for default error messages and throw correct exception """
if "error" in response:
http_error = ["HTTP request timed out.", "Pool queue is full"]
geo_error = [
"Page coordinates unknown.",
"One ... | python | def _check_error_response(response, query):
""" check for default error messages and throw correct exception """
if "error" in response:
http_error = ["HTTP request timed out.", "Pool queue is full"]
geo_error = [
"Page coordinates unknown.",
"One ... | [
"def",
"_check_error_response",
"(",
"response",
",",
"query",
")",
":",
"if",
"\"error\"",
"in",
"response",
":",
"http_error",
"=",
"[",
"\"HTTP request timed out.\"",
",",
"\"Pool queue is full\"",
"]",
"geo_error",
"=",
"[",
"\"Page coordinates unknown.\"",
",",
... | check for default error messages and throw correct exception | [
"check",
"for",
"default",
"error",
"messages",
"and",
"throw",
"correct",
"exception"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L874-L889 |
8,091 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki._get_response | def _get_response(self, params):
""" wrap the call to the requests package """
return self._session.get(
self._api_url, params=params, timeout=self._timeout
).json(encoding="utf8") | python | def _get_response(self, params):
""" wrap the call to the requests package """
return self._session.get(
self._api_url, params=params, timeout=self._timeout
).json(encoding="utf8") | [
"def",
"_get_response",
"(",
"self",
",",
"params",
")",
":",
"return",
"self",
".",
"_session",
".",
"get",
"(",
"self",
".",
"_api_url",
",",
"params",
"=",
"params",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
".",
"json",
"(",
"encoding",
... | wrap the call to the requests package | [
"wrap",
"the",
"call",
"to",
"the",
"requests",
"package"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L897-L901 |
8,092 | barrust/mediawiki | mediawiki/mediawiki.py | MediaWiki._post_response | def _post_response(self, params):
""" wrap a post call to the requests package """
return self._session.post(
self._api_url, data=params, timeout=self._timeout
).json(encoding="utf8") | python | def _post_response(self, params):
""" wrap a post call to the requests package """
return self._session.post(
self._api_url, data=params, timeout=self._timeout
).json(encoding="utf8") | [
"def",
"_post_response",
"(",
"self",
",",
"params",
")",
":",
"return",
"self",
".",
"_session",
".",
"post",
"(",
"self",
".",
"_api_url",
",",
"data",
"=",
"params",
",",
"timeout",
"=",
"self",
".",
"_timeout",
")",
".",
"json",
"(",
"encoding",
... | wrap a post call to the requests package | [
"wrap",
"a",
"post",
"call",
"to",
"the",
"requests",
"package"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawiki.py#L903-L907 |
8,093 | barrust/mediawiki | mediawiki/utilities.py | parse_all_arguments | def parse_all_arguments(func):
""" determine all positional and named arguments as a dict """
args = dict()
if sys.version_info < (3, 0):
func_args = inspect.getargspec(func)
if func_args.defaults is not None:
val = len(func_args.defaults)
for i, itm in enumerate(func... | python | def parse_all_arguments(func):
""" determine all positional and named arguments as a dict """
args = dict()
if sys.version_info < (3, 0):
func_args = inspect.getargspec(func)
if func_args.defaults is not None:
val = len(func_args.defaults)
for i, itm in enumerate(func... | [
"def",
"parse_all_arguments",
"(",
"func",
")",
":",
"args",
"=",
"dict",
"(",
")",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
"0",
")",
":",
"func_args",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"if",
"func_args",
".",
"defaul... | determine all positional and named arguments as a dict | [
"determine",
"all",
"positional",
"and",
"named",
"arguments",
"as",
"a",
"dict"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/utilities.py#L11-L26 |
8,094 | barrust/mediawiki | mediawiki/utilities.py | str_or_unicode | def str_or_unicode(text):
""" handle python 3 unicode and python 2.7 byte strings """
encoding = sys.stdout.encoding
if sys.version_info > (3, 0):
return text.encode(encoding).decode(encoding)
return text.encode(encoding) | python | def str_or_unicode(text):
""" handle python 3 unicode and python 2.7 byte strings """
encoding = sys.stdout.encoding
if sys.version_info > (3, 0):
return text.encode(encoding).decode(encoding)
return text.encode(encoding) | [
"def",
"str_or_unicode",
"(",
"text",
")",
":",
"encoding",
"=",
"sys",
".",
"stdout",
".",
"encoding",
"if",
"sys",
".",
"version_info",
">",
"(",
"3",
",",
"0",
")",
":",
"return",
"text",
".",
"encode",
"(",
"encoding",
")",
".",
"decode",
"(",
... | handle python 3 unicode and python 2.7 byte strings | [
"handle",
"python",
"3",
"unicode",
"and",
"python",
"2",
".",
"7",
"byte",
"strings"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/utilities.py#L78-L83 |
8,095 | barrust/mediawiki | mediawiki/utilities.py | is_relative_url | def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True | python | def is_relative_url(url):
""" simple method to determine if a url is relative or absolute """
if url.startswith("#"):
return None
if url.find("://") > 0 or url.startswith("//"):
# either 'http(s)://...' or '//cdn...' and therefore absolute
return False
return True | [
"def",
"is_relative_url",
"(",
"url",
")",
":",
"if",
"url",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"return",
"None",
"if",
"url",
".",
"find",
"(",
"\"://\"",
")",
">",
"0",
"or",
"url",
".",
"startswith",
"(",
"\"//\"",
")",
":",
"# either 'htt... | simple method to determine if a url is relative or absolute | [
"simple",
"method",
"to",
"determine",
"if",
"a",
"url",
"is",
"relative",
"or",
"absolute"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/utilities.py#L86-L93 |
8,096 | barrust/mediawiki | setup.py | read_file | def read_file(filepath):
""" read the file """
with io.open(filepath, "r") as filepointer:
res = filepointer.read()
return res | python | def read_file(filepath):
""" read the file """
with io.open(filepath, "r") as filepointer:
res = filepointer.read()
return res | [
"def",
"read_file",
"(",
"filepath",
")",
":",
"with",
"io",
".",
"open",
"(",
"filepath",
",",
"\"r\"",
")",
"as",
"filepointer",
":",
"res",
"=",
"filepointer",
".",
"read",
"(",
")",
"return",
"res"
] | read the file | [
"read",
"the",
"file"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/setup.py#L14-L18 |
8,097 | barrust/mediawiki | mediawiki/mediawikipage.py | MediaWikiPage._pull_content_revision_parent | def _pull_content_revision_parent(self):
""" combine the pulling of these three properties """
if self._revision_id is None:
query_params = {
"prop": "extracts|revisions",
"explaintext": "",
"rvprop": "ids",
}
query_par... | python | def _pull_content_revision_parent(self):
""" combine the pulling of these three properties """
if self._revision_id is None:
query_params = {
"prop": "extracts|revisions",
"explaintext": "",
"rvprop": "ids",
}
query_par... | [
"def",
"_pull_content_revision_parent",
"(",
"self",
")",
":",
"if",
"self",
".",
"_revision_id",
"is",
"None",
":",
"query_params",
"=",
"{",
"\"prop\"",
":",
"\"extracts|revisions\"",
",",
"\"explaintext\"",
":",
"\"\"",
",",
"\"rvprop\"",
":",
"\"ids\"",
",",... | combine the pulling of these three properties | [
"combine",
"the",
"pulling",
"of",
"these",
"three",
"properties"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawikipage.py#L127-L142 |
8,098 | barrust/mediawiki | mediawiki/mediawikipage.py | MediaWikiPage.section | def section(self, section_title):
""" Plain text section content
Args:
section_title (str): Name of the section to pull
Returns:
str: The content of the section
Note:
Returns **None** if section title is not found; only text \
... | python | def section(self, section_title):
""" Plain text section content
Args:
section_title (str): Name of the section to pull
Returns:
str: The content of the section
Note:
Returns **None** if section title is not found; only text \
... | [
"def",
"section",
"(",
"self",
",",
"section_title",
")",
":",
"section",
"=",
"\"== {0} ==\"",
".",
"format",
"(",
"section_title",
")",
"try",
":",
"content",
"=",
"self",
".",
"content",
"index",
"=",
"content",
".",
"index",
"(",
"section",
")",
"+",... | Plain text section content
Args:
section_title (str): Name of the section to pull
Returns:
str: The content of the section
Note:
Returns **None** if section title is not found; only text \
between title and next section... | [
"Plain",
"text",
"section",
"content"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawikipage.py#L412-L447 |
8,099 | barrust/mediawiki | mediawiki/mediawikipage.py | MediaWikiPage.parse_section_links | def parse_section_links(self, section_title):
""" Parse all links within a section
Args:
section_title (str): Name of the section to pull
Returns:
list: List of (title, url) tuples
Note:
Returns **None** if section title is not... | python | def parse_section_links(self, section_title):
""" Parse all links within a section
Args:
section_title (str): Name of the section to pull
Returns:
list: List of (title, url) tuples
Note:
Returns **None** if section title is not... | [
"def",
"parse_section_links",
"(",
"self",
",",
"section_title",
")",
":",
"soup",
"=",
"BeautifulSoup",
"(",
"self",
".",
"html",
",",
"\"html.parser\"",
")",
"headlines",
"=",
"soup",
".",
"find_all",
"(",
"\"span\"",
",",
"{",
"\"class\"",
":",
"\"mw-head... | Parse all links within a section
Args:
section_title (str): Name of the section to pull
Returns:
list: List of (title, url) tuples
Note:
Returns **None** if section title is not found
Note:
Side effect is to... | [
"Parse",
"all",
"links",
"within",
"a",
"section"
] | 292e0be6c752409062dceed325d74839caf16a9b | https://github.com/barrust/mediawiki/blob/292e0be6c752409062dceed325d74839caf16a9b/mediawiki/mediawikipage.py#L449-L475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.