repository_name
stringclasses
316 values
func_path_in_repository
stringlengths
6
223
func_name
stringlengths
1
134
language
stringclasses
1 value
func_code_string
stringlengths
57
65.5k
func_documentation_string
stringlengths
1
46.3k
split_name
stringclasses
1 value
func_code_url
stringlengths
91
315
called_functions
listlengths
1
156
enclosing_scope
stringlengths
2
1.48M
thiezn/iperf3-python
iperf3/iperf3.py
IPerf3.iperf_version
python
def iperf_version(self): # TODO: Is there a better way to get the const char than allocating 30? VersionType = c_char * 30 return VersionType.in_dll(self.lib, "version").value.decode('utf-8')
Returns the version of the libiperf library :rtype: string
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L369-L376
null
class IPerf3(object): """The base class used by both the iperf3 :class:`Server` and :class:`Client` .. note:: You should not use this class directly """ def __init__(self, role, verbose=True, lib_name=None): """Initialise the iperf shared libra...
thiezn/iperf3-python
iperf3/iperf3.py
IPerf3._error_to_string
python
def _error_to_string(self, error_id): strerror = self.lib.iperf_strerror strerror.restype = c_char_p return strerror(error_id).decode('utf-8')
Returns an error string from libiperf :param error_id: The error_id produced by libiperf :rtype: string
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L378-L386
null
class IPerf3(object): """The base class used by both the iperf3 :class:`Server` and :class:`Client` .. note:: You should not use this class directly """ def __init__(self, role, verbose=True, lib_name=None): """Initialise the iperf shared libra...
thiezn/iperf3-python
iperf3/iperf3.py
Client.server_hostname
python
def server_hostname(self): result = c_char_p( self.lib.iperf_get_test_server_hostname(self._test) ).value if result: self._server_hostname = result.decode('utf-8') else: self._server_hostname = None return self._server_hostname
The server hostname to connect to. Accepts DNS entries or IP addresses. :rtype: string
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L432-L446
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.protocol
python
def protocol(self): proto_id = self.lib.iperf_get_test_protocol_id(self._test) if proto_id == SOCK_STREAM: self._protocol = 'tcp' elif proto_id == SOCK_DGRAM: self._protocol = 'udp' return self._protocol
The iperf3 instance protocol valid protocols are 'tcp' and 'udp' :rtype: str
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L457-L471
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.omit
python
def omit(self): self._omit = self.lib.iperf_get_test_omit(self._test) return self._omit
The test startup duration to omit in seconds.
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L486-L489
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.duration
python
def duration(self): self._duration = self.lib.iperf_get_test_duration(self._test) return self._duration
The test duration in seconds.
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L497-L500
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.bandwidth
python
def bandwidth(self): self._bandwidth = self.lib.iperf_get_test_rate(self._test) return self._bandwidth
Target bandwidth in bits/sec
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L508-L511
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.blksize
python
def blksize(self): self._blksize = self.lib.iperf_get_test_blksize(self._test) return self._blksize
The test blksize.
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L519-L522
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.num_streams
python
def num_streams(self): self._num_streams = self.lib.iperf_get_test_num_streams(self._test) return self._num_streams
The number of streams to use.
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L552-L555
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.reverse
python
def reverse(self): enabled = self.lib.iperf_get_test_reverse(self._test) if enabled: self._reverse = True else: self._reverse = False return self._reverse
Toggles direction of test :rtype: bool
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L586-L598
null
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Client.run
python
def run(self): if self.json_output: output_to_pipe(self._pipe_in) # Disable stdout error = self.lib.iperf_run_client(self._test) if not self.iperf_version.startswith('iperf 3.1'): data = read_pipe(self._pipe_out) if data.startswith('Control c...
Run the current test client. :rtype: instance of :class:`TestResult`
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L609-L634
[ "def read_pipe(pipe_out):\n \"\"\"Read data on a pipe\n\n Used to capture stdout data produced by libiperf\n\n :param pipe_out: The os pipe_out\n :rtype: unicode string\n \"\"\"\n out = b''\n while more_data(pipe_out):\n out += os.read(pipe_out, 1024)\n\n return out.decode('utf-8')\n"...
class Client(IPerf3): """An iperf3 client connection. This opens up a connection to a running iperf3 server Basic Usage:: >>> import iperf3 >>> client = iperf3.Client() >>> client.duration = 1 >>> client.server_hostname = '127.0.0.1' >>> client.port = 5201 >>> client....
thiezn/iperf3-python
iperf3/iperf3.py
Server.run
python
def run(self): def _run_in_thread(self, data_queue): """Runs the iperf_run_server :param data_queue: thread-safe queue """ output_to_pipe(self._pipe_in) # disable stdout error = self.lib.iperf_run_server(self._test) output_to_screen(self...
Run the iperf3 server instance. :rtype: instance of :class:`TestResult`
train
https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L660-L707
null
class Server(IPerf3): """An iperf3 server connection. This starts an iperf3 server session. The server terminates after each succesful client connection so it might be useful to run Server.run() in a loop. The C function iperf_run_server is called in a seperate thread to make sure KeyboardInte...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
get_or_create_placeholder
python
def get_or_create_placeholder(page, placeholder_slot, delete_existing=False): placeholder, created = page.placeholders.get_or_create( slot=placeholder_slot) if created: log.debug("Create placeholder %r for page %r", placeholder_slot, page.get_title()) else: log.debu...
Get or create a placeholder on the given page. Optional: Delete existing placeholder.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L24-L44
null
import logging import pytest from django.utils import translation from cms.api import add_plugin, create_page, create_title from cms.constants import TEMPLATE_INHERITANCE_MAGIC from cms.models import CMSPlugin, Page, Title, settings from cms.utils import apphook_reload # https://github.com/jedie/django-tools from d...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
publish_page
python
def publish_page(page, languages): for language_code, lang_name in iter_languages(languages): url = page.get_absolute_url() if page.publisher_is_draft: page.publish(language_code) log.info('page "%s" published in %s: %s', page, lang_name, url) else: log.i...
Publish a CMS page in all given languages.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L47-L60
null
import logging import pytest from django.utils import translation from cms.api import add_plugin, create_page, create_title from cms.constants import TEMPLATE_INHERITANCE_MAGIC from cms.models import CMSPlugin, Page, Title, settings from cms.utils import apphook_reload # https://github.com/jedie/django-tools from d...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
create_cms_index_pages
python
def create_cms_index_pages(placeholder_slot="content"): try: index_page = Page.objects.get(is_home=True, publisher_is_draft=False) except Page.DoesNotExist: log.debug('Create index page in "en" and...') index_page = create_page( title="index in English", template...
create cms home page and fill >content< placeholder with TextPlugin
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L372-L406
null
import logging import pytest from django.utils import translation from cms.api import add_plugin, create_page, create_title from cms.constants import TEMPLATE_INHERITANCE_MAGIC from cms.models import CMSPlugin, Page, Title, settings from cms.utils import apphook_reload # https://github.com/jedie/django-tools from d...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
create_cms_plugin_page
python
def create_cms_plugin_page(apphook, apphook_namespace, placeholder_slot=None): creator = CmsPluginPageCreator( apphook=apphook, apphook_namespace=apphook_namespace, ) creator.placeholder_slot = placeholder_slot plugin_page = creator.create() return plugin_page
Create cms plugin page in all existing languages. Add a link to the index page. :param apphook: e.g...........: 'FooBarApp' :param apphook_namespace: e.g.: 'foobar' :return:
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L458-L473
[ "def create(self):\n \"\"\"\n Create the plugin page in all languages and fill dummy content.\n \"\"\"\n plugin = CMSPlugin.objects.filter(plugin_type=self.apphook)\n if plugin.exists():\n log.debug('Plugin page for \"%s\" plugin already exist, ok.',\n self.apphook)\n r...
import logging import pytest from django.utils import translation from cms.api import add_plugin, create_page, create_title from cms.constants import TEMPLATE_INHERITANCE_MAGIC from cms.models import CMSPlugin, Page, Title, settings from cms.utils import apphook_reload # https://github.com/jedie/django-tools from d...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.get_slug
python
def get_slug(self, language_code, lang_name): title = self.get_title(language_code, lang_name) assert title != "" title = str(title) # e.g.: evaluate a lazy translation slug = slugify(title) assert slug != "", "Title %r results in empty slug!" % title return slug
Notes: - slug must be unique! - slug is used to check if page already exists! :return: 'slug' string for cms.api.create_page()
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L107-L121
[ "def get_title(self, language_code, lang_name):\n \"\"\"\n :return: 'title' string for cms.api.create_page()\n \"\"\"\n return \"%s in %s\" % (self.__class__.__name__, language_code)\n" ]
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.get_home_page
python
def get_home_page(self): try: home_page_draft = Page.objects.get( is_home=True, publisher_is_draft=True) except Page.DoesNotExist: log.error('ERROR: "home page" doesn\'t exists!') raise RuntimeError('no home page') return home_page_draft
Return the published home page. Used for 'parent' in cms.api.create_page()
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L129-L140
null
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.publish
python
def publish(self, page): assert page.publisher_is_draft == True, "Page '%s' must be a draft!" % page publish_page(page, languages=self.languages)
Publish the page in all languages.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L148-L153
[ "def publish_page(page, languages):\n \"\"\"\n Publish a CMS page in all given languages.\n \"\"\"\n for language_code, lang_name in iter_languages(languages):\n url = page.get_absolute_url()\n\n if page.publisher_is_draft:\n page.publish(language_code)\n log.info('pa...
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.create_page
python
def create_page(self, **extra_kwargs): with translation.override(self.default_language_code): # for evaluate the language name lazy translation # e.g.: settings.LANGUAGE_CODE is not "en" self.default_lang_name = dict( self.languages)[self.default_language_cod...
Create page (and page title) in default language extra_kwargs will be pass to cms.api.create_page() e.g.: extra_kwargs={ "soft_root": True, "reverse_id": my_reverse_id, }
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L155-L250
[ "def get_title(self, language_code, lang_name):\n \"\"\"\n :return: 'title' string for cms.api.create_page()\n \"\"\"\n return \"%s in %s\" % (self.__class__.__name__, language_code)\n", "def get_menu_title(self, language_code, lang_name):\n \"\"\"\n :return: 'menu_title' string for cms.api.crea...
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.create_title
python
def create_title(self, page): for language_code, lang_name in iter_languages(self.languages): try: title = Title.objects.get(page=page, language=language_code) except Title.DoesNotExist: slug = self.get_slug(language_code, lang_name) assert...
Create page title in all other languages with cms.api.create_title()
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L252-L270
[ "def get_title(self, language_code, lang_name):\n \"\"\"\n :return: 'title' string for cms.api.create_page()\n \"\"\"\n return \"%s in %s\" % (self.__class__.__name__, language_code)\n", "def get_slug(self, language_code, lang_name):\n \"\"\"\n Notes:\n - slug must be unique!\n - s...
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.get_add_plugin_kwargs
python
def get_add_plugin_kwargs(self, page, no, placeholder, language_code, lang_name): return { "plugin_type": 'TextPlugin', # djangocms_text_ckeditor "body": self.get_dummy_text(page, no, placeholder, language_code, ...
Return "content" for create the plugin. Called from self.add_plugins()
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L289-L301
[ "def get_dummy_text(self, page, no, placeholder, language_code, lang_name):\n if no == 1:\n source = self.prefix_dummy_part\n elif no == self.dummy_text_count:\n source = self.suffix_dummy_part\n else:\n source = self.dummy_text_part\n\n dummy_text = source.format(\n absolute...
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.add_plugins
python
def add_plugins(self, page, placeholder): for language_code, lang_name in iter_languages(self.languages): for no in range(1, self.dummy_text_count + 1): add_plugin_kwargs = self.get_add_plugin_kwargs( page, no, placeholder, language_code, lang_name) ...
Add a "TextPlugin" in all languages.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L303-L320
[ "def get_add_plugin_kwargs(self, page, no, placeholder, language_code,\n lang_name):\n \"\"\"\n Return \"content\" for create the plugin.\n Called from self.add_plugins()\n \"\"\"\n return {\n \"plugin_type\":\n 'TextPlugin', # djangocms_text_ckeditor\n ...
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.get_or_create_placeholder
python
def get_or_create_placeholder(self, page, placeholder_slot): placeholder, created = get_or_create_placeholder( page, placeholder_slot, delete_existing=self.delete_first) return placeholder, created
Add a placeholder if not exists.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L322-L328
[ "def get_or_create_placeholder(page, placeholder_slot, delete_existing=False):\n \"\"\"\n Get or create a placeholder on the given page.\n Optional: Delete existing placeholder.\n \"\"\"\n placeholder, created = page.placeholders.get_or_create(\n slot=placeholder_slot)\n if created:\n ...
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPageCreator.fill_content
python
def fill_content(self, page, placeholder_slot): if len(placeholder_slot) == 1: raise RuntimeError(placeholder_slot) placeholder, created = self.get_or_create_placeholder( page, placeholder_slot) self.add_plugins(page, placeholder)
Add a placeholder to the page. Here we add a "TextPlugin" in all languages.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L330-L339
[ "def add_plugins(self, page, placeholder):\n \"\"\"\n Add a \"TextPlugin\" in all languages.\n \"\"\"\n for language_code, lang_name in iter_languages(self.languages):\n for no in range(1, self.dummy_text_count + 1):\n add_plugin_kwargs = self.get_add_plugin_kwargs(\n pa...
class CmsPageCreator(object): """ Create a normal Django CMS page """ # Some defaults: languages = settings.LANGUAGES # Languages for created content. default_language_code = settings.LANGUAGE_CODE # First language to start create the page template = TEMPLATE_INHERITANCE_MAGIC in_navig...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
CmsPluginPageCreator.create
python
def create(self): plugin = CMSPlugin.objects.filter(plugin_type=self.apphook) if plugin.exists(): log.debug('Plugin page for "%s" plugin already exist, ok.', self.apphook) raise plugin page, created = super(CmsPluginPageCreator, self).create() ...
Create the plugin page in all languages and fill dummy content.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L437-L455
[ "def fill_content(self, page, placeholder_slot):\n \"\"\"\n Add a placeholder to the page.\n Here we add a \"TextPlugin\" in all languages.\n \"\"\"\n if len(placeholder_slot) == 1:\n raise RuntimeError(placeholder_slot)\n placeholder, created = self.get_or_create_placeholder(\n page...
class CmsPluginPageCreator(CmsPageCreator): """ Create a Django CMS plugin page and fill the content. Useable for default production fixtures or unittests fixtures. The idea is to inherit from this class and update it for your need by overwrite some methods ;) """ placeholder_slots = () # ...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
DummyPageGenerator.get_title
python
def get_title(self, language_code, lang_name): title = "%s %i-%i in %s" % (self.title_prefix, self.current_count, self.current_level, language_code) log.info(title) return title
:return: 'title' string for cms.api.create_page()
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L494-L501
null
class DummyPageGenerator(CmsPageCreator): def __init__(self, delete_first=False, title_prefix=None, levels=3, count=2): if title_prefix is None: self.title_prefix = self.__class__.__name__ else: self.title_pr...
jedie/django-cms-tools
django_cms_tools/fixture_helper/pages.py
DummyPageGenerator.get_parent_page
python
def get_parent_page(self): if self.current_level == 1: # 'root' page return None else: return self.page_data[(self.current_level - 1, self.current_count)]
For 'parent' in cms.api.create_page()
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/pages.py#L503-L511
null
class DummyPageGenerator(CmsPageCreator): def __init__(self, delete_first=False, title_prefix=None, levels=3, count=2): if title_prefix is None: self.title_prefix = self.__class__.__name__ else: self.title_pr...
jedie/django-cms-tools
django_cms_tools/fixture_helper/page_utils.py
get_public_cms_app_namespaces
python
def get_public_cms_app_namespaces(): qs = Page.objects.public() qs = qs.exclude(application_namespace=None) qs = qs.order_by('application_namespace') try: application_namespaces = list( qs.distinct('application_namespace').values_list( 'application_namespace', flat=T...
:return: a tuple() with all cms app namespaces
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/page_utils.py#L10-L30
null
""" :created: 17.09.2018 by Jens Diemer :copyleft: 2018 by the django-cms-tools team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. """ from cms.models import Page def get_public_cms_page_urls(*, language_code): """ :param language_code: e.g.: "en" or...
jedie/django-cms-tools
django_cms_tools/fixture_helper/page_utils.py
get_public_cms_page_urls
python
def get_public_cms_page_urls(*, language_code): pages = Page.objects.public() urls = [page.get_absolute_url(language=language_code) for page in pages] urls.sort() return tuple(urls)
:param language_code: e.g.: "en" or "de" :return: Tuple with all public urls in the given language
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/fixture_helper/page_utils.py#L33-L41
null
""" :created: 17.09.2018 by Jens Diemer :copyleft: 2018 by the django-cms-tools team, see AUTHORS for more details. :license: GNU GPL v3 or above, see LICENSE for more details. """ from cms.models import Page def get_public_cms_app_namespaces(): """ :return: a tuple() with all cms app namespaces ...
jedie/django-cms-tools
django_cms_tools/plugin_landing_page/views.py
LandingPageDetailView.set_meta
python
def set_meta(self, instance): self.use_title_tag = True self.title = instance.title
Set django-meta stuff from LandingPageModel instance.
train
https://github.com/jedie/django-cms-tools/blob/0a70dbbb6f770f5a73c8ecd174d5559a37262792/django_cms_tools/plugin_landing_page/views.py#L36-L41
null
class LandingPageDetailView(MetadataMixin, TranslatableSlugMixin, PublisherCmsDetailView): model = LandingPageModel # key and name of the "item" toolbar toolbar_key = LANDING_PAGE_TOOLBAR_NAME toolbar_verbose_name = LANDING_PAGE_TOOLBAR_VERBOSE_NAME def get(self, request, *args, **kwargs): ...
grabbles/grabbit
grabbit/core.py
merge_layouts
python
def merge_layouts(layouts): ''' Utility function for merging multiple layouts. Args: layouts (list): A list of BIDSLayout instances to merge. Returns: A BIDSLayout containing merged files and entities. Notes: Layouts will be merged in the order of the elements in the list. I.e.,...
Utility function for merging multiple layouts. Args: layouts (list): A list of BIDSLayout instances to merge. Returns: A BIDSLayout containing merged files and entities. Notes: Layouts will be merged in the order of the elements in the list. I.e., the first Layout will be up...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L1079-L1105
null
import json import os import re from collections import defaultdict, OrderedDict, namedtuple from grabbit.external import six, inflect from grabbit.utils import natural_sort, listify from grabbit.extensions.writable import build_path, write_contents_to_file from os.path import (join, basename, dirname, abspath, split, ...
grabbles/grabbit
grabbit/core.py
File._matches
python
def _matches(self, entities=None, extensions=None, domains=None, regex_search=False): if extensions is not None: if isinstance(extensions, six.string_types): extensions = [extensions] extensions = '(' + '|'.join(extensions) + ')$' if re.search...
Checks whether the file matches all of the passed entities and extensions. Args: entities (dict): A dictionary of entity names -> regex patterns. extensions (str, list): One or more file extensions to allow. domains (str, list): One or more domains the file must matc...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L35-L88
null
class File(object): def __init__(self, filename, domains=None): """ Represents a single file. """ self.path = filename self.filename = basename(self.path) self.dirname = dirname(self.path) self.tags = {} self.domains = domains or [] @property ...
grabbles/grabbit
grabbit/core.py
File.as_named_tuple
python
def as_named_tuple(self): keys = list(self.entities.keys()) replaced = [] for i, k in enumerate(keys): if iskeyword(k): replaced.append(k) keys[i] = '%s_' % k if replaced: safe = ['%s_' % k for k in replaced] warnings.wa...
Returns the File as a named tuple. The full path plus all entity key/value pairs are returned as attributes.
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L90-L108
null
class File(object): def __init__(self, filename, domains=None): """ Represents a single file. """ self.path = filename self.filename = basename(self.path) self.dirname = dirname(self.path) self.tags = {} self.domains = domains or [] @property ...
grabbles/grabbit
grabbit/core.py
File.copy
python
def copy(self, path_patterns, symbolic_link=False, root=None, conflicts='fail'): ''' Copy the contents of a file to a new location, with target filename defined by the current File's entities and the specified path_patterns. ''' new_filename = build_path(self.entities, path_...
Copy the contents of a file to a new location, with target filename defined by the current File's entities and the specified path_patterns.
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L110-L141
[ "def build_path(entities, path_patterns, strict=False):\n \"\"\"\n Constructs a path given a set of entities and a list of potential\n filename patterns to use.\n\n Args:\n entities (dict): A dictionary mapping entity names to entity values.\n path_patterns (str, list): One or more filenam...
class File(object): def __init__(self, filename, domains=None): """ Represents a single file. """ self.path = filename self.filename = basename(self.path) self.dirname = dirname(self.path) self.tags = {} self.domains = domains or [] @property ...
grabbles/grabbit
grabbit/core.py
Entity.match_file
python
def match_file(self, f, update_file=False): if self.map_func is not None: val = self.map_func(f) else: m = self.regex.search(f.path) val = m.group(1) if m is not None else None return self._astype(val)
Determine whether the passed file matches the Entity. Args: f (File): The File instance to match against. Returns: the matched value if a match was found, otherwise None.
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L261-L276
[ "def _astype(self, val):\n if val is not None and self.dtype is not None:\n val = self.dtype(val)\n return val\n" ]
class Entity(object): def __init__(self, name, pattern=None, domain=None, mandatory=False, directory=None, map_func=None, dtype=None, aliases=None, **kwargs): """ Represents a single entity defined in the JSON config. Args: name (str): The name...
grabbles/grabbit
grabbit/core.py
Layout._get_or_load_domain
python
def _get_or_load_domain(self, domain): ''' Return a domain if one already exists, or create a new one if not. Args: domain (str, dict): Can be one of: - The name of the Domain to return (fails if none exists) - A path to the Domain configuration file ...
Return a domain if one already exists, or create a new one if not. Args: domain (str, dict): Can be one of: - The name of the Domain to return (fails if none exists) - A path to the Domain configuration file - A dictionary containing configuration inf...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L423-L457
null
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout._check_inclusions
python
def _check_inclusions(self, f, domains=None): ''' Check file or directory against regexes in config to determine if it should be included in the index ''' filename = f if isinstance(f, six.string_types) else f.path if domains is None: domains = list(self.domains.values(...
Check file or directory against regexes in config to determine if it should be included in the index
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L470-L495
null
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout._find_entity
python
def _find_entity(self, entity): ''' Find an Entity instance by name. Checks both name and id fields.''' if entity in self.entities: return self.entities[entity] _ent = [e for e in self.entities.values() if e.name == entity] if len(_ent) > 1: raise ValueError("Enti...
Find an Entity instance by name. Checks both name and id fields.
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L557-L570
null
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.save_index
python
def save_index(self, filename): ''' Save the current Layout's index to a .json file. Args: filename (str): Filename to write to. Note: At the moment, this won't serialize directory-specific config files. This means reconstructed indexes will only work properly in ca...
Save the current Layout's index to a .json file. Args: filename (str): Filename to write to. Note: At the moment, this won't serialize directory-specific config files. This means reconstructed indexes will only work properly in cases where there aren't multiple layout specs...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L613-L628
null
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.load_index
python
def load_index(self, filename, reindex=False): ''' Load the Layout's index from a plaintext file. Args: filename (str): Path to the plaintext index file. reindex (bool): If True, discards entity values provided in the loaded index and instead re-indexes every fil...
Load the Layout's index from a plaintext file. Args: filename (str): Path to the plaintext index file. reindex (bool): If True, discards entity values provided in the loaded index and instead re-indexes every file in the loaded index against the entities ...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L630-L664
[ "def _make_file_object(self, root, f):\n ''' Initialize a new File oject from a directory and filename. Extend\n in subclasses as needed. '''\n return File(join(root, f))\n", "def _reset_index(self):\n # Reset indexes\n self.files = {}\n for ent in self.entities.values():\n ent.files = {}...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.add_entity
python
def add_entity(self, domain, **kwargs): ''' Add a new Entity to tracking. ''' # Set the entity's mapping func if one was specified map_func = kwargs.get('map_func', None) if map_func is not None and not callable(kwargs['map_func']): if self.entity_mapper is None: ...
Add a new Entity to tracking.
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L666-L697
[ "def plural(self, text, count=None):\n \"\"\"\n Return the plural of text.\n\n If count supplied, then return text if count is one of:\n 1, a, an, one, each, every, this, that\n otherwise return the plural.\n\n Whitespace at the start and end is preserved.\n\n \"\"\"\n pre, word, post = ...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.get
python
def get(self, return_type='tuple', target=None, extensions=None, domains=None, regex_search=None, **kwargs): if regex_search is None: regex_search = self.regex_search result = [] filters = {} filters.update(kwargs) for filename, file in self.files.items...
Retrieve files and/or metadata from the current Layout. Args: return_type (str): Type of result to return. Valid values: 'tuple': returns a list of namedtuples containing file name as well as attribute/value pairs for all named entities. 'file': r...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L699-L791
[ "def natural_sort(l, field=None):\n '''\n based on snippet found at http://stackoverflow.com/a/4836734/2445984\n '''\n convert = lambda text: int(text) if text.isdigit() else text.lower()\n\n def alphanum_key(key):\n if field is not None:\n key = getattr(key, field)\n if not ...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.count
python
def count(self, entity, files=False): return self._find_entity(entity).count(files)
Return the count of unique values or files for the named entity. Args: entity (str): The name of the entity. files (bool): If True, counts the number of filenames that contain at least one value of the entity, rather than the number of unique values of th...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L802-L812
[ "def _find_entity(self, entity):\n ''' Find an Entity instance by name. Checks both name and id fields.'''\n if entity in self.entities:\n return self.entities[entity]\n _ent = [e for e in self.entities.values() if e.name == entity]\n if len(_ent) > 1:\n raise ValueError(\"Entity name '%s'...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.as_data_frame
python
def as_data_frame(self, **kwargs): try: import pandas as pd except ImportError: raise ImportError("What are you doing trying to export a Layout " "as a pandas DataFrame when you don't have " "pandas installed? Eh? Eh?") ...
Return information for all Files tracked in the Layout as a pandas DataFrame. Args: kwargs: Optional keyword arguments passed on to get(). This allows one to easily select only a subset of files for export. Returns: A pandas DataFrame, where each row is a...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L814-L839
[ "def get(self, return_type='tuple', target=None, extensions=None,\n domains=None, regex_search=None, **kwargs):\n \"\"\"\n Retrieve files and/or metadata from the current Layout.\n\n Args:\n return_type (str): Type of result to return. Valid values:\n 'tuple': returns a list of nam...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.get_nearest
python
def get_nearest(self, path, return_type='file', strict=True, all_=False, ignore_strict_entities=None, full_search=False, **kwargs): ''' Walk up the file tree from the specified path and return the nearest matching file(s). Args: path (str): The file to search fro...
Walk up the file tree from the specified path and return the nearest matching file(s). Args: path (str): The file to search from. return_type (str): What to return; must be one of 'file' (default) or 'tuple'. strict (bool): When True, all entities pre...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L845-L929
[ "def get(self, return_type='tuple', target=None, extensions=None,\n domains=None, regex_search=None, **kwargs):\n \"\"\"\n Retrieve files and/or metadata from the current Layout.\n\n Args:\n return_type (str): Type of result to return. Valid values:\n 'tuple': returns a list of nam...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.build_path
python
def build_path(self, source, path_patterns=None, strict=False, domains=None): ''' Constructs a target filename for a file or dictionary of entities. Args: source (str, File, dict): The source data to use to construct the new file path. Must be one of: ...
Constructs a target filename for a file or dictionary of entities. Args: source (str, File, dict): The source data to use to construct the new file path. Must be one of: - A File object - A string giving the path of a File contained within the ...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L948-L989
[ "def build_path(entities, path_patterns, strict=False):\n \"\"\"\n Constructs a path given a set of entities and a list of potential\n filename patterns to use.\n\n Args:\n entities (dict): A dictionary mapping entity names to entity values.\n path_patterns (str, list): One or more filenam...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/core.py
Layout.write_contents_to_file
python
def write_contents_to_file(self, entities, path_patterns=None, contents=None, link_to=None, content_mode='text', conflicts='fail', strict=False, domains=None, index=False, index_domains=None): ...
Write arbitrary data to a file defined by the passed entities and path patterns. Args: entities (dict): A dictionary of entities, with Entity names in keys and values for the desired file in values. path_patterns (list): Optional path patterns to use when buildin...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/core.py#L1024-L1076
[ "def write_contents_to_file(path, contents=None, link_to=None,\n content_mode='text', root=None, conflicts='fail'):\n \"\"\"\n Uses provided filename patterns to write contents to a new path, given\n a corresponding entity map.\n\n Args:\n path (str): Destination path of...
class Layout(object): def __init__(self, paths, root=None, index=None, dynamic_getters=False, absolute_paths=True, regex_search=False, entity_mapper=None, path_patterns=None, config_filename='layout.json', include=None, exclude=None): """ A contain...
grabbles/grabbit
grabbit/utils.py
listify
python
def listify(obj, ignore=(list, tuple, type(None))): ''' Wraps all non-list or tuple objects in a list; provides a simple way to accept flexible arguments. ''' return obj if isinstance(obj, ignore) else [obj]
Wraps all non-list or tuple objects in a list; provides a simple way to accept flexible arguments.
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/utils.py#L34-L37
null
import os import re from os.path import join, dirname, basename def natural_sort(l, field=None): ''' based on snippet found at http://stackoverflow.com/a/4836734/2445984 ''' convert = lambda text: int(text) if text.isdigit() else text.lower() def alphanum_key(key): if field is not None: ...
grabbles/grabbit
grabbit/extensions/writable.py
build_path
python
def build_path(entities, path_patterns, strict=False): if isinstance(path_patterns, string_types): path_patterns = [path_patterns] # Loop over available patherns, return first one that matches all for pattern in path_patterns: # If strict, all entities must be contained in the pattern ...
Constructs a path given a set of entities and a list of potential filename patterns to use. Args: entities (dict): A dictionary mapping entity names to entity values. path_patterns (str, list): One or more filename patterns to write the file to. Entities should be represented by the...
train
https://github.com/grabbles/grabbit/blob/83ff93df36019eaaee9d4e31f816a518e46cae07/grabbit/extensions/writable.py#L55-L104
[ "def replace_entities(entities, pattern):\n \"\"\"\n Replaces all entity names in a given pattern with the corresponding\n values provided by entities.\n\n Args:\n entities (dict): A dictionary mapping entity names to entity values.\n pattern (str): A path pattern that contains entity name...
import logging import os import re import sys from grabbit.utils import splitext from os.path import join, dirname, exists, islink, isabs, isdir from six import string_types __all__ = ['replace_entities', 'build_path', 'write_contents_to_file'] def replace_entities(entities, pattern): """ Replaces all entity...
alpha-xone/xone
xone/utils.py
trade_day
python
def trade_day(dt, cal='US'): from xone import calendar dt = pd.Timestamp(dt).date() return calendar.trading_dates(start=dt - pd.Timedelta('10D'), end=dt, calendar=cal)[-1]
Latest trading day w.r.t given dt Args: dt: date of reference cal: trading calendar Returns: pd.Timestamp: last trading day Examples: >>> trade_day('2018-12-25').strftime('%Y-%m-%d') '2018-12-24'
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L52-L70
[ "def trading_dates(start, end, calendar='US'):\n \"\"\"\n Trading dates for given exchange\n\n Args:\n start: start date\n end: end date\n calendar: exchange as string\n\n Returns:\n pd.DatetimeIndex: datetime index\n\n Examples:\n >>> bus_dates = ['2018-12-24', '20...
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/utils.py
cur_time
python
def cur_time(typ='date', tz=DEFAULT_TZ, trading=True, cal='US'): dt = pd.Timestamp('now', tz=tz) if typ == 'date': if trading: return trade_day(dt=dt, cal=cal).strftime('%Y-%m-%d') else: return dt.strftime('%Y-%m-%d') if typ == 'time': return dt.strftime('%Y-%m-%d %H:%M:%S') if typ == ...
Current time Args: typ: one of ['date', 'time', 'time_path', 'raw', ''] tz: timezone trading: check if current date is trading day cal: trading calendar Returns: relevant current time or date Examples: >>> cur_dt = pd.Timestamp('now') >>> cur_time(t...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L73-L111
[ "def trade_day(dt, cal='US'):\n \"\"\"\n Latest trading day w.r.t given dt\n\n Args:\n dt: date of reference\n cal: trading calendar\n\n Returns:\n pd.Timestamp: last trading day\n\n Examples:\n >>> trade_day('2018-12-25').strftime('%Y-%m-%d')\n '2018-12-24'\n \"...
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/utils.py
align_data
python
def align_data(*args): res = pd.DataFrame(pd.concat([ d.loc[~d.index.duplicated(keep='first')].rename( columns=lambda vv: '%s_%d' % (vv, i + 1) ) for i, d in enumerate(args) ], axis=1)) data_cols = [col for col in res.columns if col[-2:] == '_1'] other_cols = [col for col in ...
Resample and aligh data for defined frequency Args: *args: DataFrame of data to be aligned Returns: pd.DataFrame: aligned data with renamed columns Examples: >>> start = '2018-09-10T10:10:00' >>> tz = 'Australia/Sydney' >>> idx = pd.date_range(start=start, periods=...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L114-L167
null
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/utils.py
cat_data
python
def cat_data(data_kw): if len(data_kw) == 0: return pd.DataFrame() return pd.DataFrame(pd.concat([ data.assign(ticker=ticker).set_index('ticker', append=True) .unstack('ticker').swaplevel(0, 1, axis=1) for ticker, data in data_kw.items() ], axis=1))
Concatenate data with ticker as sub column index Args: data_kw: key = ticker, value = pd.DataFrame Returns: pd.DataFrame Examples: >>> start = '2018-09-10T10:10:00' >>> tz = 'Australia/Sydney' >>> idx = pd.date_range(start=start, periods=6, freq='min').tz_localize(...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L170-L209
null
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/utils.py
to_frame
python
def to_frame(data_list, exc_cols=None, **kwargs): from collections import OrderedDict return pd.DataFrame( pd.Series(data_list).apply(OrderedDict).tolist(), **kwargs ).drop(columns=[] if exc_cols is None else exc_cols)
Dict in Python 3.6 keeps insertion order, but cannot be relied upon This method is to keep column names in order In Python 3.7 this method is redundant Args: data_list: list of dict exc_cols: exclude columns Returns: pd.DataFrame Example: >>> d_list = [ ......
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L262-L293
null
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/utils.py
spline_curve
python
def spline_curve(x, y, step, val_min=0, val_max=None, kind='quadratic', **kwargs): from scipy.interpolate import interp1d from collections import OrderedDict if isinstance(y, pd.DataFrame): return pd.DataFrame(OrderedDict([(col, spline_curve( x, y.loc[:, col], step=step, val_min=val_min...
Fit spline curve for given x, y values Args: x: x-values y: y-values step: step size for interpolation val_min: minimum value of result val_max: maximum value of result kind: for scipy.interpolate.interp1d Specifies the kind of interpolation as a string (‘lin...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L296-L346
null
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/utils.py
format_float
python
def format_float(digit=0, is_pct=False): if is_pct: space = ' ' if digit < 0 else '' fmt = f'{{:{space}.{abs(int(digit))}%}}' return lambda vv: 'NaN' if np.isnan(vv) else fmt.format(vv) else: return lambda vv: 'NaN' if np.isnan(vv) else ( f'{{:,.{digit}f}}'.format(vv...
Number display format for pandas Args: digit: number of digits to keep if negative, add one space in front of positive pct is_pct: % display Returns: lambda function to format floats Examples: >>> format_float(0)(1e5) '100,000' >>> format_flo...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L369-L400
null
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/utils.py
inst_repr
python
def inst_repr(instance, fmt='str', public_only=True): if not hasattr(instance, '__dict__'): return '' if public_only: inst_dict = {k: v for k, v in instance.__dict__.items() if k[0] != '_'} else: inst_dict = instance.__dict__ if fmt == 'json': return json.dumps(inst_dict, indent=2) elif fmt == 'st...
Generate class instance signature from its __dict__ From python 3.6 dict is ordered and order of attributes will be preserved automatically Args: instance: class instance fmt: ['json', 'str'] public_only: if display public members only Returns: str: string or json represent...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/utils.py#L469-L509
[ "def to_str(data: dict, fmt='{key}={value}', sep=', ', public_only=True):\n \"\"\"\n Convert dict to string\n\n Args:\n data: dict\n fmt: how key and value being represented\n sep: how pairs of key and value are seperated\n public_only: if display public members only\n\n Retu...
import numpy as np import pandas as pd import json import time import pytz import inspect import sys DEFAULT_TZ = pytz.FixedOffset(-time.timezone / 60) def tolist(iterable): """ Simpler implementation of flatten method Args: iterable: any array or value Returns: list: list of uniqu...
alpha-xone/xone
xone/profile.py
profile
python
def profile(func): def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() res = func(*args, **kwargs) pr.disable() s = io.StringIO() ps = pstats.Stats(pr, stream=s).sort_stats('cumulative') ps.print_stats() print(s.getvalue()) return...
Decorator to profile functions with cProfile Args: func: python function Returns: profile report References: https://osf.io/upav8/
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/profile.py#L6-L31
null
import cProfile import io import pstats
alpha-xone/xone
xone/procs.py
run
python
def run(func, keys, max_procs=None, show_proc=False, affinity=None, **kwargs): if max_procs is None: max_procs = cpu_count() kw_arr = saturate_kwargs(keys=keys, **kwargs) if len(kw_arr) == 0: return if isinstance(affinity, int): win32process.SetProcessAffinityMask(win32api.GetCurrentProcess(), ...
Provide interface for multiprocessing Args: func: callable functions keys: keys in kwargs that want to use process max_procs: max number of processes show_proc: whether to show process affinity: CPU affinity **kwargs: kwargs for func
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/procs.py#L16-L49
[ "def saturate_kwargs(keys, **kwargs):\n \"\"\"\n Saturate all combinations of kwargs\n\n Args:\n keys: keys in kwargs that want to use process\n **kwargs: kwargs for func\n \"\"\"\n # Validate if keys are in kwargs and if they are iterable\n if isinstance(keys, str): keys = [keys]\n ...
import sys import queue import pytest from multiprocessing import Process, cpu_count from itertools import product try: import win32process import win32api except ImportError: pytest.skip() sys.exit(1) def saturate_kwargs(keys, **kwargs): """ Saturate all combinations of kwargs Args: ...
alpha-xone/xone
xone/procs.py
saturate_kwargs
python
def saturate_kwargs(keys, **kwargs): # Validate if keys are in kwargs and if they are iterable if isinstance(keys, str): keys = [keys] keys = [k for k in keys if k in kwargs and hasattr(kwargs.get(k, None), '__iter__')] if len(keys) == 0: return [] # Saturate coordinates of kwargs kw_corr = lis...
Saturate all combinations of kwargs Args: keys: keys in kwargs that want to use process **kwargs: kwargs for func
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/procs.py#L52-L78
null
import sys import queue import pytest from multiprocessing import Process, cpu_count from itertools import product try: import win32process import win32api except ImportError: pytest.skip() sys.exit(1) def run(func, keys, max_procs=None, show_proc=False, affinity=None, **kwargs): """ Provide...
alpha-xone/xone
xone/calendar.py
trading_dates
python
def trading_dates(start, end, calendar='US'): kw = dict(start=pd.Timestamp(start, tz='UTC').date(), end=pd.Timestamp(end, tz='UTC').date()) us_cal = getattr(sys.modules[__name__], f'{calendar}TradingCalendar')() return pd.bdate_range(**kw).drop(us_cal.holidays(**kw))
Trading dates for given exchange Args: start: start date end: end date calendar: exchange as string Returns: pd.DatetimeIndex: datetime index Examples: >>> bus_dates = ['2018-12-24', '2018-12-26', '2018-12-27'] >>> trd_dates = trading_dates(start='2018-12-2...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/calendar.py#L22-L42
null
import pandas as pd import sys from pandas.tseries import holiday class USTradingCalendar(holiday.AbstractHolidayCalendar): rules = [ holiday.Holiday('NewYearsDay', month=1, day=1, observance=holiday.nearest_workday), holiday.USMartinLutherKingJr, holiday.USPresidentsDay, holiday...
alpha-xone/xone
xone/logs.py
get_logger
python
def get_logger( name_or_func, log_file='', level=logging.INFO, types='stream', **kwargs ): if isinstance(level, str): level = getattr(logging, level.upper()) log_name = name_or_func if isinstance(name_or_func, str) else utils.func_scope(name_or_func) logger = logging.getLogger(name=log_name) log...
Generate logger Args: name_or_func: logger name or current running function log_file: logger file level: level of logs - debug, info, error types: file or stream, or both Returns: logger Examples: >>> get_logger(name_or_func='download_data', level='debug', ...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/logs.py#L8-L47
[ "def func_scope(func):\n \"\"\"\n Function scope name\n\n Args:\n func: python function\n\n Returns:\n str: module_name.func_name\n\n Examples:\n >>> func_scope(flatten)\n 'xone.utils.flatten'\n >>> func_scope(json.dump)\n 'json.dump'\n \"\"\"\n cur_mod...
import logging from xone import utils LOG_FMT = '%(asctime)s:%(name)s:%(levelname)s:%(message)s'
alpha-xone/xone
xone/cache.py
cache_file
python
def cache_file(symbol, func, has_date, root, date_type='date'): cur_mod = sys.modules[func.__module__] data_tz = getattr(cur_mod, 'DATA_TZ') if hasattr(cur_mod, 'DATA_TZ') else 'UTC' cur_dt = utils.cur_time(typ=date_type, tz=data_tz, trading=False) if has_date: if hasattr(cur_mod, 'FILE_WITH_DA...
Data file Args: symbol: symbol func: use function to categorize data has_date: contains date in data file root: root path date_type: parameters pass to utils.cur_time, [date, time, time_path, ...] Returns: str: date file
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L12-L43
[ "def cur_time(typ='date', tz=DEFAULT_TZ, trading=True, cal='US'):\n \"\"\"\n Current time\n\n Args:\n typ: one of ['date', 'time', 'time_path', 'raw', '']\n tz: timezone\n trading: check if current date is trading day\n cal: trading calendar\n\n Returns:\n relevant cur...
import hashlib import json import pandas as pd import sys import inspect from functools import wraps from xone import utils, files, logs def update_data(func): """ Decorator to save data more easily. Use parquet as data format Args: func: function to load data from data source Returns: ...
alpha-xone/xone
xone/cache.py
update_data
python
def update_data(func): default = dict([ (param.name, param.default) for param in inspect.signature(func).parameters.values() if param.default != getattr(inspect, '_empty') ]) @wraps(func) def wrapper(*args, **kwargs): default.update(kwargs) kwargs.update(default...
Decorator to save data more easily. Use parquet as data format Args: func: function to load data from data source Returns: wrapped function
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L46-L99
null
import hashlib import json import pandas as pd import sys import inspect from functools import wraps from xone import utils, files, logs def cache_file(symbol, func, has_date, root, date_type='date'): """ Data file Args: symbol: symbol func: use function to categorize data has_d...
alpha-xone/xone
xone/cache.py
save_data
python
def save_data(data, file_fmt, append=False, drop_dups=None, info=None, **kwargs): d_file = data_file(file_fmt=file_fmt, info=info, **kwargs) if append and files.exists(d_file): data = pd.DataFrame(pd.concat([pd.read_parquet(d_file), data], sort=False)) if drop_dups is not None: data....
Save data to file Args: data: pd.DataFrame file_fmt: data file format in terms of f-strings append: if append data to existing data drop_dups: list, drop duplicates in columns info: dict, infomation to be hashed and passed to f-strings **kwargs: additional parameters...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L102-L128
[ "def tolist(iterable):\n \"\"\"\n Simpler implementation of flatten method\n\n Args:\n iterable: any array or value\n\n Returns:\n list: list of unique values\n\n Examples:\n >>> tolist('xyz')\n ['xyz']\n >>> tolist(['ab', 'cd', 'xy', 'ab'])\n ['ab', 'cd', 'x...
import hashlib import json import pandas as pd import sys import inspect from functools import wraps from xone import utils, files, logs def cache_file(symbol, func, has_date, root, date_type='date'): """ Data file Args: symbol: symbol func: use function to categorize data has_d...
alpha-xone/xone
xone/cache.py
data_file
python
def data_file(file_fmt, info=None, **kwargs): if isinstance(info, dict): kwargs['hash_key'] = hashlib.sha256(json.dumps(info).encode('utf-8')).hexdigest() kwargs.update(info) return utils.fstr(fmt=file_fmt, **kwargs)
Data file name for given infomation Args: file_fmt: file format in terms of f-strings info: dict, to be hashed and then pass to f-string using 'hash_key' these info will also be passed to f-strings **kwargs: arguments for f-strings Returns: str: data file name
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/cache.py#L131-L148
[ "def fstr(fmt, **kwargs):\n \"\"\"\n Delayed evaluation of f-strings\n\n Args:\n fmt: f-string but in terms of normal string, i.e., '{path}/{file}.parq'\n **kwargs: variables for f-strings, i.e., path, file = '/data', 'daily'\n\n Returns:\n FString object\n\n References:\n ...
import hashlib import json import pandas as pd import sys import inspect from functools import wraps from xone import utils, files, logs def cache_file(symbol, func, has_date, root, date_type='date'): """ Data file Args: symbol: symbol func: use function to categorize data has_d...
alpha-xone/xone
xone/plots.py
plot_multi
python
def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs): import matplotlib.pyplot as plt from pandas import plotting if cols is None: cols = data.columns if plot_kw is None: plot_kw = [{}] * len(cols) if len(cols) == 0: return num_colors = len(utils.flatten(cols)) ...
Plot data with multiple scaels together Args: data: DataFrame of data cols: columns to be plotted spacing: spacing between legends color_map: customized colors in map plot_kw: kwargs for each plot **kwargs: kwargs for the first plot Returns: ax for plot ...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/plots.py#L4-L87
[ "def flatten(iterable, maps=None, unique=False):\n \"\"\"\n Flatten any array of items to list\n\n Args:\n iterable: any array or value\n maps: map items to values\n unique: drop duplicates\n\n Returns:\n list: flattened list\n\n References:\n https://stackoverflow....
from xone import utils def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs): """ Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot R...
alpha-xone/xone
xone/plots.py
plot_h
python
def plot_h(data, cols, wspace=.1, plot_kw=None, **kwargs): import matplotlib.pyplot as plt if plot_kw is None: plot_kw = [dict()] * len(cols) _, axes = plt.subplots(nrows=1, ncols=len(cols), **kwargs) plt.subplots_adjust(wspace=wspace) for n, col in enumerate(cols): data.loc[:, col].plot(a...
Plot horizontally Args: data: DataFrame of data cols: columns to be plotted wspace: spacing between plots plot_kw: kwargs for each plot **kwargs: kwargs for the whole plot Returns: axes for plots Examples: >>> import pandas as pd >>> import ...
train
https://github.com/alpha-xone/xone/blob/68534a30f7f1760b220ba58040be3927f7dfbcf4/xone/plots.py#L90-L121
null
from xone import utils def plot_multi(data, cols=None, spacing=.06, color_map=None, plot_kw=None, **kwargs): """ Plot data with multiple scaels together Args: data: DataFrame of data cols: columns to be plotted spacing: spacing between legends color_map: customized colors ...
mozilla-releng/signtool
signtool/signing/client.py
uploadfile
python
def uploadfile(baseurl, filename, format_, token, nonce, cert, method=requests.post): filehash = sha1sum(filename) files = {'filedata': open(filename, 'rb')} payload = { 'sha1': filehash, 'filename': os.path.basename(filename), 'token': token, 'nonce': nonce, } retu...
Uploads file (given by `filename`) to server at `baseurl`. `sesson_key` and `nonce` are string values that get passed as POST parameters.
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/signing/client.py#L161-L177
[ "def sha1sum(f):\n \"\"\"Return the SHA-1 hash of the contents of file `f`, in hex format\"\"\"\n h = hashlib.sha1()\n fp = open(f, 'rb')\n while True:\n block = fp.read(512 * 1024)\n if not block:\n break\n h.update(block)\n return h.hexdigest()\n" ]
import os import requests import six from subprocess import check_call import time from signtool.util.file import sha1sum, safe_copyfile import logging log = logging.getLogger(__name__) def getfile(baseurl, filehash, format_, cert, method=requests.get): url = "%s/sign/%s/%s" % (baseurl, format_, filehash) l...
mozilla-releng/signtool
signtool/signtool.py
is_authenticode_signed
python
def is_authenticode_signed(filename): with open(filename, 'rb') as fp: fp.seek(0) magic = fp.read(2) if magic != b'MZ': return False # First grab the pointer to the coff_header, which is at offset 60 fp.seek(60) coff_header_offset = struct.unpack('<L', fp...
Returns True if the file is signed with authenticode
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/signtool.py#L37-L88
null
#!/usr/bin/env python """signtool.py [options] file [file ...] If no include patterns are specified, all files will be considered. -i/-x only have effect when signing entire directories.""" from __future__ import absolute_import, division, print_function from collections import defaultdict import logging import os imp...
mozilla-releng/signtool
signtool/signtool.py
parse_cmdln_opts
python
def parse_cmdln_opts(parser, cmdln_args): parser.set_defaults( hosts=[], cert=None, log_level=logging.INFO, output_dir=None, output_file=None, formats=[], includes=[], excludes=[], nsscmd=None, tokenfile=None, noncefile=None, ...
Rather than have this all clutter main(), let's split this out. Clean arch decision: rather than parsing sys.argv directly, pass sys.argv[1:] to this function (or any iterable for testing.)
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/signtool.py#L92-L229
[ "def error(self, msg, *args):\n self.msg = msg\n raise SystemExit(msg)\n" ]
#!/usr/bin/env python """signtool.py [options] file [file ...] If no include patterns are specified, all files will be considered. -i/-x only have effect when signing entire directories.""" from __future__ import absolute_import, division, print_function from collections import defaultdict import logging import os imp...
mozilla-releng/signtool
signtool/util/paths.py
cygpath
python
def cygpath(filename): if sys.platform == 'cygwin': proc = Popen(['cygpath', '-am', filename], stdout=PIPE) return proc.communicate()[0].strip() else: return filename
Convert a cygwin path into a windows style path
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/paths.py#L11-L17
null
import os.path import sys import fnmatch import logging # TODO: Use util.commands from subprocess import PIPE, Popen log = logging.getLogger(__name__) def convertPath(srcpath, dstdir): """Given `srcpath`, return a corresponding path within `dstdir`""" bits = srcpath.split("/") bits.pop(0) # Strip ou...
mozilla-releng/signtool
signtool/util/paths.py
convertPath
python
def convertPath(srcpath, dstdir): bits = srcpath.split("/") bits.pop(0) # Strip out leading 'unsigned' from paths like unsigned/update/win32/... if bits[0] == 'unsigned': bits.pop(0) return os.path.join(dstdir, *bits)
Given `srcpath`, return a corresponding path within `dstdir`
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/paths.py#L20-L27
null
import os.path import sys import fnmatch import logging # TODO: Use util.commands from subprocess import PIPE, Popen log = logging.getLogger(__name__) def cygpath(filename): """Convert a cygwin path into a windows style path""" if sys.platform == 'cygwin': proc = Popen(['cygpath', '-am', filename], s...
mozilla-releng/signtool
signtool/util/paths.py
finddirs
python
def finddirs(root): retval = [] for root, dirs, files in os.walk(root): for d in dirs: retval.append(os.path.join(root, d)) return retval
Return a list of all the directories under `root`
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/paths.py#L52-L58
null
import os.path import sys import fnmatch import logging # TODO: Use util.commands from subprocess import PIPE, Popen log = logging.getLogger(__name__) def cygpath(filename): """Convert a cygwin path into a windows style path""" if sys.platform == 'cygwin': proc = Popen(['cygpath', '-am', filename], s...
mozilla-releng/signtool
signtool/util/archives.py
unpackexe
python
def unpackexe(exefile, destdir): nullfd = open(os.devnull, "w") exefile = cygpath(os.path.abspath(exefile)) try: check_call([SEVENZIP, 'x', exefile], cwd=destdir, stdout=nullfd, preexec_fn=_noumask) except Exception: log.exception("Error unpacking exe %s to %s", exefil...
Unpack the given exefile into destdir, using 7z
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L23-L33
[ "def cygpath(filename):\n \"\"\"Convert a cygwin path into a windows style path\"\"\"\n if sys.platform == 'cygwin':\n proc = Popen(['cygpath', '-am', filename], stdout=PIPE)\n return proc.communicate()[0].strip()\n else:\n return filename\n" ]
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
packexe
python
def packexe(exefile, srcdir): exefile = cygpath(os.path.abspath(exefile)) appbundle = exefile + ".app.7z" # Make sure that appbundle doesn't already exist # We don't want to risk appending to an existing file if os.path.exists(appbundle): raise OSError("%s already exists" % appbundle) ...
Pack the files in srcdir into exefile using 7z. Requires that stub files are available in checkouts/stubs
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L36-L83
[ "def cygpath(filename):\n \"\"\"Convert a cygwin path into a windows style path\"\"\"\n if sys.platform == 'cygwin':\n proc = Popen(['cygpath', '-am', filename], stdout=PIPE)\n return proc.communicate()[0].strip()\n else:\n return filename\n" ]
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
bunzip2
python
def bunzip2(filename): log.debug("Uncompressing %s", filename) tmpfile = "%s.tmp" % filename os.rename(filename, tmpfile) b = bz2.BZ2File(tmpfile) f = open(filename, "wb") while True: block = b.read(512 * 1024) if not block: break f.write(block) f.close() ...
Uncompress `filename` in place
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L86-L102
null
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
unpackmar
python
def unpackmar(marfile, destdir): marfile = cygpath(os.path.abspath(marfile)) nullfd = open(os.devnull, "w") try: check_call([MAR, '-x', marfile], cwd=destdir, stdout=nullfd, preexec_fn=_noumask) except Exception: log.exception("Error unpacking mar file %s to %s", marfi...
Unpack marfile into destdir
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L124-L134
[ "def cygpath(filename):\n \"\"\"Convert a cygwin path into a windows style path\"\"\"\n if sys.platform == 'cygwin':\n proc = Popen(['cygpath', '-am', filename], stdout=PIPE)\n return proc.communicate()[0].strip()\n else:\n return filename\n" ]
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
packmar
python
def packmar(marfile, srcdir): nullfd = open(os.devnull, "w") files = [f[len(srcdir) + 1:] for f in findfiles(srcdir)] marfile = cygpath(os.path.abspath(marfile)) try: check_call( [MAR, '-c', marfile] + files, cwd=srcdir, preexec_fn=_noumask) except Exception: log.exceptio...
Create marfile from the contents of srcdir
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L137-L148
[ "def cygpath(filename):\n \"\"\"Convert a cygwin path into a windows style path\"\"\"\n if sys.platform == 'cygwin':\n proc = Popen(['cygpath', '-am', filename], stdout=PIPE)\n return proc.communicate()[0].strip()\n else:\n return filename\n", "def findfiles(roots, includes=('*', ), ...
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
unpacktar
python
def unpacktar(tarfile, destdir): nullfd = open(os.devnull, "w") tarfile = cygpath(os.path.abspath(tarfile)) log.debug("unpack tar %s into %s", tarfile, destdir) try: check_call([TAR, '-xzf', tarfile], cwd=destdir, stdout=nullfd, preexec_fn=_noumask) except Exception: ...
Unpack given tarball into the specified dir
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L151-L162
[ "def cygpath(filename):\n \"\"\"Convert a cygwin path into a windows style path\"\"\"\n if sys.platform == 'cygwin':\n proc = Popen(['cygpath', '-am', filename], stdout=PIPE)\n return proc.communicate()[0].strip()\n else:\n return filename\n" ]
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
tar_dir
python
def tar_dir(tarfile, srcdir): files = os.listdir(srcdir) packtar(tarfile, files, srcdir)
Pack a tar file using all the files in the given srcdir
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L165-L168
[ "def packtar(tarfile, files, srcdir):\n \"\"\" Pack the given files into a tar, setting cwd = srcdir\"\"\"\n nullfd = open(os.devnull, \"w\")\n tarfile = cygpath(os.path.abspath(tarfile))\n log.debug(\"pack tar %s from folder %s with files \", tarfile, srcdir)\n log.debug(files)\n try:\n c...
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
packtar
python
def packtar(tarfile, files, srcdir): nullfd = open(os.devnull, "w") tarfile = cygpath(os.path.abspath(tarfile)) log.debug("pack tar %s from folder %s with files ", tarfile, srcdir) log.debug(files) try: check_call([TAR, '-czf', tarfile] + files, cwd=srcdir, stdout=nullfd,...
Pack the given files into a tar, setting cwd = srcdir
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L171-L183
[ "def cygpath(filename):\n \"\"\"Convert a cygwin path into a windows style path\"\"\"\n if sys.platform == 'cygwin':\n proc = Popen(['cygpath', '-am', filename], stdout=PIPE)\n return proc.communicate()[0].strip()\n else:\n return filename\n" ]
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
unpackfile
python
def unpackfile(filename, destdir): if filename.endswith(".mar"): return unpackmar(filename, destdir) elif filename.endswith(".exe"): return unpackexe(filename, destdir) elif filename.endswith(".tar") or filename.endswith(".tar.gz") \ or filename.endswith(".tgz"): return u...
Unpack a mar or exe into destdir
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L186-L196
[ "def unpackmar(marfile, destdir):\n \"\"\"Unpack marfile into destdir\"\"\"\n marfile = cygpath(os.path.abspath(marfile))\n nullfd = open(os.devnull, \"w\")\n try:\n check_call([MAR, '-x', marfile], cwd=destdir,\n stdout=nullfd, preexec_fn=_noumask)\n except Exception:\n ...
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/archives.py
packfile
python
def packfile(filename, srcdir): if filename.endswith(".mar"): return packmar(filename, srcdir) elif filename.endswith(".exe"): return packexe(filename, srcdir) elif filename.endswith(".tar"): return tar_dir(filename, srcdir) else: raise ValueError("Unknown file type: %s" ...
Package up srcdir into filename, archived with 7z for exes or mar for mar files
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/archives.py#L199-L209
[ "def packmar(marfile, srcdir):\n \"\"\"Create marfile from the contents of srcdir\"\"\"\n nullfd = open(os.devnull, \"w\")\n files = [f[len(srcdir) + 1:] for f in findfiles(srcdir)]\n marfile = cygpath(os.path.abspath(marfile))\n try:\n check_call(\n [MAR, '-c', marfile] + files, cw...
import os # TODO: use util.commands from subprocess import check_call import logging import tempfile import bz2 import shutil from signtool.util.paths import cygpath, findfiles log = logging.getLogger(__name__) SEVENZIP = os.environ.get('SEVENZIP', '7z') MAR = os.environ.get('MAR', 'mar') TAR = os.environ.get('TAR',...
mozilla-releng/signtool
signtool/util/file.py
compare
python
def compare(file1, file2): if isinstance(file1, six.string_types): # pragma: no branch file1 = open(file1, 'r', True) if isinstance(file2, six.string_types): # pragma: no branch file2 = open(file2, 'r', True) file1_contents = file1.read() file2_contents = file2.read() return file1_...
compares the contents of two files, passed in either as open file handles or accessible file paths. Does a simple naive string comparison, so do not use on larger files
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/file.py#L11-L21
null
"""Helper functions to handle file operations""" import logging import os import shutil import six import hashlib import tempfile log = logging.getLogger(__name__) def sha1sum(f): """Return the SHA-1 hash of the contents of file `f`, in hex format""" h = hashlib.sha1() fp = open(f, 'rb') while True: ...
mozilla-releng/signtool
signtool/util/file.py
sha1sum
python
def sha1sum(f): h = hashlib.sha1() fp = open(f, 'rb') while True: block = fp.read(512 * 1024) if not block: break h.update(block) return h.hexdigest()
Return the SHA-1 hash of the contents of file `f`, in hex format
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/file.py#L24-L33
null
"""Helper functions to handle file operations""" import logging import os import shutil import six import hashlib import tempfile log = logging.getLogger(__name__) def compare(file1, file2): """compares the contents of two files, passed in either as open file handles or accessible file paths. Does a simple...
mozilla-releng/signtool
signtool/util/file.py
safe_copyfile
python
def safe_copyfile(src, dest): fd, tmpname = tempfile.mkstemp(dir=os.path.dirname(dest)) shutil.copyfileobj(open(src, 'rb'), os.fdopen(fd, 'wb')) shutil.copystat(src, tmpname) os.rename(tmpname, dest)
safely copy src to dest using a temporary intermediate and then renaming to dest
train
https://github.com/mozilla-releng/signtool/blob/0a778778a181cb9cab424b29fa104b70345f53c2/signtool/util/file.py#L36-L42
null
"""Helper functions to handle file operations""" import logging import os import shutil import six import hashlib import tempfile log = logging.getLogger(__name__) def compare(file1, file2): """compares the contents of two files, passed in either as open file handles or accessible file paths. Does a simple...
lobocv/pyperform
pyperform/comparisonbenchmark.py
ComparisonBenchmark.validate
python
def validate(self): validation_code = self.setup_src + '\nvalidation_result = ' + self.stmt validation_scope = {} exec(validation_code, validation_scope) # Store the result in the first function in the group. if len(self.groups[self.group]) == 1: self.result = validat...
Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/comparisonbenchmark.py#L36-L64
null
class ComparisonBenchmark(Benchmark): groups = {} def __init__(self, group, classname=None, setup=None, validation=False, validation_func=None, largs=None, kwargs=None, **kw): super(ComparisonBenchmark, self).__init__(setup=setup, largs=largs, kwargs=kwargs, **kw) self.group = group sel...
lobocv/pyperform
pyperform/comparisonbenchmark.py
ComparisonBenchmark.summarize
python
def summarize(group, fs=None, include_source=True): _line_break = '{0:-<120}\n'.format('') tests = sorted(ComparisonBenchmark.groups[group], key=lambda t: getattr(t, 'time_average_seconds')) log = StringIO.StringIO() log.write('Call statement:\n\n') log.write('\t' + tests[0].stmt...
Tabulate and write the results of ComparisonBenchmarks to a file or standard out. :param str group: name of the comparison group. :param fs: file-like object (Optional)
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/comparisonbenchmark.py#L67-L115
[ "def convert_time_units(t):\n \"\"\" Convert time in seconds into reasonable time units. \"\"\"\n if t == 0:\n return '0 s'\n order = log10(t)\n if -9 < order < -6:\n time_units = 'ns'\n factor = 1000000000\n elif -6 <= order < -3:\n time_units = 'us'\n factor = 100...
class ComparisonBenchmark(Benchmark): groups = {} def __init__(self, group, classname=None, setup=None, validation=False, validation_func=None, largs=None, kwargs=None, **kw): super(ComparisonBenchmark, self).__init__(setup=setup, largs=largs, kwargs=kwargs, **kw) self.group = group sel...
lobocv/pyperform
pyperform/__init__.py
enable
python
def enable(): Benchmark.enable = True ComparisonBenchmark.enable = True BenchmarkedFunction.enable = True BenchmarkedClass.enable = True
Enable all benchmarking.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/__init__.py#L23-L30
null
from __future__ import print_function __version__ = '1.86' import sys if sys.version[0] == '3': import io as StringIO # Python 3.x else: import cStringIO as StringIO # Python 2.x range = xrange from pyperform.benchmark import Benchmark from .comparisonbenchmark import ComparisonBenchmark from .benchma...
lobocv/pyperform
pyperform/__init__.py
disable
python
def disable(): Benchmark.enable = False ComparisonBenchmark.enable = False BenchmarkedFunction.enable = False BenchmarkedClass.enable = False
Disable all benchmarking.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/__init__.py#L33-L40
null
from __future__ import print_function __version__ = '1.86' import sys if sys.version[0] == '3': import io as StringIO # Python 3.x else: import cStringIO as StringIO # Python 2.x range = xrange from pyperform.benchmark import Benchmark from .comparisonbenchmark import ComparisonBenchmark from .benchma...
lobocv/pyperform
pyperform/customlogger.py
new_log_level
python
def new_log_level(level, name, logger_name=None): @CustomLogLevel(level, name, logger_name) def _default_template(logger, msg, *args, **kwargs): return msg, args, kwargs
Quick way to create a custom log level that behaves like the default levels in the logging module. :param level: level number :param name: level name :param logger_name: optional logger name
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/customlogger.py#L40-L49
null
__author__ = 'clobo' import logging class CustomLogLevel(object): def __init__(self, level, name, logger_name=None): self.level = level self.name = name self.logger_name = logger_name if logger_name is None: self.logger = logging.getLogger() else: ...
lobocv/pyperform
pyperform/thread.py
enable_thread_profiling
python
def enable_thread_profiling(profile_dir, exception_callback=None): global profiled_thread_enabled, Thread, Process if os.path.isdir(profile_dir): _Profiler.profile_dir = profile_dir else: raise OSError('%s does not exist' % profile_dir) _Profiler.exception_callback = exception_callback ...
Monkey-patch the threading.Thread class with our own ProfiledThread. Any subsequent imports of threading.Thread will reference ProfiledThread instead.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/thread.py#L22-L35
null
__author__ = 'calvin' import cProfile import logging from pyperform import StringIO import os import pstats import sys import threading import multiprocessing Thread = threading.Thread # Start off using threading.Thread until changed Process = multiprocessing.Process BaseThread = threading.Thread # Sto...
lobocv/pyperform
pyperform/thread.py
enable_thread_logging
python
def enable_thread_logging(exception_callback=None): global logged_thread_enabled, Thread LoggedThread.exception_callback = exception_callback Thread = threading.Thread = LoggedThread logged_thread_enabled = True
Monkey-patch the threading.Thread class with our own LoggedThread. Any subsequent imports of threading.Thread will reference LoggedThread instead.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/thread.py#L38-L46
null
__author__ = 'calvin' import cProfile import logging from pyperform import StringIO import os import pstats import sys import threading import multiprocessing Thread = threading.Thread # Start off using threading.Thread until changed Process = multiprocessing.Process BaseThread = threading.Thread # Sto...
lobocv/pyperform
pyperform/tools.py
convert_time_units
python
def convert_time_units(t): if t == 0: return '0 s' order = log10(t) if -9 < order < -6: time_units = 'ns' factor = 1000000000 elif -6 <= order < -3: time_units = 'us' factor = 1000000 elif -3 <= order < -1: time_units = 'ms' factor = 1000. ...
Convert time in seconds into reasonable time units.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/tools.py#L17-L34
null
__author__ = 'calvin' import re import sys from math import log10 if sys.version[0] == '3': pass else: range = xrange classdef_regex = re.compile(r"\S*def .*#!|class .*#!") tagged_line_regex = re.compile(r".*#!") def globalize_indentation(src): """ Strip the indentation level so the code runs in the ...
lobocv/pyperform
pyperform/tools.py
globalize_indentation
python
def globalize_indentation(src): lines = src.splitlines() indent = len(lines[0]) - len(lines[0].strip(' ')) func_src = '' for ii, l in enumerate(src.splitlines()): line = l[indent:] func_src += line + '\n' return func_src
Strip the indentation level so the code runs in the global scope.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/tools.py#L37-L45
null
__author__ = 'calvin' import re import sys from math import log10 if sys.version[0] == '3': pass else: range = xrange classdef_regex = re.compile(r"\S*def .*#!|class .*#!") tagged_line_regex = re.compile(r".*#!") def convert_time_units(t): """ Convert time in seconds into reasonable time units. """ ...
lobocv/pyperform
pyperform/tools.py
remove_decorators
python
def remove_decorators(src): src = src.strip() src_lines = src.splitlines() multi_line = False n_deleted = 0 for n in range(len(src_lines)): line = src_lines[n - n_deleted].strip() if (line.startswith('@') and 'Benchmark' in line) or multi_line: del src_lines[n - n_deleted...
Remove decorators from the source code
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/tools.py#L48-L64
null
__author__ = 'calvin' import re import sys from math import log10 if sys.version[0] == '3': pass else: range = xrange classdef_regex = re.compile(r"\S*def .*#!|class .*#!") tagged_line_regex = re.compile(r".*#!") def convert_time_units(t): """ Convert time in seconds into reasonable time units. """ ...
lobocv/pyperform
pyperform/tools.py
walk_tree
python
def walk_tree(start, attr): path = [start] for child in path: yield child idx = path.index(child) for grandchild in reversed(getattr(child, attr)): path.insert(idx + 1, grandchild)
Recursively walk through a tree relationship. This iterates a tree in a top-down approach, fully reaching the end of a lineage before moving onto the next sibling of that generation.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/tools.py#L137-L147
null
__author__ = 'calvin' import re import sys from math import log10 if sys.version[0] == '3': pass else: range = xrange classdef_regex = re.compile(r"\S*def .*#!|class .*#!") tagged_line_regex = re.compile(r".*#!") def convert_time_units(t): """ Convert time in seconds into reasonable time units. """ ...
lobocv/pyperform
pyperform/benchmarkedclass.py
BenchmarkedClass.validate
python
def validate(self, benchmarks): class_code = self.setup_src instance_creation = '\ninstance = {}'.format(self.stmt) for i, benchmark in enumerate(benchmarks): if not benchmark.result_validation: break validation_code = class_code + instance_creation + '\n...
Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group. :param benchmarks: list of benchmarks to validate.
train
https://github.com/lobocv/pyperform/blob/97d87e8b9ddb35bd8f2a6782965fd7735ab0349f/pyperform/benchmarkedclass.py#L36-L64
null
class BenchmarkedClass(Benchmark): bound_functions = {} def __init__(self, setup=None, largs=None, kwargs=None, **kw): super(BenchmarkedClass, self).__init__(setup, largs=largs, kwargs=kwargs, **kw) def __call__(self, cls): if self.enable: super(BenchmarkedClass, self).__call__...