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
jspricke/python-abook
abook.py
Abook._gen_addr
python
def _gen_addr(entry): return Address(street=entry.get('address', ''), extended=entry.get('address2', ''), city=entry.get('city', ''), region=entry.get('state', ''), code=entry.get('zip', ''), count...
Generates a vCard Address object
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L125-L132
null
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook._add_photo
python
def _add_photo(self, card, name): try: photo_file = join(dirname(self._filename), 'photo/%s.jpeg' % name) jpeg = open(photo_file, 'rb').read() photo = card.add('photo') photo.type_param = 'jpeg' photo.encoding_param = 'b' photo.value = jpeg...
Tries to load a photo and add it to the vCard
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L134-L144
null
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook._to_vcard
python
def _to_vcard(self, entry): card = vCard() card.add('uid').value = Abook._gen_uid(entry) card.add('fn').value = entry['name'] card.add('n').value = Abook._gen_name(entry['name']) if 'email' in entry: for email in entry['email'].split(','): card.add('...
Return a vCard of the Abook entry
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L146-L192
[ "def _gen_uid(entry):\n \"\"\"Generates a UID based on the index in the Abook file\n Not that the index is just a number and abook tends to regenerate it upon sorting.\n \"\"\"\n return '%s@%s' % (entry.name, getfqdn())\n", "def _gen_name(name):\n \"\"\"Splits the name into family and given name\"\...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.get_uids
python
def get_uids(self, filename=None): self._update() return [Abook._gen_uid(self._book[entry]) for entry in self._book.sections()]
Return a list of UIDs filename -- unused, for API compatibility only
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L194-L199
[ "def _update(self):\n \"\"\" Update internal state.\"\"\"\n with self._lock:\n if getmtime(self._filename) > self._last_modified:\n self._last_modified = getmtime(self._filename)\n self._book = ConfigParser(default_section='format')\n self._book.read(self._filename)\n" ...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.to_vcards
python
def to_vcards(self): self._update() return [self._to_vcard(self._book[entry]) for entry in self._book.sections()]
Return a list of vCards
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L214-L217
[ "def _update(self):\n \"\"\" Update internal state.\"\"\"\n with self._lock:\n if getmtime(self._filename) > self._last_modified:\n self._last_modified = getmtime(self._filename)\n self._book = ConfigParser(default_section='format')\n self._book.read(self._filename)\n" ...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.to_vobjects
python
def to_vobjects(self, filename, uids=None): self._update() if not uids: uids = self.get_uids(filename) items = [] for uid in uids: entry = self._book[uid.split('@')[0]] # TODO add getmtime of photo etag = sha1(str(dict(entry)).encode('ut...
Return vCards and etags of all Abook entries in uids filename -- unused, for API compatibility only uids -- the UIDs of the Abook entries (all if None)
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L226-L243
[ "def _update(self):\n \"\"\" Update internal state.\"\"\"\n with self._lock:\n if getmtime(self._filename) > self._last_modified:\n self._last_modified = getmtime(self._filename)\n self._book = ConfigParser(default_section='format')\n self._book.read(self._filename)\n",...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.to_vobject
python
def to_vobject(self, filename=None, uid=None): self._update() return self._to_vcard(self._book[uid.split('@')[0]])
Return the vCard corresponding to the uid filename -- unused, for API compatibility only uid -- the UID to get (required)
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L245-L251
[ "def _update(self):\n \"\"\" Update internal state.\"\"\"\n with self._lock:\n if getmtime(self._filename) > self._last_modified:\n self._last_modified = getmtime(self._filename)\n self._book = ConfigParser(default_section='format')\n self._book.read(self._filename)\n",...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook._conv_adr
python
def _conv_adr(adr, entry): if adr.value.street: entry['address'] = adr.value.street if adr.value.extended: entry['address2'] = adr.value.extended if adr.value.city: entry['city'] = adr.value.city if adr.value.region: entry['state'] = adr.va...
Converts to Abook address format
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L254-L267
null
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook._conv_tel_list
python
def _conv_tel_list(tel_list, entry): for tel in tel_list: if not hasattr(tel, 'TYPE_param'): entry['other'] = tel.value elif tel.TYPE_param.lower() == 'home': entry['phone'] = tel.value elif tel.TYPE_param.lower() == 'work': ent...
Converts to Abook phone types
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L270-L280
null
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.to_abook
python
def to_abook(card, section, book, bookfile=None): book[section] = {} book[section]['name'] = card.fn.value if hasattr(card, 'email'): book[section]['email'] = ','.join([e.value for e in card.email_list]) if hasattr(card, 'adr'): Abook._conv_adr(card.adr, book[se...
Converts a vCard to Abook
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L283-L311
[ "def _conv_adr(adr, entry):\n \"\"\"Converts to Abook address format\"\"\"\n if adr.value.street:\n entry['address'] = adr.value.street\n if adr.value.extended:\n entry['address2'] = adr.value.extended\n if adr.value.city:\n entry['city'] = adr.value.city\n if adr.value.region:\n...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
jspricke/python-abook
abook.py
Abook.abook_file
python
def abook_file(vcard, bookfile): book = ConfigParser(default_section='format') book['format'] = {} book['format']['program'] = 'abook' book['format']['version'] = '0.6.1' for (i, card) in enumerate(readComponents(vcard.read())): Abook.to_abook(card, str(i), book, bo...
Write a new Abook file with the given vcards
train
https://github.com/jspricke/python-abook/blob/cc58ad998303ce9a8b347a3317158c8f7cd0529f/abook.py#L314-L325
[ "def to_abook(card, section, book, bookfile=None):\n \"\"\"Converts a vCard to Abook\"\"\"\n book[section] = {}\n book[section]['name'] = card.fn.value\n\n if hasattr(card, 'email'):\n book[section]['email'] = ','.join([e.value for e in card.email_list])\n\n if hasattr(card, 'adr'):\n A...
class Abook(object): """Represents a Abook addressbook""" def __init__(self, filename=expanduser('~/.abook/addressbook')): """Constructor filename -- the filename to load (default: ~/.abook/addressbook) """ self._filename = filename self._last_modified = 0 self....
slarse/pdfebc-core
pdfebc_core/email_utils.py
send_with_attachments
python
async def send_with_attachments(subject, message, filepaths, config): email_ = MIMEMultipart() email_.attach(MIMEText(message)) email_["Subject"] = subject email_["From"] = get_attribute_from_config(config, EMAIL_SECTION_KEY, USER_KEY) email_["To"] = get_attribute_from_config(config, EMAIL_SECTION_K...
Send an email from the user (a gmail) to the receiver. Args: subject (str): Subject of the email. message (str): A message. filepaths (list(str)): Filepaths to files to be attached. config (defaultdict): A defaultdict.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L36-L51
[ "def get_attribute_from_config(config, section, attribute):\n \"\"\"Try to parse an attribute of the config file.\n\n Args:\n config (defaultdict): A defaultdict.\n section (str): The section of the config file to get information from.\n attribute (str): The attribute of the section to fe...
# -*- coding: utf-8 -*- """Module containing email util functions for the pdfebc program. The SMTP server and port are configured in the config.cnf file, see the config_utils module for more information. .. module:: utils :platform: Unix :synopsis: Email utility functions for pdfebc. .. moduleauthor:: Simon ...
slarse/pdfebc-core
pdfebc_core/email_utils.py
_attach_files
python
def _attach_files(filepaths, email_): for filepath in filepaths: base = os.path.basename(filepath) with open(filepath, "rb") as file: part = MIMEApplication(file.read(), Name=base) part["Content-Disposition"] = 'attachment; filename="%s"' % base email_.attach(part...
Take a list of filepaths and attach the files to a MIMEMultipart. Args: filepaths (list(str)): A list of filepaths. email_ (email.MIMEMultipart): A MIMEMultipart email_.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L53-L65
null
# -*- coding: utf-8 -*- """Module containing email util functions for the pdfebc program. The SMTP server and port are configured in the config.cnf file, see the config_utils module for more information. .. module:: utils :platform: Unix :synopsis: Email utility functions for pdfebc. .. moduleauthor:: Simon ...
slarse/pdfebc-core
pdfebc_core/email_utils.py
_send_email
python
async def _send_email(email_, config, loop=asyncio.get_event_loop()): smtp_server = get_attribute_from_config(config, EMAIL_SECTION_KEY, SMTP_SERVER_KEY) smtp_port = int(get_attribute_from_config(config, EMAIL_SECTION_KEY, SMTP_PORT_KEY)) user = get_attribute_from_config(config, EMAIL_SECTION_KEY, USER_KEY)...
Send an email. Args: email_ (email.MIMEMultipart): The email to send. config (defaultdict): A defaultdict.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L67-L83
[ "def get_attribute_from_config(config, section, attribute):\n \"\"\"Try to parse an attribute of the config file.\n\n Args:\n config (defaultdict): A defaultdict.\n section (str): The section of the config file to get information from.\n attribute (str): The attribute of the section to fe...
# -*- coding: utf-8 -*- """Module containing email util functions for the pdfebc program. The SMTP server and port are configured in the config.cnf file, see the config_utils module for more information. .. module:: utils :platform: Unix :synopsis: Email utility functions for pdfebc. .. moduleauthor:: Simon ...
slarse/pdfebc-core
pdfebc_core/email_utils.py
send_files_preconf
python
async def send_files_preconf(filepaths, config_path=CONFIG_PATH): config = read_config(config_path) subject = "PDF files from pdfebc" message = "" await send_with_attachments(subject, message, filepaths, config)
Send files using the config.ini settings. Args: filepaths (list(str)): A list of filepaths.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/email_utils.py#L85-L94
[ "def read_config(config_path=CONFIG_PATH):\n \"\"\"Read the config information from the config file.\n\n Args:\n config_path (str): Relative path to the email config file.\n Returns:\n defaultdict: A defaultdict with the config information.\n Raises:\n IOError\n \"\"\"\n if no...
# -*- coding: utf-8 -*- """Module containing email util functions for the pdfebc program. The SMTP server and port are configured in the config.cnf file, see the config_utils module for more information. .. module:: utils :platform: Unix :synopsis: Email utility functions for pdfebc. .. moduleauthor:: Simon ...
slarse/pdfebc-core
pdfebc_core/misc_utils.py
if_callable_call_with_formatted_string
python
def if_callable_call_with_formatted_string(callback, formattable_string, *args): try: formatted_string = formattable_string.format(*args) except IndexError: raise ValueError("Mismatch metween amount of insertion points in the formattable string\n" "and the amount of args...
If the callback is callable, format the string with the args and make a call. Otherwise, do nothing. Args: callback (function): May or may not be callable. formattable_string (str): A string with '{}'s inserted. *args: A variable amount of arguments for the string formatting. Must corre...
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/misc_utils.py#L14-L32
null
# -*- coding: utf-8 -*- """Module containing miscellaneous util functions for pdfebc. The SMTP server and port are configured in the config.cnf file, see the config_utils module for more information. .. module:: utils :platform: Unix :synopsis: Miscellaneous utility functions for pdfebc. .. moduleauthor:: Si...
slarse/pdfebc-core
pdfebc_core/compress.py
_get_pdf_filenames_at
python
def _get_pdf_filenames_at(source_directory): if not os.path.isdir(source_directory): raise ValueError("%s is not a directory!" % source_directory) return [os.path.join(source_directory, filename) for filename in os.listdir(source_directory) if filename.endswith(PDF_EXTENSION)]
Find all PDF files in the specified directory. Args: source_directory (str): The source directory. Returns: list(str): Filepaths to all PDF files in the specified directory. Raises: ValueError
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/compress.py#L36-L52
null
# -*- coding: utf-8 -*- """This module contains the PDF manipulation functions of the pdfebc program. Ghostscript is used to compress PDF files. .. module:: compress :platform: Unix :synopsis: PDF maniupulation functions using Ghostscript. .. moduleauthor:: Simon Larsén <slarse@kth.se> """ import os import sy...
slarse/pdfebc-core
pdfebc_core/compress.py
compress_pdf
python
def compress_pdf(filepath, output_path, ghostscript_binary): if not filepath.endswith(PDF_EXTENSION): raise ValueError("Filename must end with .pdf!\n%s does not." % filepath) try: file_size = os.stat(filepath).st_size if file_size < FILE_SIZE_LOWER_LIMIT: LOGGER.info(NOT_COM...
Compress a single PDF file. Args: filepath (str): Path to the PDF file. output_path (str): Output path. ghostscript_binary (str): Name/alias of the Ghostscript binary. Raises: ValueError FileNotFoundError
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/compress.py#L54-L85
null
# -*- coding: utf-8 -*- """This module contains the PDF manipulation functions of the pdfebc program. Ghostscript is used to compress PDF files. .. module:: compress :platform: Unix :synopsis: PDF maniupulation functions using Ghostscript. .. moduleauthor:: Simon Larsén <slarse@kth.se> """ import os import sy...
slarse/pdfebc-core
pdfebc_core/compress.py
compress_multiple_pdfs
python
def compress_multiple_pdfs(source_directory, output_directory, ghostscript_binary): source_paths = _get_pdf_filenames_at(source_directory) yield len(source_paths) for source_path in source_paths: output = os.path.join(output_directory, os.path.basename(source_path)) compress_pdf(source_path,...
Compress all PDF files in the current directory and place the output in the given output directory. This is a generator function that first yields the amount of files to be compressed, and then yields the output path of each file. Args: source_directory (str): Filepath to the source directory. ...
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/compress.py#L87-L105
[ "def _get_pdf_filenames_at(source_directory):\n \"\"\"Find all PDF files in the specified directory.\n\n Args:\n source_directory (str): The source directory.\n\n Returns:\n list(str): Filepaths to all PDF files in the specified directory.\n\n Raises:\n ValueError\n \"\"\"\n i...
# -*- coding: utf-8 -*- """This module contains the PDF manipulation functions of the pdfebc program. Ghostscript is used to compress PDF files. .. module:: compress :platform: Unix :synopsis: PDF maniupulation functions using Ghostscript. .. moduleauthor:: Simon Larsén <slarse@kth.se> """ import os import sy...
slarse/pdfebc-core
pdfebc_core/config_utils.py
create_config
python
def create_config(sections, section_contents): sections_length, section_contents_length = len(sections), len(section_contents) if sections_length != section_contents_length: raise ValueError("Mismatch between argument lengths.\n" "len(sections) = {}\n" "...
Create a config file from the provided sections and key value pairs. Args: sections (List[str]): A list of section keys. key_value_pairs (Dict[str, str]): A list of of dictionaries. Must be as long as the list of sections. That is to say, if there are two sections, there should be two ...
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L56-L78
null
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
write_config
python
def write_config(config, config_path=CONFIG_PATH): if not os.path.exists(config_path): os.makedirs(os.path.dirname(config_path)) with open(config_path, 'w', encoding='utf-8') as f: config.write(f)
Write the config to the output path. Creates the necessary directories if they aren't there. Args: config (configparser.ConfigParser): A ConfigParser.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L80-L90
null
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
read_config
python
def read_config(config_path=CONFIG_PATH): if not os.path.isfile(config_path): raise IOError("No config file found at %s" % config_path) config_parser = configparser.ConfigParser() config_parser.read(config_path) config = _config_parser_to_defaultdict(config_parser) return config
Read the config information from the config file. Args: config_path (str): Relative path to the email config file. Returns: defaultdict: A defaultdict with the config information. Raises: IOError
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L92-L107
[ "def _config_parser_to_defaultdict(config_parser):\n \"\"\"Convert a ConfigParser to a defaultdict.\n\n Args:\n config_parser (ConfigParser): A ConfigParser.\n \"\"\"\n config = defaultdict(defaultdict)\n for section, section_content in config_parser.items():\n if section != 'DEFAULT':\...
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
check_config
python
def check_config(config): for section, expected_section_keys in SECTION_KEYS.items(): section_content = config.get(section) if not section_content: raise ConfigurationError("Config file badly formed! Section {} is missing." .format(section)) e...
Check that all sections of the config contain the keys that they should. Args: config (defaultdict): A defaultdict. Raises: ConfigurationError
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L109-L124
[ "def _section_is_healthy(section, expected_keys):\n \"\"\"Check that the section contains all keys it should.\n\n Args:\n section (defaultdict): A defaultdict.\n expected_keys (Iterable): A Set of keys that should be contained in the section.\n Returns:\n boolean: True if the section i...
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
run_config_diagnostics
python
def run_config_diagnostics(config_path=CONFIG_PATH): config = read_config(config_path) missing_sections = set() malformed_entries = defaultdict(set) for section, expected_section_keys in SECTION_KEYS.items(): section_content = config.get(section) if not section_content: missi...
Run diagnostics on the configuration file. Args: config_path (str): Path to the configuration file. Returns: str, Set[str], dict(str, Set[str]): The path to the configuration file, a set of missing sections and a dict that maps each section to the entries that have either missing or emp...
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L126-L148
[ "def read_config(config_path=CONFIG_PATH):\n \"\"\"Read the config information from the config file.\n\n Args:\n config_path (str): Relative path to the email config file.\n Returns:\n defaultdict: A defaultdict with the config information.\n Raises:\n IOError\n \"\"\"\n if no...
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
get_attribute_from_config
python
def get_attribute_from_config(config, section, attribute): section = config.get(section) if section: option = section.get(attribute) if option: return option raise ConfigurationError("Config file badly formed!\n" "Failed to get attribute '{}' from sec...
Try to parse an attribute of the config file. Args: config (defaultdict): A defaultdict. section (str): The section of the config file to get information from. attribute (str): The attribute of the section to fetch. Returns: str: The string corresponding to the section and attri...
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L150-L169
null
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
valid_config_exists
python
def valid_config_exists(config_path=CONFIG_PATH): if os.path.isfile(config_path): try: config = read_config(config_path) check_config(config) except (ConfigurationError, IOError): return False else: return False return True
Verify that a valid config file exists. Args: config_path (str): Path to the config file. Returns: boolean: True if there is a valid config file, false if not.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L171-L188
[ "def read_config(config_path=CONFIG_PATH):\n \"\"\"Read the config information from the config file.\n\n Args:\n config_path (str): Relative path to the email config file.\n Returns:\n defaultdict: A defaultdict with the config information.\n Raises:\n IOError\n \"\"\"\n if no...
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
config_to_string
python
def config_to_string(config): output = [] for section, section_content in config.items(): output.append("[{}]".format(section)) for option, option_value in section_content.items(): output.append("{} = {}".format(option, option_value)) return "\n".join(output)
Nice output string for the config, which is a nested defaultdict. Args: config (defaultdict(defaultdict)): The configuration information. Returns: str: A human-readable output string detailing the contents of the config.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L190-L203
null
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
slarse/pdfebc-core
pdfebc_core/config_utils.py
_config_parser_to_defaultdict
python
def _config_parser_to_defaultdict(config_parser): config = defaultdict(defaultdict) for section, section_content in config_parser.items(): if section != 'DEFAULT': for option, option_value in section_content.items(): config[section][option] = option_value return config
Convert a ConfigParser to a defaultdict. Args: config_parser (ConfigParser): A ConfigParser.
train
https://github.com/slarse/pdfebc-core/blob/fc40857bc42365b7434714333e37d7a3487603a0/pdfebc_core/config_utils.py#L205-L216
null
# -*- coding: utf-8 -*- """Module containing util functions relating to the configuration of pdfebc. The SMTP server and port are configured in the config.cnf file. Requires a config file called 'config.cnf' in the user conf directory specified by appdirs. In the case of Arch Linux, this is '$HOME/.config/pdfebc/conf...
eddiejessup/agaro
agaro/measure_utils.py
get_average_measure
python
def get_average_measure(dirname, measure_func, t_steady=None): if t_steady is None: meas, meas_err = measure_func(get_recent_model(dirname)) return meas, meas_err else: ms = [filename_to_model(fname) for fname in get_filenames(dirname)] ms_steady = [m for m in ms if m.t > t_stead...
Calculate a measure of a model in an output directory, averaged over all times when the model is at steady-state. Parameters ---------- dirname: str Output directory measure_func: function Function which takes a :class:`Model` instance as a single argument, and returns the m...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L9-L42
[ "def get_recent_model(dirname):\n \"\"\"Get latest-time model in a directory.\"\"\"\n return filename_to_model(get_recent_filename(dirname))\n", "def get_filenames(dirname):\n \"\"\"Return all model output filenames inside a model output directory,\n sorted by iteration number.\n\n Parameters\n ...
from __future__ import print_function, division from collections import defaultdict import numpy as np from scipy.stats import sem from agaro.output_utils import (get_recent_model, get_filenames, filename_to_model) def measures(dirnames, measure_func, t_steady=None): """Calculate ...
eddiejessup/agaro
agaro/measure_utils.py
measures
python
def measures(dirnames, measure_func, t_steady=None): measures, measure_errs = [], [] for dirname in dirnames: meas, meas_err = get_average_measure(dirname, measure_func, t_steady) measures.append(meas) measure_errs.append(meas_err) return np.array(measures), np.array(measure_errs)
Calculate a measure of a set of model output directories, for a measure function which returns an associated uncertainty. Parameters ---------- dirnames: list[str] Model output directory paths. measure_func: function Function which takes a :class:`Model` instance as a single argumen...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L45-L73
[ "def get_average_measure(dirname, measure_func, t_steady=None):\n \"\"\"\n Calculate a measure of a model in an output directory, averaged over\n all times when the model is at steady-state.\n\n Parameters\n ----------\n dirname: str\n Output directory\n measure_func: function\n F...
from __future__ import print_function, division from collections import defaultdict import numpy as np from scipy.stats import sem from agaro.output_utils import (get_recent_model, get_filenames, filename_to_model) def get_average_measure(dirname, measure_func, t_steady=None): """ ...
eddiejessup/agaro
agaro/measure_utils.py
params
python
def params(dirnames, param_func, t_steady=None): return np.array([param_func(get_recent_model(d)) for d in dirnames])
Calculate a parameter of a set of model output directories, for a measure function which returns an associated uncertainty. Parameters ---------- dirnames: list[str] Model output directory paths. param_func: function Function which takes a :class:`Model` instance as a single argumen...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L76-L93
null
from __future__ import print_function, division from collections import defaultdict import numpy as np from scipy.stats import sem from agaro.output_utils import (get_recent_model, get_filenames, filename_to_model) def get_average_measure(dirname, measure_func, t_steady=None): """ ...
eddiejessup/agaro
agaro/measure_utils.py
t_measures
python
def t_measures(dirname, time_func, measure_func): ts, measures, measure_errs = [], [], [] for fname in get_filenames(dirname): m = filename_to_model(fname) ts.append(time_func(m)) meas, meas_err = measure_func(m) measures.append(meas) measure_errs.append(meas_err) ret...
Calculate a measure over time for a single output directory, and its uncertainty. Parameters ---------- dirname: str Path to a model output directory. time_func: function Function which takes a :class:`Model` instance as a single argument, and returns its time. measure_f...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L96-L127
[ "def get_filenames(dirname):\n \"\"\"Return all model output filenames inside a model output directory,\n sorted by iteration number.\n\n Parameters\n ----------\n dirname: str\n A path to a directory.\n\n Returns\n -------\n filenames: list[str]\n Paths to all output files ins...
from __future__ import print_function, division from collections import defaultdict import numpy as np from scipy.stats import sem from agaro.output_utils import (get_recent_model, get_filenames, filename_to_model) def get_average_measure(dirname, measure_func, t_steady=None): """ ...
eddiejessup/agaro
agaro/measure_utils.py
group_by_key
python
def group_by_key(dirnames, key): groups = defaultdict(lambda: []) for dirname in dirnames: m = get_recent_model(dirname) groups[m.__dict__[key]].append(dirname) return dict(groups)
Group a set of output directories according to a model parameter. Parameters ---------- dirnames: list[str] Output directories key: various A field of a :class:`Model` instance. Returns ------- groups: dict[various: list[str]] For each value of `key` that is found a...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/measure_utils.py#L130-L150
[ "def get_recent_model(dirname):\n \"\"\"Get latest-time model in a directory.\"\"\"\n return filename_to_model(get_recent_filename(dirname))\n" ]
from __future__ import print_function, division from collections import defaultdict import numpy as np from scipy.stats import sem from agaro.output_utils import (get_recent_model, get_filenames, filename_to_model) def get_average_measure(dirname, measure_func, t_steady=None): """ ...
eddiejessup/agaro
agaro/output_utils.py
get_filenames
python
def get_filenames(dirname): filenames = glob.glob('{}/*.pkl'.format(dirname)) return sorted(filenames, key=_f_to_i)
Return all model output filenames inside a model output directory, sorted by iteration number. Parameters ---------- dirname: str A path to a directory. Returns ------- filenames: list[str] Paths to all output files inside `dirname`, sorted in order of increasing it...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L24-L40
null
from os.path import basename, splitext import glob import numpy as np import pickle import os def _f_to_i(f): """Infer a model's iteration number from its output filename. Parameters ---------- f: str A path to a model output file. Returns ------- i: int The iteration num...
eddiejessup/agaro
agaro/output_utils.py
get_output_every
python
def get_output_every(dirname): fnames = get_filenames(dirname) i_s = np.array([_f_to_i(fname) for fname in fnames]) everys = list(set(np.diff(i_s))) if len(everys) > 1: raise TypeError('Multiple values for `output_every` ' 'found, {}.'.format(everys)) return everys[0]
Get how many iterations between outputs have been done in a directory run. If there are multiple values used in a run, raise an exception. Parameters ---------- dirname: str A path to a directory. Returns ------- output_every: int The inferred number of iterations betw...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L59-L87
[ "def get_filenames(dirname):\n \"\"\"Return all model output filenames inside a model output directory,\n sorted by iteration number.\n\n Parameters\n ----------\n dirname: str\n A path to a directory.\n\n Returns\n -------\n filenames: list[str]\n Paths to all output files ins...
from os.path import basename, splitext import glob import numpy as np import pickle import os def _f_to_i(f): """Infer a model's iteration number from its output filename. Parameters ---------- f: str A path to a model output file. Returns ------- i: int The iteration num...
eddiejessup/agaro
agaro/output_utils.py
model_to_file
python
def model_to_file(model, filename): with open(filename, 'wb') as f: pickle.dump(model, f)
Dump a model to a file as a pickle file. Parameters ---------- model: Model Model instance. filename: str A path to the file in which to store the pickle output.
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L107-L118
null
from os.path import basename, splitext import glob import numpy as np import pickle import os def _f_to_i(f): """Infer a model's iteration number from its output filename. Parameters ---------- f: str A path to a model output file. Returns ------- i: int The iteration num...
eddiejessup/agaro
agaro/output_utils.py
sparsify
python
def sparsify(dirname, output_every): fnames = get_filenames(dirname) output_every_old = get_output_every(dirname) if output_every % output_every_old != 0: raise ValueError('Directory with output_every={} cannot be coerced to' 'desired new value.'.format(output_every_old)) ...
Remove files from an output directory at regular interval, so as to make it as if there had been more iterations between outputs. Can be used to reduce the storage size of a directory. If the new number of iterations between outputs is not an integer multiple of the old number, then raise an exception....
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/output_utils.py#L121-L150
[ "def get_filenames(dirname):\n \"\"\"Return all model output filenames inside a model output directory,\n sorted by iteration number.\n\n Parameters\n ----------\n dirname: str\n A path to a directory.\n\n Returns\n -------\n filenames: list[str]\n Paths to all output files ins...
from os.path import basename, splitext import glob import numpy as np import pickle import os def _f_to_i(f): """Infer a model's iteration number from its output filename. Parameters ---------- f: str A path to a model output file. Returns ------- i: int The iteration num...
eddiejessup/agaro
agaro/run_utils.py
run_model
python
def run_model(t_output_every, output_dir=None, m=None, force_resume=True, **iterate_args): r = runner.Runner(output_dir, m, force_resume) print(r) r.iterate(t_output_every=t_output_every, **iterate_args) return r
Convenience function to combine making a Runner object, and running it for some time. Parameters ---------- m: Model Model to run. iterate_args: Arguments to pass to :meth:`Runner.iterate`. Others: see :class:`Runner`. Returns ------- r: Runner runne...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/run_utils.py#L7-L29
[ "def iterate(self,\n n=None, n_upto=None, t=None, t_upto=None,\n output_every=None, t_output_every=None):\n \"\"\"Run the model for a number of iterations, expressed in a number\n of options.\n Only one iteration argument should be passed.\n Only one output arguments should be pass...
from __future__ import print_function, division from functools import partial from ciabatta.parallel import run_func from agaro import runner def resume_runs(dirnames, t_output_every, t_upto, parallel=False): """Resume many models, and run. Parameters ---------- dirnames: list[str] List of o...
eddiejessup/agaro
agaro/run_utils.py
resume_runs
python
def resume_runs(dirnames, t_output_every, t_upto, parallel=False): run_model_partial = partial(run_model, t_output_every, force_resume=True, t_upto=t_upto) run_func(run_model_partial, dirnames, parallel)
Resume many models, and run. Parameters ---------- dirnames: list[str] List of output directory paths from which to resume. output_every: int see :class:`Runner`. t_upto: float Run each model until the time is equal to this parallel: bool Whether or not to run th...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/run_utils.py#L32-L50
null
from __future__ import print_function, division from functools import partial from ciabatta.parallel import run_func from agaro import runner def run_model(t_output_every, output_dir=None, m=None, force_resume=True, **iterate_args): """Convenience function to combine making a Runner object, and ...
eddiejessup/agaro
agaro/run_utils.py
run_kwarg_scan
python
def run_kwarg_scan(ModelClass, model_kwarg_sets, t_output_every, t_upto, force_resume=True, parallel=False): task_runner = _TaskRunner(ModelClass, t_output_every, t_upto, force_resume) run_func(task_runner, model_kwarg_sets, parallel)
Run many models with the same parameters but variable `field`. For each `val` in `vals`, a new model will be made, and run up to a time. The output directory is automatically generated from the model arguments. Parameters ---------- ModelClass: type A class or factory function that returns...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/run_utils.py#L74-L99
null
from __future__ import print_function, division from functools import partial from ciabatta.parallel import run_func from agaro import runner def run_model(t_output_every, output_dir=None, m=None, force_resume=True, **iterate_args): """Convenience function to combine making a Runner object, and ...
eddiejessup/agaro
agaro/run_utils.py
run_field_scan
python
def run_field_scan(ModelClass, model_kwargs, t_output_every, t_upto, field, vals, force_resume=True, parallel=False): model_kwarg_sets = [dict(model_kwargs, field=val) for val in vals] run_kwarg_scan(ModelClass, model_kwarg_sets, t_output_every, t_upto, force_resume, parall...
Run many models with a range of parameter sets. Parameters ---------- ModelClass: callable A class or factory function that returns a model object by calling `ModelClass(model_kwargs)` model_kwargs: dict See `ModelClass` explanation. t_output_every: float see :class:...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/run_utils.py#L102-L128
[ "def run_kwarg_scan(ModelClass, model_kwarg_sets,\n t_output_every, t_upto,\n force_resume=True, parallel=False):\n \"\"\"Run many models with the same parameters but variable `field`.\n\n For each `val` in `vals`, a new model will be made, and run up to a time.\n The ou...
from __future__ import print_function, division from functools import partial from ciabatta.parallel import run_func from agaro import runner def run_model(t_output_every, output_dir=None, m=None, force_resume=True, **iterate_args): """Convenience function to combine making a Runner object, and ...
eddiejessup/agaro
agaro/runner.py
Runner.clear_dir
python
def clear_dir(self): for snapshot in output_utils.get_filenames(self.output_dir): if snapshot.endswith('.pkl'): os.remove(snapshot)
Clear the output directory of all output files.
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L99-L103
[ "def get_filenames(dirname):\n \"\"\"Return all model output filenames inside a model output directory,\n sorted by iteration number.\n\n Parameters\n ----------\n dirname: str\n A path to a directory.\n\n Returns\n -------\n filenames: list[str]\n Paths to all output files ins...
class Runner(object): """Wrapper for loading and iterating model objects, and saving their output. There are several ways to initialise the object. - If no output directory is provided, one will be automatically generated from the model, assuming that is provided. - If no model is provided, an...
eddiejessup/agaro
agaro/runner.py
Runner.is_snapshot_time
python
def is_snapshot_time(self, output_every=None, t_output_every=None): if t_output_every is not None: output_every = int(round(t_output_every // self.model.dt)) return not self.model.i % output_every
Determine whether or not the model's iteration number is one where the runner is expected to make an output snapshot.
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L105-L111
null
class Runner(object): """Wrapper for loading and iterating model objects, and saving their output. There are several ways to initialise the object. - If no output directory is provided, one will be automatically generated from the model, assuming that is provided. - If no model is provided, an...
eddiejessup/agaro
agaro/runner.py
Runner.iterate
python
def iterate(self, n=None, n_upto=None, t=None, t_upto=None, output_every=None, t_output_every=None): if t is not None: t_upto = self.model.t + t if t_upto is not None: n_upto = int(round(t_upto // self.model.dt)) if n is not None: ...
Run the model for a number of iterations, expressed in a number of options. Only one iteration argument should be passed. Only one output arguments should be passed. Parameters ---------- n: int Run the model for `n` iterations from its current point. ...
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L113-L149
[ "def is_snapshot_time(self, output_every=None, t_output_every=None):\n \"\"\"Determine whether or not the model's iteration number is one\n where the runner is expected to make an output snapshot.\n \"\"\"\n if t_output_every is not None:\n output_every = int(round(t_output_every // self.model.dt...
class Runner(object): """Wrapper for loading and iterating model objects, and saving their output. There are several ways to initialise the object. - If no output directory is provided, one will be automatically generated from the model, assuming that is provided. - If no model is provided, an...
eddiejessup/agaro
agaro/runner.py
Runner.make_snapshot
python
def make_snapshot(self): filename = join(self.output_dir, '{:010d}.pkl'.format(self.model.i)) output_utils.model_to_file(self.model, filename)
Output a snapshot of the current model state, as a pickle of the `Model` object in a file inside the output directory, with a name determined by its iteration number.
train
https://github.com/eddiejessup/agaro/blob/b2feb45d6129d749088c70b3e9290af7ca7c7d33/agaro/runner.py#L151-L157
[ "def model_to_file(model, filename):\n \"\"\"Dump a model to a file as a pickle file.\n\n Parameters\n ----------\n model: Model\n Model instance.\n filename: str\n A path to the file in which to store the pickle output.\n \"\"\"\n with open(filename, 'wb') as f:\n pickle.d...
class Runner(object): """Wrapper for loading and iterating model objects, and saving their output. There are several ways to initialise the object. - If no output directory is provided, one will be automatically generated from the model, assuming that is provided. - If no model is provided, an...
f213/rumetr-client
rumetr/roometr.py
Rumetr.complex_exists
python
def complex_exists(self, complex: str) -> bool: try: self.check_complex(complex) except exceptions.RumetrComplexNotFound: return False return True
Shortcut to check if complex exists in our database.
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L39-L48
[ "def check_complex(self, complex: str) -> bool:\n \"\"\"\n Check if a given complex exists in the rumetr database\n \"\"\"\n self.check_developer()\n if complex in self._checked_complexes:\n return True\n\n try:\n self.get('developers/{developer}/complexes/{complex}/'.format(\n ...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def house_exists(self, complex: str, house: str) -> bool: """ Shortcut to check if house exists in our database. """ try: self.check_house(com...
f213/rumetr-client
rumetr/roometr.py
Rumetr.house_exists
python
def house_exists(self, complex: str, house: str) -> bool: try: self.check_house(complex, house) except exceptions.RumetrHouseNotFound: return False return True
Shortcut to check if house exists in our database.
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L50-L59
[ "def check_house(self, complex: str, house: str) -> bool:\n \"\"\"\n Check if given house exists in the rumetr database\n \"\"\"\n self.check_complex(complex)\n if '%s__%s' % (complex, house) in self._checked_houses:\n return True\n\n try:\n self.get('developers/{developer}/complexes...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.appt_exists
python
def appt_exists(self, complex: str, house: str, appt: str) -> bool: try: self.check_appt(complex, house, appt) except exceptions.RumetrApptNotFound: return False return True
Shortcut to check if appt exists in our database.
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L61-L70
[ "def check_appt(self, complex: str, house: str, appt: str) -> bool:\n \"\"\"\n Check if given appartment exists in the rumetr database\n \"\"\"\n self.check_house(complex, house)\n if '%s__%s__%s' % (complex, house, appt) in self._checked_appts:\n return True\n\n try:\n self.get('dev...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.post
python
def post(self, url: str, data: str, expected_status_code=201): r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT) self._check_response(r, expected_status_code) return r.json()
Do a POST request
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L95-L102
[ "def _format_url(self, endpoint):\n \"\"\"\n Append the API host\n \"\"\"\n return (self.api_host + '/%s/' % endpoint).replace('//', '/').replace(':/', '://')\n", "def _check_response(self, response, expected_status_code):\n if response.status_code == 404:\n raise exceptions.Rumetr404Excepti...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.get
python
def get(self, url): r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT) self._check_response(r, 200) return r.json()
Do a GET request
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L113-L120
[ "def _format_url(self, endpoint):\n \"\"\"\n Append the API host\n \"\"\"\n return (self.api_host + '/%s/' % endpoint).replace('//', '/').replace(':/', '://')\n", "def _check_response(self, response, expected_status_code):\n if response.status_code == 404:\n raise exceptions.Rumetr404Excepti...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.check_developer
python
def check_developer(self) -> bool: if self._last_checked_developer == self.developer: return True try: self.get('developers/%s/' % self.developer) except exceptions.Rumetr404Exception: raise exceptions.RumetrDeveloperNotFound('Bad developer id — rumetr server...
Check if a given developer exists in the rumetr database
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L137-L150
[ "def get(self, url):\n \"\"\"\n Do a GET request\n \"\"\"\n r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, 200)\n\n return r.json()\n" ]
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.check_complex
python
def check_complex(self, complex: str) -> bool: self.check_developer() if complex in self._checked_complexes: return True try: self.get('developers/{developer}/complexes/{complex}/'.format( developer=self.developer, complex=complex, ...
Check if a given complex exists in the rumetr database
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L152-L169
[ "def get(self, url):\n \"\"\"\n Do a GET request\n \"\"\"\n r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, 200)\n\n return r.json()\n", "def check_developer(self) -> bool:\n \"\"\"\n Check if a given developer exists in the rumetr d...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.check_house
python
def check_house(self, complex: str, house: str) -> bool: self.check_complex(complex) if '%s__%s' % (complex, house) in self._checked_houses: return True try: self.get('developers/{developer}/complexes/{complex}/houses/{house}/'.format( developer=self.deve...
Check if given house exists in the rumetr database
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L171-L189
[ "def get(self, url):\n \"\"\"\n Do a GET request\n \"\"\"\n r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, 200)\n\n return r.json()\n", "def check_complex(self, complex: str) -> bool:\n \"\"\"\n Check if a given complex exists in th...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.check_appt
python
def check_appt(self, complex: str, house: str, appt: str) -> bool: self.check_house(complex, house) if '%s__%s__%s' % (complex, house, appt) in self._checked_appts: return True try: self.get('developers/{developer}/complexes/{complex}/houses/{house}/appts/{appt}'.format(...
Check if given appartment exists in the rumetr database
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L191-L210
[ "def get(self, url):\n \"\"\"\n Do a GET request\n \"\"\"\n r = requests.get(self._format_url(url), headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, 200)\n\n return r.json()\n", "def check_house(self, complex: str, house: str) -> bool:\n \"\"\"\n Check if given house exists...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.add_complex
python
def add_complex(self, **kwargs): self.check_developer() self.post('developers/%s/complexes/' % self.developer, data=kwargs)
Add a new complex to the rumetr db
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L212-L217
[ "def post(self, url: str, data: str, expected_status_code=201):\n \"\"\"\n Do a POST request\n \"\"\"\n r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, expected_status_code)\n\n return r.json()\n", "def check_developer(self) ->...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.add_house
python
def add_house(self, complex: str, **kwargs): self.check_complex(complex) self.post('developers/{developer}/complexes/{complex}/houses/'.format(developer=self.developer, complex=complex), data=kwargs)
Add a new house to the rumetr db
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L219-L224
[ "def post(self, url: str, data: str, expected_status_code=201):\n \"\"\"\n Do a POST request\n \"\"\"\n r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, expected_status_code)\n\n return r.json()\n", "def check_complex(self, comp...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.add_appt
python
def add_appt(self, complex: str, house: str, price: str, square: str, **kwargs): self.check_house(complex, house) kwargs['price'] = self._format_decimal(price) kwargs['square'] = self._format_decimal(square) self.post('developers/{developer}/complexes/{complex}/houses/{house}/appts/'.f...
Add a new appartment to the rumetr db
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L226-L239
[ "def post(self, url: str, data: str, expected_status_code=201):\n \"\"\"\n Do a POST request\n \"\"\"\n r = requests.post(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, expected_status_code)\n\n return r.json()\n", "def _format_decimal(decimal:...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.update_house
python
def update_house(self, complex: str, id: str, **kwargs): self.check_house(complex, id) self.put('developers/{developer}/complexes/{complex}/houses/{id}'.format( developer=self.developer, complex=complex, id=id, ), data=kwargs)
Update the existing house
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L241-L250
[ "def put(self, url: str, data: str, expected_status_code=200):\n \"\"\"\n Do a PUT request\n \"\"\"\n r = requests.put(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, expected_status_code)\n\n return r.json()\n", "def check_house(self, complex: ...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/roometr.py
Rumetr.update_appt
python
def update_appt(self, complex: str, house: str, price: str, square: str, id: str, **kwargs): self.check_house(complex, house) kwargs['price'] = self._format_decimal(price) kwargs['square'] = self._format_decimal(square) self.put('developers/{developer}/complexes/{complex}/houses/{house...
Update existing appartment
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/roometr.py#L252-L267
[ "def put(self, url: str, data: str, expected_status_code=200):\n \"\"\"\n Do a PUT request\n \"\"\"\n r = requests.put(self._format_url(url), json=data, headers=self.headers, timeout=TIMEOUT)\n self._check_response(r, expected_status_code)\n\n return r.json()\n", "def _format_decimal(decimal: st...
class Rumetr: """ The client for the rumetr.com internal database. Use it to update our data with your scraper. """ def complex_exists(self, complex: str) -> bool: """ Shortcut to check if complex exists in our database. """ try: self.check_complex(complex) ...
f213/rumetr-client
rumetr/scrapy/pipeline.py
UploadPipeline.c
python
def c(self): if self._client is None: self._parse_settings() self._client = Rumetr(**self.settings) return self._client
Caching client for not repeapting checks
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/scrapy/pipeline.py#L81-L86
[ "def _parse_settings(self):\n \"\"\"Gets upload options from the scrapy settings\"\"\"\n if hasattr(self, 'settings'): # parse setting only one time\n return\n\n self.settings = {\n 'auth_key': self._check_required_setting('RUMETR_TOKEN'),\n 'developer': self._check_required_setting('...
class UploadPipeline(object): """Scrapy pipeline to upload single appartment data to rumetr.com database""" _client = None def process_item(self, item, spider): self.spider = spider self.item = item self.add_complex_if_required() self.add_house_if_required() self.up...
f213/rumetr-client
rumetr/scrapy/pipeline.py
UploadPipeline._parse_settings
python
def _parse_settings(self): if hasattr(self, 'settings'): # parse setting only one time return self.settings = { 'auth_key': self._check_required_setting('RUMETR_TOKEN'), 'developer': self._check_required_setting('RUMETR_DEVELOPER'), } self.settings.u...
Gets upload options from the scrapy settings
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/scrapy/pipeline.py#L88-L97
[ "def _check_required_setting(self, setting) -> str:\n\n if setting not in self.spider.settings.keys() or not len(self.spider.settings[setting]):\n raise TypeError('Please set up %s in your scrapy settings' % setting)\n return self.spider.settings[setting]\n", "def _non_required_settings(self, *args) ...
class UploadPipeline(object): """Scrapy pipeline to upload single appartment data to rumetr.com database""" _client = None def process_item(self, item, spider): self.spider = spider self.item = item self.add_complex_if_required() self.add_house_if_required() self.up...
f213/rumetr-client
rumetr/scrapy/pipeline.py
UploadPipeline._parse_deadline
python
def _parse_deadline(deadline): if '-' in deadline and len(deadline) == 10: return deadline if '.' in deadline and len(deadline) == 10: # russian format dd.mm.yyyy to yyyy-mm-dd dmy = deadline.split('.') if len(dmy) == 3 and all(v is not None for v in dmy): ...
Translate deadline date from human-acceptable format to the machine-acceptable
train
https://github.com/f213/rumetr-client/blob/5180152bcb2eed8246b88035db7c0bb1fe603166/rumetr/scrapy/pipeline.py#L109-L119
null
class UploadPipeline(object): """Scrapy pipeline to upload single appartment data to rumetr.com database""" _client = None def process_item(self, item, spider): self.spider = spider self.item = item self.add_complex_if_required() self.add_house_if_required() self.up...
monkeython/scriba
scriba/schemes/file.py
write
python
def write(url, content, **args): with FileResource(url, **args) as resource: resource.write(content)
Put the object/collection into a file URL.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/file.py#L64-L67
null
"""Handle file URL""" import mimetypes import os try: url2pathname = __import__('urllib.request').url2pathname except ImportError: url2pathname = __import__('urllib').url2pathname import multipla content_encodings = multipla.power_up('scriba.content_encodings') content_types = multipla.power_up('scriba.cont...
monkeython/scriba
scriba/schemes/scriba_pop.py
read
python
def read(url, **args): all_ = args.pop('all', False) password = args.pop('password', '') if not password: raise ValueError('password') try: username, __ = url.username.split(';') except ValueError: username = url.username if not username: username = os.environ.get...
Get the object from a ftp URL.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_pop.py#L19-L55
null
"""Handle mailto URL""" import email import os import poplib import socket import multipla content_encodings = multipla.power_up('scriba.content_encodings') content_types = multipla.power_up('scriba.content_types') email_mimes = multipla.power_up('scriba.email_mimes') class BadPOP3Response(Exception): pass #...
monkeython/scriba
scriba/content_types/scriba_x_tar.py
parse
python
def parse(binary, **params): binary = io.BytesIO(binary) collection = list() with tarfile.TarFile(fileobj=binary, mode='r') as tar: for tar_info in tar.getmembers(): content_type, encoding = mimetypes.guess_type(tar_info.name) content = tar.extractfile(tar_info) c...
Turns a TAR file into a frozen sample.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_x_tar.py#L16-L27
null
""" Handle the serialization of a collection of python objects from/to a tar file. """ import calendar import datetime import io import mimetypes import tarfile import multipla content_types = multipla.power_up('scriba.content_types') content_encodings = multipla.power_up('scriba.content_encodings') def format(col...
monkeython/scriba
scriba/content_types/scriba_x_tar.py
format
python
def format(collection, **params): binary = io.BytesIO() with tarfile.TarFile(fileobj=binary, mode='w') as tar: mode = params.get('mode', 0o640) now = calendar.timegm(datetime.datetime.utcnow().timetuple()) for filename, content in collection: content_type, encoding = mimetype...
Truns a frozen sample into a TAR file.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_x_tar.py#L30-L47
null
""" Handle the serialization of a collection of python objects from/to a tar file. """ import calendar import datetime import io import mimetypes import tarfile import multipla content_types = multipla.power_up('scriba.content_types') content_encodings = multipla.power_up('scriba.content_encodings') def parse(binar...
monkeython/scriba
scriba/content_types/scriba_zip.py
parse
python
def parse(binary, **params): binary = io.BytesIO(binary) collection = list() with zipfile.ZipFile(binary, 'r') as zip_: for zip_info in zip_.infolist(): content_type, encoding = mimetypes.guess_type(zip_info.filename) content = zip_.read(zip_info) content = conten...
Turns a ZIP file into a frozen sample.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_zip.py#L13-L24
null
"""Handle serialization of a python object from/to a ZIP file.""" import datetime import io import mimetypes import zipfile import multipla content_types = multipla.power_up('scriba.content_types') content_encodings = multipla.power_up('scriba.content_encodings') def format(collection, **params): """Truns a py...
monkeython/scriba
scriba/content_types/scriba_zip.py
format
python
def format(collection, **params): binary = io.BytesIO() with zipfile.ZipFile(binary, 'w') as zip_: now = datetime.datetime.utcnow().timetuple() for filename, content in collection: content_type, encoding = mimetypes.guess_type(filename) content = content_types.get(content...
Truns a python object into a ZIP file.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_zip.py#L27-L40
null
"""Handle serialization of a python object from/to a ZIP file.""" import datetime import io import mimetypes import zipfile import multipla content_types = multipla.power_up('scriba.content_types') content_encodings = multipla.power_up('scriba.content_encodings') def parse(binary, **params): """Turns a ZIP file...
monkeython/scriba
scriba/content_types/scriba_json.py
parse
python
def parse(binary, **params): encoding = params.get('charset', 'UTF-8') return json.loads(binary, encoding=encoding)
Turns a JSON structure into a python object.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_json.py#L6-L9
null
"""Handle JSON formatting/parsing.""" import json def format(item, **params): """Truns a python object into a JSON structure.""" encoding = params.get('charset', 'UTF-8') return json.dumps(item, encoding=encoding)
monkeython/scriba
scriba/content_types/scriba_json.py
format
python
def format(item, **params): encoding = params.get('charset', 'UTF-8') return json.dumps(item, encoding=encoding)
Truns a python object into a JSON structure.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_types/scriba_json.py#L12-L15
null
"""Handle JSON formatting/parsing.""" import json def parse(binary, **params): """Turns a JSON structure into a python object.""" encoding = params.get('charset', 'UTF-8') return json.loads(binary, encoding=encoding)
monkeython/scriba
scriba/schemes/scriba_mailto.py
write
python
def write(url, content, **args): relay = urlparse.urlparse(args.pop('relay', 'lmtp://localhot')) try: smtplib_SMTPS = functools.partial(smtplib.SMTP_SSL, keyfile=args.pop('keyfile', None), certfile=args.pop('certfile', N...
Put an object into a ftp URL.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_mailto.py#L26-L70
null
"""Handle mailto URL""" from email.mime import application from email.mime import text import functools import mimetypes import os import smtplib import urllib try: import urlparse except ImportError: # pragma: no cover import urllib.parse as urlparse import socket import multipla content_encodings = mult...
monkeython/scriba
scriba/schemes/scriba_ftps.py
write
python
def write(url, content, **args): with FTPSResource(url, **args) as resource: resource.write(content)
Put an object into a ftps URL.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_ftps.py#L27-L30
null
import ftplib import scriba.schemes.scriba_ftp as ftp_scheme class FTPSResource(ftp_scheme.FTPResource): def __init__(self, url, **params): self.url = url self.params = params keyfile = self.params.pop('keyfile', None) certfile = self.params.pop('certfile', None) self.cli...
monkeython/scriba
scriba/schemes/scriba_ftp.py
write
python
def write(url, content, **args): with FTPResource(url, **args) as resource: resource.write(content)
Put an object into a ftp URL.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_ftp.py#L84-L87
null
"""Handle ftp URL""" import ftplib import io import netrc import socket import multipla import scriba.schemes.file as file_scheme content_encodings = multipla.power_up('scriba.content_encodings') content_types = multipla.power_up('scriba.content_types') _netrc = dict() try: _locked_netrc = __import__('thread')...
monkeython/scriba
scriba/schemes/scriba_http.py
write
python
def write(url, content, **args): with HTTPResource(url, **args) as resource: resource.write(content)
Put the object/collection into a file URL.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_http.py#L90-L93
null
"""Handle http URL""" import httplib import mimetypes import socket import multipla content_encodings = multipla.power_up('scriba.content_encodings') content_types = multipla.power_up('scriba.content_types') class HTTPBadResponse(httplib.HTTPException): pass class HTTPResource(object): def __init__(self,...
monkeython/scriba
scriba/content_encodings/gzip.py
decode
python
def decode(binary): encoded = io.BytesIO(binary) with gzip.GzipFile(mode='rb', fileobj=encoded) as file_: decoded = file_.read() return decoded
Decode (gunzip) binary data.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_encodings/gzip.py#L9-L14
null
"""Handle gzip encoding/decoding.""" import gzip import io LEVEL = 9 def encode(binary): """Encode (gzip) binary data.""" encoded = io.BytesIO() gzip_file = dict(mode='wb', fileobj=encoded, compresslevel=LEVEL) with gzip.GzipFile(**gzip_file) as file_: file_.write(binary) encoded.seek(0...
monkeython/scriba
scriba/content_encodings/gzip.py
encode
python
def encode(binary): encoded = io.BytesIO() gzip_file = dict(mode='wb', fileobj=encoded, compresslevel=LEVEL) with gzip.GzipFile(**gzip_file) as file_: file_.write(binary) encoded.seek(0) return encoded.read()
Encode (gzip) binary data.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/content_encodings/gzip.py#L17-L24
null
"""Handle gzip encoding/decoding.""" import gzip import io LEVEL = 9 def decode(binary): """Decode (gunzip) binary data.""" encoded = io.BytesIO(binary) with gzip.GzipFile(mode='rb', fileobj=encoded) as file_: decoded = file_.read() return decoded
monkeython/scriba
scriba/schemes/data.py
read
python
def read(url, **args): info, data = url.path.split(',') info = data_re.search(info).groupdict() mediatype = info.setdefault('mediatype', 'text/plain;charset=US-ASCII') if ';' in mediatype: mimetype, params = mediatype.split(';', 1) params = [p.split('=') for p in params.split(';')] ...
Loads an object from a data URI.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/data.py#L23-L35
null
"""Handle the data URI""" import base64 import re import urllib import multipla content_types = multipla.power_up('scriba.content_types') data_re = """ (?P<mediatype> (?P<maintype>[^/]+)/(?P<subtype>[^;]+) (?P<params>;[^=]+=[^;,]+)* )? (?P<base64>;base64)? , (?P<data>.*) """...
monkeython/scriba
scriba/schemes/data.py
write
python
def write(url, object_, **args): default_content_type = ('text/plain', {'charset': 'US-ASCII'}) content_encoding = args.get('content_encoding', 'base64') content_type, params = args.get('content_type', default_content_type) data = content_types.get(content_type).format(object_, **params) args['data'...
Writes an object to a data URI.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/data.py#L38-L51
null
"""Handle the data URI""" import base64 import re import urllib import multipla content_types = multipla.power_up('scriba.content_types') data_re = """ (?P<mediatype> (?P<maintype>[^/]+)/(?P<subtype>[^;]+) (?P<params>;[^=]+=[^;,]+)* )? (?P<base64>;base64)? , (?P<data>.*) """...
monkeython/scriba
scriba/schemes/scriba_https.py
write
python
def write(url, content, **args): with HTTPSResource(url, **args) as resource: resource.write(content)
Put the object/collection into a file URL.
train
https://github.com/monkeython/scriba/blob/fb8e7636ed07c3d035433fdd153599ac8b24dfc4/scriba/schemes/scriba_https.py#L32-L35
null
"""Handle http URL""" import httplib import socket import scriba.scheme.scriba_http as http_scheme import multipla content_encodings = multipla.power_up('scriba.content_encodings') content_types = multipla.power_up('scriba.content_types') class HTTPSResource(http_scheme.HTTPResource): def __enter__(self): ...
EdwinvO/pyutillib
pyutillib/date_utils.py
previous_weekday
python
def previous_weekday(date): ''' Returns the last weekday before date Args: date (datetime or datetime.date) Returns: (datetime or datetime.date) Raises: - ''' weekday = date.weekday() if weekday == 0: n_days = 3 elif weekday == 6: n_days = 2 ...
Returns the last weekday before date Args: date (datetime or datetime.date) Returns: (datetime or datetime.date) Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L172-L190
null
''' pyutillib/date_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This p...
EdwinvO/pyutillib
pyutillib/date_utils.py
next_weekday
python
def next_weekday(date): ''' Return the first weekday after date Args: date (datetime or datetime.date) Returns: (datetime or datetime.date) Raises: - ''' n_days = 7 - date.weekday() if n_days > 3: n_days = 1 return date + datetime.timedelta(days=n_day...
Return the first weekday after date Args: date (datetime or datetime.date) Returns: (datetime or datetime.date) Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L193-L207
null
''' pyutillib/date_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This p...
EdwinvO/pyutillib
pyutillib/date_utils.py
last_year
python
def last_year(date_): ''' Returns the same date 1 year ago. Args: date (datetime or datetime.date) Returns: (datetime or datetime.date) Raises: - ''' day = 28 if date_.day == 29 and date_.month == 2 else date_.day return datetime.date(date_.year-1, date_.month, d...
Returns the same date 1 year ago. Args: date (datetime or datetime.date) Returns: (datetime or datetime.date) Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L210-L222
null
''' pyutillib/date_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This p...
EdwinvO/pyutillib
pyutillib/date_utils.py
timestr2time
python
def timestr2time(time_str): ''' Turns a string into a datetime.time object. This will only work if the format can be "guessed", so the string must have one of the formats from VALID_TIME_FORMATS_TEXT. Args: time_str (str) a string that represents a date Returns: datetime.time o...
Turns a string into a datetime.time object. This will only work if the format can be "guessed", so the string must have one of the formats from VALID_TIME_FORMATS_TEXT. Args: time_str (str) a string that represents a date Returns: datetime.time object Raises: ValueError if ...
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L317-L353
null
''' pyutillib/date_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This p...
EdwinvO/pyutillib
pyutillib/date_utils.py
time2timestr
python
def time2timestr(time, fmt='hhmmss'): ''' Turns a datetime.time object into a string. The string must have one of the formats from VALID_TIME_FORMATS_TEXT to make it compatible with timestr2time. Args: time (datetime.time) the time to be translated fmt (str) a format string. Re...
Turns a datetime.time object into a string. The string must have one of the formats from VALID_TIME_FORMATS_TEXT to make it compatible with timestr2time. Args: time (datetime.time) the time to be translated fmt (str) a format string. Returns: (str) that represents a time. R...
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L355-L406
null
''' pyutillib/date_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This p...
EdwinvO/pyutillib
pyutillib/date_utils.py
DateList.index
python
def index(self, date): ''' Overloads the default list.index, because of special behaviour if the date is not in the list: - If <date> is not in the list, the index of the latest date before <date> is returned. - If <date> is earlier than the earliest date ...
Overloads the default list.index, because of special behaviour if the date is not in the list: - If <date> is not in the list, the index of the latest date before <date> is returned. - If <date> is earlier than the earliest date in the list, the return va...
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L243-L264
null
class DateList(list): ''' Provides a list of dates with methods to extract information. The dates list MUST be sorted for the methods of this class to work. ''' ONE_DAY = datetime.timedelta(days=1) def __init__(self, dates, sort=True): ''' Constructor stores the list of dates. ...
EdwinvO/pyutillib
pyutillib/date_utils.py
DateList.delta
python
def delta(self, fromdate, todate): ''' Return the number of dates in the list between <fromdate> and <todate>. ''' #CONSIDER: raise an exception if a date is not in self return self.index(todate) - self.index(fromdate)
Return the number of dates in the list between <fromdate> and <todate>.
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L273-L279
[ "def index(self, date):\n '''\n Overloads the default list.index, because of special behaviour if the\n date is not in the list:\n - If <date> is not in the list, the index of the latest date before\n <date> is returned.\n - If <date> is earlier than the earliest date in the list, ...
class DateList(list): ''' Provides a list of dates with methods to extract information. The dates list MUST be sorted for the methods of this class to work. ''' ONE_DAY = datetime.timedelta(days=1) def __init__(self, dates, sort=True): ''' Constructor stores the list of dates. ...
EdwinvO/pyutillib
pyutillib/date_utils.py
DateList.offset
python
def offset(self, date, n_days): ''' Return the date n_days after (or before if n_days < 0) <date> note: not calender days, but self days! ''' #CONSIDER: raise an exception if a date is not in self index = self.index(date) + n_days if index < 0: index = 0 ...
Return the date n_days after (or before if n_days < 0) <date> note: not calender days, but self days!
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L281-L292
[ "def index(self, date):\n '''\n Overloads the default list.index, because of special behaviour if the\n date is not in the list:\n - If <date> is not in the list, the index of the latest date before\n <date> is returned.\n - If <date> is earlier than the earliest date in the list, ...
class DateList(list): ''' Provides a list of dates with methods to extract information. The dates list MUST be sorted for the methods of this class to work. ''' ONE_DAY = datetime.timedelta(days=1) def __init__(self, dates, sort=True): ''' Constructor stores the list of dates. ...
EdwinvO/pyutillib
pyutillib/date_utils.py
DateList.subset
python
def subset(self, fromdate, todate): ''' Return a list of dates from the list between <fromdate> and <todate> (inclusive) ''' #CONSIDER: raise an exception if a date is not in self i_from = self.index(fromdate) if fromdate != self[i_from]: # don't go back befor...
Return a list of dates from the list between <fromdate> and <todate> (inclusive)
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/date_utils.py#L294-L305
[ "def index(self, date):\n '''\n Overloads the default list.index, because of special behaviour if the\n date is not in the list:\n - If <date> is not in the list, the index of the latest date before\n <date> is returned.\n - If <date> is earlier than the earliest date in the list, ...
class DateList(list): ''' Provides a list of dates with methods to extract information. The dates list MUST be sorted for the methods of this class to work. ''' ONE_DAY = datetime.timedelta(days=1) def __init__(self, dates, sort=True): ''' Constructor stores the list of dates. ...
EdwinvO/pyutillib
pyutillib/math_utils.py
div
python
def div(numerator, denominator): ''' Returns numerator / denominator, but instead of a ZeroDivisionError: 0 / 0 = 0. x / 0 = float('inf') This is not mathematically correct, but often practically OK. Args: numerator (float or int) denominator (float or int) Returns: ...
Returns numerator / denominator, but instead of a ZeroDivisionError: 0 / 0 = 0. x / 0 = float('inf') This is not mathematically correct, but often practically OK. Args: numerator (float or int) denominator (float or int) Returns: (float) Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/math_utils.py#L27-L51
null
''' pyutillib/math_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This p...
EdwinvO/pyutillib
pyutillib/math_utils.py
eval_conditions
python
def eval_conditions(conditions=None, data={}): ''' Evaluates conditions and returns Boolean value. Args: conditions (tuple) for the format of the tuple, see below data (dict) the keys of which can be used in conditions Returns: (boolea) Raises: ValueError if an inval...
Evaluates conditions and returns Boolean value. Args: conditions (tuple) for the format of the tuple, see below data (dict) the keys of which can be used in conditions Returns: (boolea) Raises: ValueError if an invalid operator value is specified TypeError if: ...
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/math_utils.py#L54-L114
[ "def str2tuple(str_in):\n '''\n Extracts a tuple from a string.\n\n Args:\n str_in (string) that contains python tuple\n Returns:\n (dict) or None if no valid tuple was found\n Raises:\n -\n '''\n tuple_out = safe_eval(str_in)\n if not isinstance(tuple_out, tuple):\n ...
''' pyutillib/math_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This p...
EdwinvO/pyutillib
pyutillib/string_utils.py
random_string
python
def random_string(length=8, charset=None): ''' Generates a string with random characters. If no charset is specified, only letters and digits are used. Args: length (int) length of the returned string charset (string) list of characters to choose from Returns: (str) with ran...
Generates a string with random characters. If no charset is specified, only letters and digits are used. Args: length (int) length of the returned string charset (string) list of characters to choose from Returns: (str) with random characters from charset Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L28-L45
null
''' pyutillib/string_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This...
EdwinvO/pyutillib
pyutillib/string_utils.py
str2dict
python
def str2dict(str_in): ''' Extracts a dict from a string. Args: str_in (string) that contains python dict Returns: (dict) or None if no valid dict was found Raises: - ''' dict_out = safe_eval(str_in) if not isinstance(dict_out, dict): dict_out = None r...
Extracts a dict from a string. Args: str_in (string) that contains python dict Returns: (dict) or None if no valid dict was found Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L65-L79
[ "def safe_eval(str_in):\n '''\n Extracts a python object from a string.\n\n Args:\n str_in (string) that contains python variable\n Returns:\n (object) of standard python type or None of no valid object was found.\n Raises:\n -\n '''\n try:\n return ast.literal_eval(...
''' pyutillib/string_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This...
EdwinvO/pyutillib
pyutillib/string_utils.py
str2tuple
python
def str2tuple(str_in): ''' Extracts a tuple from a string. Args: str_in (string) that contains python tuple Returns: (dict) or None if no valid tuple was found Raises: - ''' tuple_out = safe_eval(str_in) if not isinstance(tuple_out, tuple): tuple_out = No...
Extracts a tuple from a string. Args: str_in (string) that contains python tuple Returns: (dict) or None if no valid tuple was found Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L82-L96
[ "def safe_eval(str_in):\n '''\n Extracts a python object from a string.\n\n Args:\n str_in (string) that contains python variable\n Returns:\n (object) of standard python type or None of no valid object was found.\n Raises:\n -\n '''\n try:\n return ast.literal_eval(...
''' pyutillib/string_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This...
EdwinvO/pyutillib
pyutillib/string_utils.py
str2dict_keys
python
def str2dict_keys(str_in): ''' Extracts the keys from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with keys or None if no valid dict was found Raises: - ''' tmp_dict = str2dict(st...
Extracts the keys from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with keys or None if no valid dict was found Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L100-L115
[ "def str2dict(str_in):\n '''\n Extracts a dict from a string.\n\n Args:\n str_in (string) that contains python dict\n Returns:\n (dict) or None if no valid dict was found\n Raises:\n -\n '''\n dict_out = safe_eval(str_in)\n if not isinstance(dict_out, dict):\n dic...
''' pyutillib/string_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This...
EdwinvO/pyutillib
pyutillib/string_utils.py
str2dict_values
python
def str2dict_values(str_in): ''' Extracts the values from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with values or None if no valid dict was found Raises: - ''' tmp_dict = str2d...
Extracts the values from a string that represents a dict and returns them sorted by key. Args: str_in (string) that contains python dict Returns: (list) with values or None if no valid dict was found Raises: -
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L119-L134
[ "def str2dict(str_in):\n '''\n Extracts a dict from a string.\n\n Args:\n str_in (string) that contains python dict\n Returns:\n (dict) or None if no valid dict was found\n Raises:\n -\n '''\n dict_out = safe_eval(str_in)\n if not isinstance(dict_out, dict):\n dic...
''' pyutillib/string_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This...
EdwinvO/pyutillib
pyutillib/string_utils.py
decstr2int
python
def decstr2int(dec_str, decimals): ''' Returns an integer that has the value of the decimal string: dec_str*10^decimals Arguments: dec_str (string) that represents a decimal number decimals (int): number of decimals for creating the integer output Returns: (int) Rais...
Returns an integer that has the value of the decimal string: dec_str*10^decimals Arguments: dec_str (string) that represents a decimal number decimals (int): number of decimals for creating the integer output Returns: (int) Raises: ValueError if dec_string is not a v...
train
https://github.com/EdwinvO/pyutillib/blob/6d773c31d1f27cc5256d47feb8afb5c3ae5f0db5/pyutillib/string_utils.py#L137-L176
null
''' pyutillib/string_utils.py Copyright (C) 2013 Edwin van Opstal This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This...
awacha/credolib
credolib/initialization.py
init_dirs
python
def init_dirs(rootdir_or_loader, outputpath, saveto_dir='data', auximages_dir='auximages', prefix='crd'): ip = get_ipython() if isinstance(rootdir_or_loader, str): print("Initializing loaders for SAXSCtrl and CCT.", flush=True) ip.user_ns['_loaders'] = [ credo_cct.Loade...
Initialize the directiories. Inputs: rootdir_or_loader: depends on the type: str: the root directory of the SAXSCtrl/CCT software, i.e. where the subfolders ``eval2d``, ``param``, ``images``, ``mask`` etc. reside. sastool.classes2.Load...
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/initialization.py#L17-L82
[ "def set_length_units(units):\n \"\"\"Set the length units: either 'nm' or 'A'.\n \"\"\"\n libconfig.LENGTH_UNIT = units\n print(\"Length units have been set to:\", units,flush=True)\n" ]
__all__=['set_length_units','init_dirs'] import os import sastool.libconfig as libconfig from IPython.core.getipython import get_ipython from sastool.classes2 import Loader from sastool.io import credo_saxsctrl, credo_cct def set_length_units(units): """Set the length units: either 'nm' or 'A'. """ libco...
awacha/credolib
credolib/qualitycontrol.py
assess_fitting_results
python
def assess_fitting_results(basename, cormap_alpha=0.01): plt.figure(figsize=(12, 4)) plt.subplot2grid((1, 4), (0, 0), colspan=2) fir = np.loadtxt(basename + '.fir', skiprows=1) # q, Iexp, Errexp, Ifitted # do a cormap test to compare the raw data and the model. pvalf, Cf, cormapf = cormaptest(fir[:...
Assess the results of a fit based on the .fit and .fir files created by various programs from the ATSAS suite.
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/qualitycontrol.py#L184-L236
[ "def calc_chi2(y, dy, fittedy):\n return (((y - fittedy) / dy) ** 2).sum() / (len(y) - 1)\n", "def calc_R2(y, fittedy):\n SStot = ((y - np.mean(y)) ** 2).sum()\n SSres = ((fittedy - y) ** 2).sum()\n return 1 - SSres / SStot\n" ]
__all__ = ['assess_flux_stability', 'sum_measurement_times', 'assess_sample_stability', 'assess_instrumental_background', 'assess_transmission', 'assess_gc_fit', 'assess_fitting_results'] import ipy_table import matplotlib.pyplot as plt import numpy as np from IPython.core.getipython import get_ipython from...
awacha/credolib
credolib/persistence.py
storedata
python
def storedata(filename=None): if filename is None: filename = 'credolib_state.pickle' ns = get_ipython().user_ns with open(filename, 'wb') as f: d = {} for var in ['_headers', '_loaders', '_data1d', '_data2d', '_data1dunited', 'allsamplenames', '_headers_sample', ...
Store the state of the current credolib workspace in a pickle file.
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/persistence.py#L8-L24
null
__all__ = ['restoredata', 'storedata'] import pickle import warnings from IPython.core.getipython import get_ipython def restoredata(filename=None): """Restore the state of the credolib workspace from a pickle file.""" if filename is None: filename = 'credolib_state.pickle' ns = get_ipython().us...
awacha/credolib
credolib/persistence.py
restoredata
python
def restoredata(filename=None): if filename is None: filename = 'credolib_state.pickle' ns = get_ipython().user_ns with open(filename, 'rb') as f: d = pickle.load(f) for k in d.keys(): ns[k] = d[k]
Restore the state of the credolib workspace from a pickle file.
train
https://github.com/awacha/credolib/blob/11c0be3eea7257d3d6e13697d3e76ce538f2f1b2/credolib/persistence.py#L27-L35
null
__all__ = ['restoredata', 'storedata'] import pickle import warnings from IPython.core.getipython import get_ipython def storedata(filename=None): """Store the state of the current credolib workspace in a pickle file.""" if filename is None: filename = 'credolib_state.pickle' ns = get_ipython().u...