text stringlengths 18 773k |
|---|
def foreign(self, value, context=None):
"""Construct a string-like representation for an iterable of string-like objects."""
if self.separator is None:
separator = ' '
else:
separator = self.separator.strip() if self.strip and hasattr(self.separator, 'strip') else self.separator
value = self._clean(... |
def tob32(val):
"""Return provided 32 bit value as a string of four bytes."""
ret = bytearray(4)
ret[0] = (val>>24)&M8
ret[1] = (val>>16)&M8
ret[2] = (val>>8)&M8
ret[3] = val&M8
return ret |
def bintoihex(buf, spos=0x0000):
"""Convert binary buffer to ihex and return as string."""
c = 0
olen = len(buf)
ret = ""
# 16 byte lines
while (c+0x10) <= olen:
adr = c + spos
l = ':10{0:04X}00'.format(adr)
sum = 0x10+((adr>>8)&M8)+(adr&M8)
for j in range(0,0x10)... |
def op_gen(mcode):
"""Generate a machine instruction using the op gen table."""
gen = op_tbl[mcode[0]]
ret = gen[0] # opcode
nargs = len(gen)
i = 1
while i < nargs:
if i < len(mcode): # or assume they are same len
ret |= (mcode[i]&gen[i][0]) << gen[i][1]
i += 1
re... |
def scanerror(self, msg):
"""Emit scan error and abort assembly."""
error('scan error: ' + msg + ' on line {}'.format(self.sline))
sys.exit(-1) |
def parsewarn(self, msg, line=None):
"""Emit parse warning."""
if line is None:
line = self.sline
self.dowarn('warning: ' + msg + ' on line {}'.format(line)) |
def parseerror(self, msg, line=None):
"""Emit parse error and abort assembly."""
if line is None:
line = self.sline
error('parse error: ' + msg + ' on line {}'.format(line))
sys.exit(-2) |
def parse(self):
"""Parse input."""
self.__next__()
while self.sym['type'] != 'EOF':
if self.sym['type'] == 'LABEL':
self.__label__()
elif self.sym['type'] == 'MNEMONIC':
self.__instruction__()
elif self.sym['type'] == 'NAME' or... |
def resync(
ctx,
opts,
owner_repo_package,
skip_errors,
wait_interval,
no_wait_for_sync,
sync_attempts,
):
"""
Resynchronise a package in a repository.
This requires appropriate permissions for package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), t... |
def resync_package(ctx, opts, owner, repo, slug, skip_errors):
"""Resynchronise a package."""
click.echo(
"Resynchonising the %(slug)s package ... "
% {"slug": click.style(slug, bold=True)},
nl=False,
)
context_msg = "Failed to resynchronise package!"
with handle_api_excepti... |
def make_create_payload(**kwargs):
"""Create payload for upload/check-upload operations."""
payload = {}
# Add non-empty arguments
for k, v in six.iteritems(kwargs):
if v is not None:
payload[k] = v
return payload |
def create_package(package_format, owner, repo, **kwargs):
"""Create a new package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
upload = getattr(client, "packages_upload_%s_with_http_info" % package_format)
data, _, headers = upload(
owner=o... |
def validate_create_package(package_format, owner, repo, **kwargs):
"""Validate parameters for creating a package."""
client = get_packages_api()
with catch_raise_api_exception():
check = getattr(
client, "packages_validate_upload_%s_with_http_info" % package_format
)
_... |
def copy_package(owner, repo, identifier, destination):
"""Copy a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_copy_with_http_info(
owner=owner,
repo=repo,
identifier=identifier... |
def move_package(owner, repo, identifier, destination):
"""Move a package to another repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_move_with_http_info(
owner=owner,
repo=repo,
identifier=identifier... |
def delete_package(owner, repo, identifier):
"""Delete a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
_, _, headers = client.packages_delete_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate_li... |
def resync_package(owner, repo, identifier):
"""Resync a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_resync_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratelimits.maybe_rate... |
def get_package_status(owner, repo, identifier):
"""Get the status for a package in a repository."""
client = get_packages_api()
with catch_raise_api_exception():
data, _, headers = client.packages_status_with_http_info(
owner=owner, repo=repo, identifier=identifier
)
ratel... |
def list_packages(owner, repo, **kwargs):
"""List packages for a repository."""
client = get_packages_api()
api_kwargs = {}
api_kwargs.update(utils.get_page_kwargs(**kwargs))
api_kwargs.update(utils.get_query_kwargs(**kwargs))
with catch_raise_api_exception():
data, _, headers = client... |
def get_package_formats():
"""Get the list of available package formats and parameters."""
# pylint: disable=fixme
# HACK: This obviously isn't great, and it is subject to change as
# the API changes, but it'll do for now as a interim method of
# introspection to get the parameters we need.
def ... |
def get_package_format_names(predicate=None):
"""Get names for available package formats."""
return [
k
for k, v in six.iteritems(get_package_formats())
if not predicate or predicate(k, v)
] |
def start(opts, bot, event):
"""Usage: start [--name=<name>]
Start a timer.
Without _name_, start the default timer.
To run more than one timer at once, pass _name_ to start and stop.
"""
name = opts['--name']
now = datetime.datetime.now()
bot.timers[name] = now
return bot.start... |
def stop(opts, bot, event):
"""Usage: stop [--name=<name>] [--notify=<slack_username>]
Stop a timer.
_name_ works the same as for `start`.
If given _slack_username_, reply with an at-mention to the given user.
"""
name = opts['--name']
slack_username = opts['--notify']
now = datetime... |
def get_user_token(login, password):
"""Retrieve user token from the API (via authentication)."""
client = get_user_api()
# Never use API key for the token endpoint
config = cloudsmith_api.Configuration()
set_api_key(config, None)
with catch_raise_api_exception():
data, _, headers = cl... |
def get_user_brief():
"""Retrieve brief for current user (if any)."""
client = get_user_api()
with catch_raise_api_exception():
data, _, headers = client.user_self_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return data.authenticated, data.slug, data.email, data.name |
def catch_raise_api_exception():
"""Context manager that translates upstream API exceptions."""
try:
yield
except _ApiException as exc:
detail = None
fields = None
if exc.body:
try:
# pylint: disable=no-member
data = json.loads(exc... |
def get_default_filepath(cls):
"""Get the default filepath for the configuratin file."""
if not cls.config_files:
return None
if not cls.config_searchpath:
return None
filename = cls.config_files[0]
filepath = cls.config_searchpath[0]
return os.pat... |
def create_default_file(cls, data=None, mode=None):
"""Create a config file and override data if specified."""
filepath = cls.get_default_filepath()
if not filepath:
return False
filename = os.path.basename(filepath)
config = read_file(get_data_path(), filename)
... |
def has_default_file(cls):
"""Check if a configuration file exists."""
for filename in cls.config_files:
for searchpath in cls.config_searchpath:
path = os.path.join(searchpath, filename)
if os.path.exists(path):
return True
return... |
def load_config(cls, opts, path=None, profile=None):
"""Load a configuration file into an options object."""
if path and os.path.exists(path):
if os.path.isdir(path):
cls.config_searchpath.insert(0, path)
else:
cls.config_files.insert(0, path)
... |
def load_config_file(self, path, profile=None):
"""Load the standard config file."""
config_cls = self.get_config_reader()
return config_cls.load_config(self, path, profile=profile) |
def load_creds_file(self, path, profile=None):
"""Load the credentials config file."""
config_cls = self.get_creds_reader()
return config_cls.load_config(self, path, profile=profile) |
def api_headers(self, value):
"""Set value for API headers."""
value = validators.validate_api_headers("api_headers", value)
self._set_option("api_headers", value) |
def error_retry_codes(self, value):
"""Set value for error_retry_codes."""
if isinstance(value, six.string_types):
value = [int(x) for x in value.split(",")]
self._set_option("error_retry_codes", value) |
def _set_option(self, name, value, allow_clear=False):
"""Set value for an option."""
if not allow_clear:
# Prevent clears if value was set
try:
current_value = self._get_option(name)
if value is None and current_value is not None:
... |
def get_rate_limits():
"""Retrieve status (and optionally) version from the API."""
client = get_rates_api()
with catch_raise_api_exception():
data, _, headers = client.rates_limits_list_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
return {
k: RateLimitsInfo.from_... |
def loads(self, value, context=None):
"""Attempt to load a string-based value into the native representation.
Empty strings are treated as ``None`` values.
"""
if value == '' or (hasattr(value, 'strip') and value.strip() == ''):
return None
return self.native(value) |
def dump(self, fh, value, context=None):
"""Attempt to transform and write a string-based foreign value to the given file-like object.
Returns the length written.
"""
value = self.dumps(value)
fh.write(value)
return len(value) |
def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
if self.strip and hasattr(value, 'strip'):
value = value.strip()
if self.none and value == '':
return None
if self.encoding and isinstance(value, bytes):
return value.decode(self.... |
def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
value = super().native(value, context)
if value is None: return
try:
return self.ingress(value)
except Exception as e:
raise Concern("Unable to transform incoming value: {0}", str(... |
def rates(ctx, opts):
"""Check current API rate limits."""
click.echo("Retrieving rate limits ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
resources_limits = get_rate_limits... |
def service(ctx, opts):
"""Check the status of the Cloudsmith service."""
click.echo("Retrieving service status ... ", nl=False)
context_msg = "Failed to retrieve status!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
status, version ... |
def list_distros(package_format=None):
"""List available distributions."""
client = get_distros_api()
# pylint: disable=fixme
# TODO(ls): Add package format param on the server-side to filter distros
# instead of doing it here.
with catch_raise_api_exception():
distros, _, headers = cli... |
def total_seconds(td):
"""For those with older versions of Python, a pure-Python
implementation of Python 2.7's :meth:`~datetime.timedelta.total_seconds`.
Args:
td (datetime.timedelta): The timedelta to convert to seconds.
Returns:
float: total number of seconds
>>> td = timedelta(... |
def dt_to_timestamp(dt):
"""Converts from a :class:`~datetime.datetime` object to an integer
timestamp, suitable interoperation with :func:`time.time` and
other `Epoch-based timestamps`.
.. _Epoch-based timestamps: https://en.wikipedia.org/wiki/Unix_time
>>> abs(round(time.time() - dt_to_timestamp... |
def isoparse(iso_str):
"""Parses the limited subset of `ISO8601-formatted time`_ strings as
returned by :meth:`datetime.datetime.isoformat`.
>>> epoch_dt = datetime.utcfromtimestamp(0)
>>> iso_str = epoch_dt.isoformat()
>>> print(iso_str)
1970-01-01T00:00:00
>>> isoparse(iso_str)
dateti... |
def parse_timedelta(text):
"""Robustly parses a short text description of a time period into a
:class:`datetime.timedelta`. Supports weeks, days, hours, minutes,
and seconds, with or without decimal points:
Args:
text (str): Text to parse.
Returns:
datetime.timedelta
Raises:
... |
def decimal_relative_time(d, other=None, ndigits=0, cardinalize=True):
"""Get a tuple representing the relative time difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and now.
Args:
d (datetime): The first datetime object.
other (datetime): An... |
def relative_time(d, other=None, ndigits=0):
"""Get a string representation of the difference between two
:class:`~datetime.datetime` objects or one
:class:`~datetime.datetime` and the current time. Handles past and
future times.
Args:
d (datetime): The first datetime object.
other ... |
def strpdate(string, format):
"""Parse the date string according to the format in `format`. Returns a
:class:`date` object. Internally, :meth:`datetime.strptime` is used to
parse the string and thus conversion specifiers for time fields (e.g. `%H`)
may be provided; these will be parsed but ignored.
... |
def daterange(start, stop, step=1, inclusive=False):
"""In the spirit of :func:`range` and :func:`xrange`, the `daterange`
generator that yields a sequence of :class:`~datetime.date`
objects, starting at *start*, incrementing by *step*, until *stop*
is reached.
When *inclusive* is True, the final d... |
def distros(ctx, opts, package_format):
"""List available distributions."""
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
click.echo("Getting list of distributions ... ", nl=False, err=use_stderr)
context_msg = "Failed to get list of ... |
def packages(ctx, opts, owner_repo, page, page_size, query):
"""
List packages for a repository.
OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the
REPO name to list packages for that namespace and repository. All separated
by a slash.
You can use the search query (-q|--query)... |
def repos(ctx, opts, owner, page, page_size):
"""
List repositories for a namespace (owner).
OWNER: Specify the OWNER namespace (i.e. user or org) to list the
repositories for that namespace.
If OWNER isn't specified it'll default to the currently authenticated user
(if any). If you're unauthe... |
def _get_package_status(package):
"""Get the status for a package."""
status = package["status_str"] or "Unknown"
stage = package["stage_str"] or "Unknown"
if stage == "Fully Synchronised":
return status
return "%(status)s / %(stage)s" % {"status": status, "stage": stage} |
def boolify(value, nullable=False, return_string=False):
"""Convert a number, string, or sequence type into a pure boolean.
Args:
value (number, string, sequence): pretty much anything
Returns:
bool: boolean representation of the given value
Examples:
>>> [boolify(x) for x in ... |
def typify(value, type_hint=None):
"""Take a primitive value, usually a string, and try to make a more relevant type out of it.
An optional type_hint will try to coerce the value to that type.
Args:
value (Any): Usually a string, not a sequence
type_hint (type or Tuple[type]):
Examples... |
def listify(val, return_type=tuple):
"""
Examples:
>>> listify('abc', return_type=list)
['abc']
>>> listify(None)
()
>>> listify(False)
(False,)
>>> listify(('a', 'b', 'c'), return_type=list)
['a', 'b', 'c']
"""
# TODO: flatlistify((1, 2, 3... |
def open(rootdir, mode='a'):
# ----------------------------------------------------------------------
# https://github.com/Blosc/bcolz/blob/master/bcolz/toplevel.py#L104-L132
# ----------------------------------------------------------------------
"""
open(rootdir, mode='a')
Open a disk-based c... |
def delete(ctx, opts, owner_repo_package, yes):
"""
Delete a package from a repository.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your... |
def validate_owner_repo_identifier(ctx, param, value):
"""Ensure that owner/repo/identifier is formatted correctly."""
# pylint: disable=unused-argument
form = "OWNER/REPO/IDENTIFIER"
return validators.validate_slashes(param, value, minimum=3, maximum=3, form=form) |
def common_entitlements_options(f):
"""Add common options for entitlement commands."""
@click.option(
"--show-tokens",
default=False,
is_flag=True,
help="Show entitlement token string contents in output.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx... |
def list_entitlements_options(f):
"""Options for list entitlements subcommand."""
@common_entitlements_options
@decorators.common_cli_config_options
@decorators.common_cli_list_options
@decorators.common_cli_output_options
@decorators.common_api_auth_options
@decorators.initialise_api
@... |
def list_entitlements(ctx, opts, owner_repo, page, page_size, show_tokens):
"""
List entitlements for a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to list entitlements for. All separated by a slash.
Example: 'your-org/your-repo'... |
def print_entitlements(opts, data, page_info=None, show_list_info=True):
"""Print entitlements as a table or output in another format."""
if utils.maybe_print_as_json(opts, data, page_info):
return
headers = ["Name", "Token", "Created / Updated", "Identifier"]
rows = []
for entitlement in ... |
def create(ctx, opts, owner_repo, show_tokens, name, token):
"""
Create a new entitlement in a repository.
- OWNER/REPO: Specify the OWNER namespace (i.e. user or org), and the REPO
name where you want to create an entitlement. All separated by a slash.
Example: 'your-org/your-repo'
Ful... |
def delete(ctx, opts, owner_repo_identifier, yes):
"""
Delete an entitlement from a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
Example: 'your-org/your... |
def update(ctx, opts, owner_repo_identifier, show_tokens, name, token):
"""
Update (set) a entitlement in a repository.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identified by IDENTIFIER. All
separated by a slash.
... |
def refresh(ctx, opts, owner_repo_identifier, show_tokens, yes):
"""
Refresh an entitlement in a repository.
Note that this changes the token associated with the entitlement.
- OWNER/REPO/IDENTIFIER: Specify the OWNER namespace (i.e. user or org),
and the REPO name that has an entitlement identi... |
def sync(ctx, opts, owner_repo, show_tokens, source, yes):
"""
Sync entitlements from another repository.
***WARNING*** This will DELETE ALL of the existing entitlements in the
repository and replace them with entitlements from the source repository.
- OWNER/REPO: Specify the OWNER namespace (i.e.... |
def ctime(message=None):
"Counts the time spent in some context"
t = time.time()
yield
if message:
print message + ":\t",
print round(time.time() - t, 4), "sec" |
def maybe_rate_limit(client, headers, atexit=False):
"""Optionally pause the process based on suggested rate interval."""
# pylint: disable=fixme
# pylint: disable=global-statement
# FIXME: Yes, I know this is not great. We'll fix it later. :-)
global LAST_CLIENT, LAST_HEADERS
if LAST_CLIENT an... |
def rate_limit(client, headers, atexit=False):
"""Pause the process based on suggested rate interval."""
if not client or not headers:
return False
if not getattr(client.config, "rate_limit", False):
return False
rate_info = RateLimitsInfo.from_headers(headers)
if not rate_info or ... |
def get_status(with_version=False):
"""Retrieve status (and optionally) version from the API."""
client = get_status_api()
with catch_raise_api_exception():
data, _, headers = client.status_check_basic_with_http_info()
ratelimits.maybe_rate_limit(client, headers)
if with_version:
... |
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
"""Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element... |
def call_each(seq):
"""Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None
"""
try:
reduce(lambda _, y: y(), seq)
except TypeError as e:
if text_type(e) != "reduce() of empty sequence with no initial value":
raise |
def transform_api_header_authorization(param, value):
"""Transform a username:password value into a base64 string."""
try:
username, password = value.split(":", 1)
except ValueError:
raise click.BadParameter(
"Authorization header needs to be Authorization=username:password",
... |
def validate_api_headers(param, value):
"""Validate that API headers is a CSV of k=v pairs."""
# pylint: disable=unused-argument
if not value:
return None
headers = {}
for kv in value.split(","):
try:
k, v = kv.split("=", 1)
k = k.strip()
for bad... |
def validate_slashes(param, value, minimum=2, maximum=None, form=None):
"""Ensure that parameter has slashes and minimum parts."""
try:
value = value.split("/")
except ValueError:
value = None
if value:
if len(value) < minimum:
value = None
elif maximum and l... |
def validate_owner_repo(ctx, param, value):
"""Ensure that owner/repo is formatted correctly."""
# pylint: disable=unused-argument
form = "OWNER/REPO"
return validate_slashes(param, value, minimum=2, maximum=2, form=form) |
def validate_owner_repo_package(ctx, param, value):
"""Ensure that owner/repo/package is formatted correctly."""
# pylint: disable=unused-argument
form = "OWNER/REPO/PACKAGE"
return validate_slashes(param, value, minimum=3, maximum=3, form=form) |
def validate_owner_repo_distro(ctx, param, value):
"""Ensure that owner/repo/distro/version is formatted correctly."""
# pylint: disable=unused-argument
form = "OWNER/REPO/DISTRO[/RELEASE]"
return validate_slashes(param, value, minimum=3, maximum=4, form=form) |
def validate_page(ctx, param, value):
"""Ensure that a valid value for page is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter(
"Page is not zero-based, please set a value to 1 or higher.", param=param
)
return value |
def validate_page_size(ctx, param, value):
"""Ensure that a valid value for page size is chosen."""
# pylint: disable=unused-argument
if value == 0:
raise click.BadParameter("Page size must be non-zero or unset.", param=param)
return value |
def getbalance(self, **params):
"""Get Account Asset Balance
API Type
--------
HTTP Private API
Docs
----
https://lightning.bitflyer.jp/docs?lang=en#get-account-asset-balance
"""
if not all([self.api_key, self.api_secret]):
raise Auth... |
def tidy_all_the_variables(host, inventory_mgr):
''' removes all overridden and inherited variables from hosts
and groups '''
global _vars
_vars = dict()
_vars[host] = inventory_mgr.inventory.get_host_vars(host)
for group in host.get_groups():
remove_inherited_and_overridden_vars(_va... |
def _plugins_inventory(self, entities):
import os
from ansible.plugins.loader import vars_loader
from ansible.utils.vars import combine_vars
''' merges all entities by inventory source '''
data = {}
for inventory_dir in self.variable_manager._inventory._sources:
... |
def handle(self, *args, **options):
"""gets data from WordPress site"""
# TODO: refactor these with .get
if 'username' in options:
self.username = options['username']
else:
self.username = None
if 'password' in options:
self.password = options[... |
def create_images_from_urls_in_content(self, body):
"""create Image objects and transfer image files to media root"""
soup = BeautifulSoup(body, "html5lib")
for img in soup.findAll('img'):
old_url = img['src']
if 'width' in img:
width = img['width']
... |
def lookup_comment_by_wordpress_id(self, comment_id, comments):
""" Returns Django comment object with this wordpress id """
for comment in comments:
if comment.wordpress_id == comment_id:
return comment |
def create_blog_pages(self, posts, blog_index, *args, **options):
"""create Blog post entries from wordpress data"""
for post in posts:
post_id = post.get('ID')
title = post.get('title')
if title:
new_title = self.convert_html_entities(title)
... |
def unique_slugify(instance, value, slug_field_name='slug', queryset=None,
slug_separator='-'):
"""
Calculates and stores a unique slug of ``value`` for an instance.
``slug_field_name`` should be a string matching the name of the field to
store the slug in (and the field to check aga... |
def _slug_strip(value, separator='-'):
"""
Cleans up a slug by removing slug separator characters that occur at the
beginning or end of a slug.
If an alternate separator is used, it will also replace any instances of
the default '-' separator with the new separator.
"""
separator = separato... |
def limit_author_choices():
""" Limit choices in blog author field based on config settings """
LIMIT_AUTHOR_CHOICES = getattr(settings, 'BLOG_LIMIT_AUTHOR_CHOICES_GROUP', None)
if LIMIT_AUTHOR_CHOICES:
if isinstance(LIMIT_AUTHOR_CHOICES, str):
limit = Q(groups__name=LIMIT_AUTHOR_CHOICES... |
def get_blog_context(context):
""" Get context data useful on all blog related pages """
context['authors'] = get_user_model().objects.filter(
owned_pages__live=True,
owned_pages__content_type__model='blogpage'
).annotate(Count('owned_pages')).order_by('-owned_pages__count')
context['all... |
def remove_xmlns(xml_string):
"""
changes the xmlns (XML namespace) so that values are
replaced with the string representation of their key
this makes the import process for portable
>>> xp = XML_parser
>>> test_xmlns = r'<rss version="2.0" xmlns:excerpt="http://wordpres... |
def item_dict(self, item):
"""
create a default dict of values, including
category and tag lookup
"""
# mocking wierd JSON structure
ret_dict = {"terms":{"category":[],"post_tag":[]}}
for e in item:
# is it a category or tag??
if "category"... |
def convert_date(d, custom_date_string=None, fallback=None):
"""
for whatever reason, sometimes WP XML has unintelligible
datetime strings for pubDate.
In this case default to custom_date_string or today
Use fallback in case a secondary date string is available.
Incident... |
def translate_item(self, item_dict):
"""cleanup item keys to match API json format"""
if not item_dict.get('title'):
return None
# Skip attachments
if item_dict.get('{wp}post_type', None) == 'attachment':
return None
ret_dict = {}
# slugify post ti... |
def translate_wp_comment(self, e):
"""
<wp:comment>
<wp:comment_id>1234</wp:comment_id>
<wp:comment_author><![CDATA[John Doe]]></wp:comment_author>
<wp:comment_author_email><![CDATA[info@adsasd.com]]></wp:comment_author_email>
<wp:comment_author_url>http://myhomepage.com/</wp:c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.