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
kennethreitz/records
records.py
RecordCollection.dataset
python
def dataset(self): # Create a new Tablib Dataset. data = tablib.Dataset() # If the RecordCollection is empty, just return the empty set # Check number of rows by typecasting to list if len(list(self)) == 0: return data # Set the column names as headers on Ta...
A Tablib Dataset representation of the RecordCollection.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L170-L188
[ "def _reduce_datetimes(row):\n \"\"\"Receives a row, converts datetimes to strings.\"\"\"\n\n row = list(row)\n\n for i in range(len(row)):\n if hasattr(row[i], 'isoformat'):\n row[i] = row[i].isoformat()\n return tuple(row)\n" ]
class RecordCollection(object): """A set of excellent Records from a query.""" def __init__(self, rows): self._rows = rows self._all_rows = [] self.pending = True def __repr__(self): return '<RecordCollection size={} pending={}>'.format(len(self), self.pending) def __it...
kennethreitz/records
records.py
RecordCollection.all
python
def all(self, as_dict=False, as_ordereddict=False): # By calling list it calls the __iter__ method rows = list(self) if as_dict: return [r.as_dict() for r in rows] elif as_ordereddict: return [r.as_dict(ordered=True) for r in rows] return rows
Returns a list of all rows for the RecordCollection. If they haven't been fetched yet, consume the iterator and cache the results.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L190-L202
null
class RecordCollection(object): """A set of excellent Records from a query.""" def __init__(self, rows): self._rows = rows self._all_rows = [] self.pending = True def __repr__(self): return '<RecordCollection size={} pending={}>'.format(len(self), self.pending) def __it...
kennethreitz/records
records.py
RecordCollection.first
python
def first(self, default=None, as_dict=False, as_ordereddict=False): # Try to get a record, or return/raise default. try: record = self[0] except IndexError: if isexception(default): raise default return default # Cast and return. ...
Returns a single record for the RecordCollection, or `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L207-L226
[ "def isexception(obj):\n \"\"\"Given an object, return a boolean indicating whether it is an instance\n or subclass of :py:class:`Exception`.\n \"\"\"\n if isinstance(obj, Exception):\n return True\n if isclass(obj) and issubclass(obj, Exception):\n return True\n return False\n" ]
class RecordCollection(object): """A set of excellent Records from a query.""" def __init__(self, rows): self._rows = rows self._all_rows = [] self.pending = True def __repr__(self): return '<RecordCollection size={} pending={}>'.format(len(self), self.pending) def __it...
kennethreitz/records
records.py
RecordCollection.one
python
def one(self, default=None, as_dict=False, as_ordereddict=False): # Ensure that we don't have more than one row. try: self[1] except IndexError: return self.first(default=default, as_dict=as_dict, as_ordereddict=as_ordereddict) else: raise ValueError(...
Returns a single record for the RecordCollection, ensuring that it is the only record, or returns `default`. If `default` is an instance or subclass of Exception, then raise it instead of returning it.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L228-L241
[ "def first(self, default=None, as_dict=False, as_ordereddict=False):\n \"\"\"Returns a single record for the RecordCollection, or `default`. If\n `default` is an instance or subclass of Exception, then raise it\n instead of returning it.\"\"\"\n\n # Try to get a record, or return/raise default.\n try...
class RecordCollection(object): """A set of excellent Records from a query.""" def __init__(self, rows): self._rows = rows self._all_rows = [] self.pending = True def __repr__(self): return '<RecordCollection size={} pending={}>'.format(len(self), self.pending) def __it...
kennethreitz/records
records.py
Database.get_connection
python
def get_connection(self): if not self.open: raise exc.ResourceClosedError('Database closed.') return Connection(self._engine.connect())
Get a connection to this Database. Connections are retrieved from a pool.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L285-L292
null
class Database(object): """A Database. Encapsulates a url and an SQLAlchemy engine with a pool of connections. """ def __init__(self, db_url=None, **kwargs): # If no db_url was provided, fallback to $DATABASE_URL. self.db_url = db_url or DATABASE_URL if not self.db_url: ...
kennethreitz/records
records.py
Database.query
python
def query(self, query, fetchall=False, **params): with self.get_connection() as conn: return conn.query(query, fetchall, **params)
Executes the given SQL query against the Database. Parameters can, optionally, be provided. Returns a RecordCollection, which can be iterated over to get result rows as dictionaries.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L294-L300
[ "def get_connection(self):\n \"\"\"Get a connection to this Database. Connections are retrieved from a\n pool.\n \"\"\"\n if not self.open:\n raise exc.ResourceClosedError('Database closed.')\n\n return Connection(self._engine.connect())\n" ]
class Database(object): """A Database. Encapsulates a url and an SQLAlchemy engine with a pool of connections. """ def __init__(self, db_url=None, **kwargs): # If no db_url was provided, fallback to $DATABASE_URL. self.db_url = db_url or DATABASE_URL if not self.db_url: ...
kennethreitz/records
records.py
Database.bulk_query
python
def bulk_query(self, query, *multiparams): with self.get_connection() as conn: conn.bulk_query(query, *multiparams)
Bulk insert or update.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L302-L306
[ "def get_connection(self):\n \"\"\"Get a connection to this Database. Connections are retrieved from a\n pool.\n \"\"\"\n if not self.open:\n raise exc.ResourceClosedError('Database closed.')\n\n return Connection(self._engine.connect())\n" ]
class Database(object): """A Database. Encapsulates a url and an SQLAlchemy engine with a pool of connections. """ def __init__(self, db_url=None, **kwargs): # If no db_url was provided, fallback to $DATABASE_URL. self.db_url = db_url or DATABASE_URL if not self.db_url: ...
kennethreitz/records
records.py
Database.query_file
python
def query_file(self, path, fetchall=False, **params): with self.get_connection() as conn: return conn.query_file(path, fetchall, **params)
Like Database.query, but takes a filename to load a query from.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L308-L312
[ "def get_connection(self):\n \"\"\"Get a connection to this Database. Connections are retrieved from a\n pool.\n \"\"\"\n if not self.open:\n raise exc.ResourceClosedError('Database closed.')\n\n return Connection(self._engine.connect())\n" ]
class Database(object): """A Database. Encapsulates a url and an SQLAlchemy engine with a pool of connections. """ def __init__(self, db_url=None, **kwargs): # If no db_url was provided, fallback to $DATABASE_URL. self.db_url = db_url or DATABASE_URL if not self.db_url: ...
kennethreitz/records
records.py
Database.bulk_query_file
python
def bulk_query_file(self, path, *multiparams): with self.get_connection() as conn: conn.bulk_query_file(path, *multiparams)
Like Database.bulk_query, but takes a filename to load a query from.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L314-L318
[ "def get_connection(self):\n \"\"\"Get a connection to this Database. Connections are retrieved from a\n pool.\n \"\"\"\n if not self.open:\n raise exc.ResourceClosedError('Database closed.')\n\n return Connection(self._engine.connect())\n" ]
class Database(object): """A Database. Encapsulates a url and an SQLAlchemy engine with a pool of connections. """ def __init__(self, db_url=None, **kwargs): # If no db_url was provided, fallback to $DATABASE_URL. self.db_url = db_url or DATABASE_URL if not self.db_url: ...
kennethreitz/records
records.py
Database.transaction
python
def transaction(self): conn = self.get_connection() tx = conn.transaction() try: yield conn tx.commit() except: tx.rollback() finally: conn.close()
A context manager for executing a transaction on this Database.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L321-L332
[ "def get_connection(self):\n \"\"\"Get a connection to this Database. Connections are retrieved from a\n pool.\n \"\"\"\n if not self.open:\n raise exc.ResourceClosedError('Database closed.')\n\n return Connection(self._engine.connect())\n", "def close(self):\n self._conn.close()\n sel...
class Database(object): """A Database. Encapsulates a url and an SQLAlchemy engine with a pool of connections. """ def __init__(self, db_url=None, **kwargs): # If no db_url was provided, fallback to $DATABASE_URL. self.db_url = db_url or DATABASE_URL if not self.db_url: ...
kennethreitz/records
records.py
Connection.query
python
def query(self, query, fetchall=False, **params): # Execute the given query. cursor = self._conn.execute(text(query), **params) # TODO: PARAMS GO HERE # Row-by-row Record generator. row_gen = (Record(cursor.keys(), row) for row in cursor) # Convert psycopg2 results to RecordCo...
Executes the given SQL query against the connected Database. Parameters can, optionally, be provided. Returns a RecordCollection, which can be iterated over to get result rows as dictionaries.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L355-L374
[ "def all(self, as_dict=False, as_ordereddict=False):\n \"\"\"Returns a list of all rows for the RecordCollection. If they haven't\n been fetched yet, consume the iterator and cache the results.\"\"\"\n\n # By calling list it calls the __iter__ method\n rows = list(self)\n\n if as_dict:\n retur...
class Connection(object): """A Database connection.""" def __init__(self, connection): self._conn = connection self.open = not connection.closed def close(self): self._conn.close() self.open = False def __enter__(self): return self def __exit__(self, exc, ...
kennethreitz/records
records.py
Connection.bulk_query
python
def bulk_query(self, query, *multiparams): self._conn.execute(text(query), *multiparams)
Bulk insert or update.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L376-L379
null
class Connection(object): """A Database connection.""" def __init__(self, connection): self._conn = connection self.open = not connection.closed def close(self): self._conn.close() self.open = False def __enter__(self): return self def __exit__(self, exc, ...
kennethreitz/records
records.py
Connection.query_file
python
def query_file(self, path, fetchall=False, **params): # If path doesn't exists if not os.path.exists(path): raise IOError("File '{}' not found!".format(path)) # If it's a directory if os.path.isdir(path): raise IOError("'{}' is a directory!".format(path)) ...
Like Connection.query, but takes a filename to load a query from.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L381-L397
null
class Connection(object): """A Database connection.""" def __init__(self, connection): self._conn = connection self.open = not connection.closed def close(self): self._conn.close() self.open = False def __enter__(self): return self def __exit__(self, exc, ...
kennethreitz/records
records.py
Connection.bulk_query_file
python
def bulk_query_file(self, path, *multiparams): # If path doesn't exists if not os.path.exists(path): raise IOError("File '{}'' not found!".format(path)) # If it's a directory if os.path.isdir(path): raise IOError("'{}' is a directory!".format(path)) # ...
Like Connection.bulk_query, but takes a filename to load a query from.
train
https://github.com/kennethreitz/records/blob/ecd857266c5e7830d657cbe0196816314790563b/records.py#L399-L416
null
class Connection(object): """A Database connection.""" def __init__(self, connection): self._conn = connection self.open = not connection.closed def close(self): self._conn.close() self.open = False def __enter__(self): return self def __exit__(self, exc, ...
kennethreitz/maya
maya/compat.py
comparable
python
def comparable(klass): # On Python 2, __cmp__ will just work, so no need to add extra methods: if not is_py3: return klass def __eq__(self, other): c = self.__cmp__(other) if c is NotImplemented: return c return c == 0 def __ne__(self, other): c = s...
Class decorator that ensures support for the special C{__cmp__} method. On Python 2 this does nothing. On Python 3, C{__eq__}, C{__lt__}, etc. methods are added to the class, relying on C{__cmp__} to implement their comparisons.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/compat.py#L43-L102
null
# -*- coding: utf-8 -*- """ maya.compat ~~~~~~~~~~~~~~~ This module handles import compatibility issues between Python 2 and Python 3. """ import sys # ------- # Pythons # ------- # Syntax sugar. _ver = sys.version_info # : Python 2.x? is_py2 = (_ver[0] == 2) # : Python 3.x? is_py3 = (_ver[0] == 3) # --------- # Spec...
kennethreitz/maya
maya/core.py
validate_class_type_arguments
python
def validate_class_type_arguments(operator): def inner(function): def wrapper(self, *args, **kwargs): for arg in args + tuple(kwargs.values()): if not isinstance(arg, self.__class__): raise TypeError( 'unorderable types: {}() {} {}()'...
Decorator to validate all the arguments to function are of the type of calling class for passed operator
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L22-L43
null
# ___ __ ___ _ _ ___ # || \/ | ||=|| \\// ||=|| # || | || || // || || import email.utils import time import functools from datetime import timedelta, datetime as Datetime import re import pytz import humanize import dateparser import pendulum import snaptime from tzlocal import get_localzone from dateutil.re...
kennethreitz/maya
maya/core.py
validate_arguments_type_of_function
python
def validate_arguments_type_of_function(param_type=None): def inner(function): def wrapper(self, *args, **kwargs): type_ = param_type or type(self) for arg in args + tuple(kwargs.values()): if not isinstance(arg, type_): raise TypeError( ...
Decorator to validate the <type> of arguments in the calling function are of the `param_type` class. if `param_type` is None, uses `param_type` as the class where it is used. Note: Use this decorator on the functions of the class.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L46-L77
null
# ___ __ ___ _ _ ___ # || \/ | ||=|| \\// ||=|| # || | || || // || || import email.utils import time import functools from datetime import timedelta, datetime as Datetime import re import pytz import humanize import dateparser import pendulum import snaptime from tzlocal import get_localzone from dateutil.re...
kennethreitz/maya
maya/core.py
utc_offset
python
def utc_offset(time_struct=None): if time_struct: ts = time_struct else: ts = time.localtime() if ts[-1]: offset = time.altzone else: offset = time.timezone return offset
Returns the time offset from UTC accounting for DST Keyword Arguments: time_struct {time.struct_time} -- the struct time for which to return the UTC offset. If None, use current local time.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L369-L387
null
# ___ __ ___ _ _ ___ # || \/ | ||=|| \\// ||=|| # || | || || // || || import email.utils import time import functools from datetime import timedelta, datetime as Datetime import re import pytz import humanize import dateparser import pendulum import snaptime from tzlocal import get_localzone from dateutil.re...
kennethreitz/maya
maya/core.py
when
python
def when(string, timezone='UTC', prefer_dates_from='current_period'): " settings = { 'TIMEZONE': timezone, 'RETURN_AS_TIMEZONE_AWARE': True, 'TO_TIMEZONE': 'UTC', 'PREFER_DATES_FROM': prefer_dates_from, } dt = dateparser.parse(string, settings=settings) if dt is None...
Returns a MayaDT instance for the human moment specified. Powered by dateparser. Useful for scraping websites. Examples: 'next week', 'now', 'tomorrow', '300 years ago', 'August 14, 2015' Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (defaul...
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L710-L739
[ "def wrapper(self, *args, **kwargs):\n type_ = param_type or type(self)\n for arg in args + tuple(kwargs.values()):\n if not isinstance(arg, type_):\n raise TypeError(\n (\n 'Invalid Type: {}.{}() accepts only the '\n 'arguments of type \"...
# ___ __ ___ _ _ ___ # || \/ | ||=|| \\// ||=|| # || | || || // || || import email.utils import time import functools from datetime import timedelta, datetime as Datetime import re import pytz import humanize import dateparser import pendulum import snaptime from tzlocal import get_localzone from dateutil.re...
kennethreitz/maya
maya/core.py
parse
python
def parse(string, timezone='UTC', day_first=False, year_first=True, strict=False): " options = {} options['tz'] = timezone options['day_first'] = day_first options['year_first'] = year_first options['strict'] = strict dt = pendulum.parse(str(string), **options) return MayaDT.from_dateti...
Returns a MayaDT instance for the machine-produced moment specified. Powered by pendulum. Accepts most known formats. Useful for working with data. Keyword Arguments: string -- string to be parsed timezone -- timezone referenced from (default: 'UTC') day_first -- if true, the first...
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L742-L767
[ "def wrapper(self, *args, **kwargs):\n type_ = param_type or type(self)\n for arg in args + tuple(kwargs.values()):\n if not isinstance(arg, type_):\n raise TypeError(\n (\n 'Invalid Type: {}.{}() accepts only the '\n 'arguments of type \"...
# ___ __ ___ _ _ ___ # || \/ | ||=|| \\// ||=|| # || | || || // || || import email.utils import time import functools from datetime import timedelta, datetime as Datetime import re import pytz import humanize import dateparser import pendulum import snaptime from tzlocal import get_localzone from dateutil.re...
kennethreitz/maya
maya/core.py
_seconds_or_timedelta
python
def _seconds_or_timedelta(duration): if isinstance(duration, int): dt_timedelta = timedelta(seconds=duration) elif isinstance(duration, timedelta): dt_timedelta = duration else: raise TypeError( 'Expects argument as `datetime.timedelta` object ' 'or seconds in...
Returns `datetime.timedelta` object for the passed duration. Keyword Arguments: duration -- `datetime.timedelta` object or seconds in `int` format.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L770-L786
null
# ___ __ ___ _ _ ___ # || \/ | ||=|| \\// ||=|| # || | || || // || || import email.utils import time import functools from datetime import timedelta, datetime as Datetime import re import pytz import humanize import dateparser import pendulum import snaptime from tzlocal import get_localzone from dateutil.re...
kennethreitz/maya
maya/core.py
intervals
python
def intervals(start, end, interval): interval = _seconds_or_timedelta(interval) current_timestamp = start while current_timestamp.epoch < end.epoch: yield current_timestamp current_timestamp = current_timestamp.add( seconds=interval.total_seconds() )
Yields MayaDT objects between the start and end MayaDTs given, at a given interval (seconds or timedelta).
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L799-L811
[ "def _seconds_or_timedelta(duration):\n \"\"\"Returns `datetime.timedelta` object for the passed duration.\n\n Keyword Arguments:\n duration -- `datetime.timedelta` object or seconds in `int` format.\n \"\"\"\n if isinstance(duration, int):\n dt_timedelta = timedelta(seconds=duration)\n ...
# ___ __ ___ _ _ ___ # || \/ | ||=|| \\// ||=|| # || | || || // || || import email.utils import time import functools from datetime import timedelta, datetime as Datetime import re import pytz import humanize import dateparser import pendulum import snaptime from tzlocal import get_localzone from dateutil.re...
kennethreitz/maya
maya/core.py
MayaDT.add
python
def add(self, **kwargs): return self.from_datetime( pendulum.instance(self.datetime()).add(**kwargs) )
Returns a new MayaDT object with the given offsets.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L142-L146
[ "def datetime(self, to_timezone=None, naive=False):\n \"\"\"Returns a timezone-aware datetime...\n Defaulting to UTC (as it should).\n\n Keyword Arguments:\n to_timezone {str} -- timezone to convert to (default: None/UTC)\n naive {bool} -- if True,\n the tzinfo is simpl...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.subtract
python
def subtract(self, **kwargs): return self.from_datetime( pendulum.instance(self.datetime()).subtract(**kwargs) )
Returns a new MayaDT object with the given offsets.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L148-L152
[ "def datetime(self, to_timezone=None, naive=False):\n \"\"\"Returns a timezone-aware datetime...\n Defaulting to UTC (as it should).\n\n Keyword Arguments:\n to_timezone {str} -- timezone to convert to (default: None/UTC)\n naive {bool} -- if True,\n the tzinfo is simpl...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.snap
python
def snap(self, instruction): return self.from_datetime(snaptime.snap(self.datetime(), instruction))
Returns a new MayaDT object modified by the given instruction. Powered by snaptime. See https://github.com/zartstrom/snaptime for a complete documentation about the snaptime instructions.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L158-L165
[ "def datetime(self, to_timezone=None, naive=False):\n \"\"\"Returns a timezone-aware datetime...\n Defaulting to UTC (as it should).\n\n Keyword Arguments:\n to_timezone {str} -- timezone to convert to (default: None/UTC)\n naive {bool} -- if True,\n the tzinfo is simpl...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.local_timezone
python
def local_timezone(self): if self._local_tz.zone in pytz.all_timezones: return self._local_tz.zone return self.timezone
Returns the name of the local timezone.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L180-L185
null
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.__dt_to_epoch
python
def __dt_to_epoch(dt): # Assume UTC if no datetime is provided. if dt.tzinfo is None: dt = dt.replace(tzinfo=pytz.utc) epoch_start = Datetime(*MayaDT.__EPOCH_START, tzinfo=pytz.timezone('UTC')) return (dt - epoch_start).total_seconds()
Converts a datetime into an epoch.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L194-L200
null
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.from_struct
python
def from_struct(klass, struct, timezone=pytz.UTC): struct_time = time.mktime(struct) - utc_offset(struct) dt = Datetime.fromtimestamp(struct_time, timezone) return klass(klass.__dt_to_epoch(dt))
Returns MayaDT instance from a 9-tuple struct It's assumed to be from gmtime().
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L212-L219
[ "def utc_offset(time_struct=None):\n \"\"\"\n Returns the time offset from UTC accounting for DST\n\n Keyword Arguments:\n time_struct {time.struct_time} -- the struct time for which to\n return the UTC offset.\n If No...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.datetime
python
def datetime(self, to_timezone=None, naive=False): if to_timezone: dt = self.datetime().astimezone(pytz.timezone(to_timezone)) else: dt = Datetime.utcfromtimestamp(self._epoch) dt.replace(tzinfo=self._tz) # Strip the timezone info if requested to do so. ...
Returns a timezone-aware datetime... Defaulting to UTC (as it should). Keyword Arguments: to_timezone {str} -- timezone to convert to (default: None/UTC) naive {bool} -- if True, the tzinfo is simply dropped (default: False)
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L238-L259
[ "def datetime(self, to_timezone=None, naive=False):\n \"\"\"Returns a timezone-aware datetime...\n Defaulting to UTC (as it should).\n\n Keyword Arguments:\n to_timezone {str} -- timezone to convert to (default: None/UTC)\n naive {bool} -- if True,\n the tzinfo is simpl...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.iso8601
python
def iso8601(self): # Get a timezone-naive datetime. dt = self.datetime(naive=True) return '{}Z'.format(dt.isoformat())
Returns an ISO 8601 representation of the MayaDT.
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L269-L273
[ "def datetime(self, to_timezone=None, naive=False):\n \"\"\"Returns a timezone-aware datetime...\n Defaulting to UTC (as it should).\n\n Keyword Arguments:\n to_timezone {str} -- timezone to convert to (default: None/UTC)\n naive {bool} -- if True,\n the tzinfo is simpl...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.slang_date
python
def slang_date(self, locale="en"): " dt = pendulum.instance(self.datetime()) try: return _translate(dt, locale) except KeyError: pass delta = humanize.time.abs_timedelta( timedelta(seconds=(self.epoch - now().epoch))) format_string =...
Returns human slang representation of date. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English)
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L335-L356
[ "def now():\n \"\"\"Returns a MayaDT instance for this exact moment.\"\"\"\n epoch = time.time()\n return MayaDT(epoch=epoch)\n", "def _translate(dt, target_locale):\n en = default_loader.get_locale(\"en\")\n target = default_loader.get_locale(target_locale)\n naturaldate = humanize.naturaldate(...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
kennethreitz/maya
maya/core.py
MayaDT.slang_time
python
def slang_time(self, locale="en"): " dt = self.datetime() return pendulum.instance(dt).diff_for_humans(locale=locale)
Returns human slang representation of time. Keyword Arguments: locale -- locale to translate to, e.g. 'fr' for french. (default: 'en' - English)
train
https://github.com/kennethreitz/maya/blob/774b141d91a83a5d77cb5351db3d02bf50564b21/maya/core.py#L358-L366
[ "def datetime(self, to_timezone=None, naive=False):\n \"\"\"Returns a timezone-aware datetime...\n Defaulting to UTC (as it should).\n\n Keyword Arguments:\n to_timezone {str} -- timezone to convert to (default: None/UTC)\n naive {bool} -- if True,\n the tzinfo is simpl...
class MayaDT(object): """The Maya Datetime object.""" __EPOCH_START = (1970, 1, 1) def __init__(self, epoch): super(MayaDT, self).__init__() self._epoch = epoch def __repr__(self): return '<MayaDT epoch={}>'.format(self._epoch) def __str__(self): return self.rfc282...
dunovank/jupyter-themes
jupyterthemes/__init__.py
get_themes
python
def get_themes(): styles_dir = os.path.join(package_dir, 'styles') themes = [os.path.basename(theme).replace('.less', '') for theme in glob('{0}/*.less'.format(styles_dir))] return themes
return list of available themes
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/__init__.py#L20-L25
null
import os import sys from argparse import ArgumentParser from glob import glob from . import stylefx from . import jtplot # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) modules = glob(os.path.dirname(__file__) + "/*.py") __all__ = [os.path.basename(f)[:-3] for f i...
dunovank/jupyter-themes
jupyterthemes/__init__.py
install_theme
python
def install_theme(theme=None, monofont=None, monosize=11, nbfont=None, nbfontsize=13, tcfont=None, tcfontsize=13, dffontsize=93, outfontsize=85, mathfontsize=100, ...
Install theme to jupyter_customcss with specified font, fontsize, md layout, and toolbar pref
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/__init__.py#L28-L112
[ "def reset_default(verbose=False):\n \"\"\"Remove custom.css and custom fonts\"\"\"\n paths = [jupyter_custom, jupyter_nbext]\n\n for fpath in paths:\n custom = '{0}{1}{2}.css'.format(fpath, os.sep, 'custom')\n try:\n os.remove(custom)\n except Exception:\n pass\n...
import os import sys from argparse import ArgumentParser from glob import glob from . import stylefx from . import jtplot # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) modules = glob(os.path.dirname(__file__) + "/*.py") __all__ = [os.path.basename(f)[:-3] for f i...
dunovank/jupyter-themes
jupyterthemes/jtplot.py
infer_theme
python
def infer_theme(): themes = [os.path.basename(theme).replace('.less', '') for theme in glob('{0}/*.less'.format(styles_dir))] if os.path.exists(theme_name_file): with open(theme_name_file) as f: theme = f.readlines()[0] if theme not in themes: theme = 'd...
checks jupyter_config_dir() for text file containing theme name (updated whenever user installs a new theme)
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L62-L76
null
import os import sys import re from glob import glob import matplotlib as mpl from jupyter_core.paths import jupyter_config_dir # path to install (~/.jupyter/custom/) jupyter_custom = os.path.join(jupyter_config_dir(), 'custom') # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath...
dunovank/jupyter-themes
jupyterthemes/jtplot.py
style
python
def style(theme=None, context='paper', grid=True, gridlines=u'-', ticks=False, spines=True, fscale=1.2, figsize=(8., 7.)): # set context and font rc parameters, return rcdict rcdict = set_context(context=context, fscale=fscale, figsize=figsize) # read in theme name from ~/.jupyter/custom/current_theme.txt...
main function for styling matplotlib according to theme ::Arguments:: theme (str): 'oceans16', 'grade3', 'chesterish', 'onedork', 'monokai', 'solarizedl', 'solarizedd'. If no theme name supplied the currently installed notebook theme will be used. context (str): 'paper' (Default), 'notebook', 'tal...
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L79-L109
[ "def infer_theme():\n \"\"\" checks jupyter_config_dir() for text file containing theme name\n (updated whenever user installs a new theme)\n \"\"\"\n themes = [os.path.basename(theme).replace('.less', '')\n for theme in glob('{0}/*.less'.format(styles_dir))]\n if os.path.exists(them...
import os import sys import re from glob import glob import matplotlib as mpl from jupyter_core.paths import jupyter_config_dir # path to install (~/.jupyter/custom/) jupyter_custom = os.path.join(jupyter_config_dir(), 'custom') # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath...
dunovank/jupyter-themes
jupyterthemes/jtplot.py
set_style
python
def set_style(rcdict, theme=None, grid=True, gridlines=u'-', ticks=False, spines=True): # extract style and color info for theme styleMap, clist = get_theme_style(theme) # extract style variables figureFace = styleMap['figureFace'] axisFace = styleMap['axisFace'] textColor = styleMap['textColo...
This code has been modified from seaborn.rcmod.set_style() ::Arguments:: rcdict (str): dict of "context" properties (filled by set_context()) theme (str): name of theme to use when setting color properties grid (bool): turns off axis grid if False (default: True) ticks (bool): remove...
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L113-L188
[ "def get_theme_style(theme):\n \"\"\"\n read-in theme style info and populate styleMap (dict of with mpl.rcParams)\n and clist (list of hex codes passed to color cylcler)\n ::Arguments::\n theme (str): theme name\n ::Returns::\n styleMap (dict): dict containing theme-specific colors for...
import os import sys import re from glob import glob import matplotlib as mpl from jupyter_core.paths import jupyter_config_dir # path to install (~/.jupyter/custom/) jupyter_custom = os.path.join(jupyter_config_dir(), 'custom') # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath...
dunovank/jupyter-themes
jupyterthemes/jtplot.py
set_context
python
def set_context(context='paper', fscale=1., figsize=(8., 7.)): # scale all the parameters by the same factor depending on the context scaling = dict(paper=.8, notebook=1, talk=1.3, poster=1.6)[context] context_dict = {k: v * scaling for k, v in base_context.items()} # scale default figsize figX, fi...
Most of this code has been copied/modified from seaborn.rcmod.plotting_context() ::Arguments:: context (str): 'paper', 'notebook', 'talk', or 'poster' fscale (float): font-size scalar applied to axes ticks, legend, labels, etc.
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L191-L212
null
import os import sys import re from glob import glob import matplotlib as mpl from jupyter_core.paths import jupyter_config_dir # path to install (~/.jupyter/custom/) jupyter_custom = os.path.join(jupyter_config_dir(), 'custom') # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath...
dunovank/jupyter-themes
jupyterthemes/jtplot.py
figsize
python
def figsize(x=8, y=7., aspect=1.): # update rcparams with adjusted figsize params mpl.rcParams.update({'figure.figsize': (x*aspect, y)})
manually set the default figure size of plots ::Arguments:: x (float): x-axis size y (float): y-axis size aspect (float): aspect ratio scalar
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L215-L223
null
import os import sys import re from glob import glob import matplotlib as mpl from jupyter_core.paths import jupyter_config_dir # path to install (~/.jupyter/custom/) jupyter_custom = os.path.join(jupyter_config_dir(), 'custom') # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath...
dunovank/jupyter-themes
jupyterthemes/jtplot.py
get_theme_style
python
def get_theme_style(theme): styleMap, clist = get_default_jtstyle() if theme == 'default': return styleMap, clist syntaxVars = ['@yellow:', '@orange:', '@red:', '@magenta:', '@violet:', '@blue:', '@cyan:', '@green:'] get_hex_code = lambda line: line.split(':')[-1].split(';')[0][-7:] theme...
read-in theme style info and populate styleMap (dict of with mpl.rcParams) and clist (list of hex codes passed to color cylcler) ::Arguments:: theme (str): theme name ::Returns:: styleMap (dict): dict containing theme-specific colors for figure properties clist (list): list of colors...
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L226-L258
[ "def remove_non_colors(clist):\n checkHex = r'^#(?:[0-9a-fA-F]{3}){1,2}$'\n return [clr for clr in clist if re.search(checkHex, clr)]\n", "def get_default_jtstyle():\n styleMap = {'axisFace': 'white',\n 'figureFace': 'white',\n 'textColor': '.15',\n 'edgeColor...
import os import sys import re from glob import glob import matplotlib as mpl from jupyter_core.paths import jupyter_config_dir # path to install (~/.jupyter/custom/) jupyter_custom = os.path.join(jupyter_config_dir(), 'custom') # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath...
dunovank/jupyter-themes
jupyterthemes/jtplot.py
reset
python
def reset(): colors = [(0., 0., 1.), (0., .5, 0.), (1., 0., 0.), (.75, .75, 0.), (.75, .75, 0.), (0., .75, .75), (0., 0., 0.)] for code, color in zip("bgrmyck", colors): rgb = mpl.colors.colorConverter.to_rgb(color) mpl.colors.colorConverter.colors[code] = rgb mpl.colors.colo...
full reset of matplotlib default style and colors
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/jtplot.py#L276-L287
null
import os import sys import re from glob import glob import matplotlib as mpl from jupyter_core.paths import jupyter_config_dir # path to install (~/.jupyter/custom/) jupyter_custom = os.path.join(jupyter_config_dir(), 'custom') # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
less_to_css
python
def less_to_css(style_less): with fileOpen(tempfile, 'w') as f: f.write(style_less) os.chdir(package_dir) style_css = lesscpy.compile(tempfile) style_css += '\n\n' return style_css
write less-compiled css file to jupyter_customcss in jupyter_dir
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L69-L77
[ "def fileOpen(filename, mode):\n if sys.version_info[0]==3:\n return open(filename, mode, encoding='utf8', errors='ignore')\n else:\n return open(filename, mode)\n" ]
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
set_font_properties
python
def set_font_properties(style_less, nbfont=None, tcfont=None, monofont=None, monosize=11, tcfontsize=13, nbfontsize=13, prfontsize=95, ...
Parent function for setting notebook, text/md, and codecell font-properties
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L120-L179
[ "def convert_fontsizes(fontsizes):\n # if triple digits, move decimal (105 --> 10.5)\n fontsizes = [str(fs) for fs in fontsizes]\n for i, fs in enumerate(fontsizes):\n if len(fs) >= 3:\n fontsizes[i] = '.'.join([fs[:-1], fs[-1]])\n elif int(fs) > 25:\n fontsizes[i] = '.'...
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
import_fonts
python
def import_fonts(style_less, fontname, font_subdir): ftype_dict = {'woff2': 'woff2', 'woff': 'woff', 'ttf': 'truetype', 'otf': 'opentype', 'svg': 'svg'} define_font = ( "@font-face {{font-family: {fontname};\n\tfont-weight:" ...
Copy all custom fonts to ~/.jupyter/custom/fonts/ and write import statements to style_less
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L182-L218
[ "def send_fonts_to_jupyter(font_file_path):\n fname = font_file_path.split(os.sep)[-1]\n copyfile(font_file_path, os.path.join(jupyter_custom_fonts, fname))\n" ]
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
style_layout
python
def style_layout(style_less, theme='grade3', cursorwidth=2, cursorcolor='default', cellwidth='980', lineheight=170, margins='auto', vimext=False, toolbar=False, nbname...
Set general layout and style properties of text and code cells
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L221-L326
[ "def fileOpen(filename, mode):\n if sys.version_info[0]==3:\n return open(filename, mode, encoding='utf8', errors='ignore')\n else:\n return open(filename, mode)\n", "def toggle_settings(\n toolbar=False, nbname=False, hideprompt=False, kernellogo=False):\n \"\"\"Toggle main notebook...
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
toggle_settings
python
def toggle_settings( toolbar=False, nbname=False, hideprompt=False, kernellogo=False): toggle = '' if toolbar: toggle += 'div#maintoolbar {margin-left: 8px !important;}\n' toggle += '.toolbar.container {width: 100% !important;}\n' else: toggle += 'div#maintoolbar {display: n...
Toggle main notebook toolbar (e.g., buttons), filename, and kernel logo.
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L329-L364
null
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
set_mathjax_style
python
def set_mathjax_style(style_css, mathfontsize): jax_style = """<script> MathJax.Hub.Config({ "HTML-CSS": { /*preferredFont: "TeX",*/ /*availableFonts: ["TeX", "STIX"],*/ styles: { scale: %d, ".MathJax_Display": { "f...
Write mathjax settings, set math fontsize
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L400-L420
null
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
set_vim_style
python
def set_vim_style(theme): vim_jupyter_nbext = os.path.join(jupyter_nbext, 'vim_binding') if not os.path.isdir(vim_jupyter_nbext): os.makedirs(vim_jupyter_nbext) vim_less = '@import "styles{}";\n'.format(''.join([os.sep, theme])) with open(vim_style, 'r') as vimstyle: vim_less += vims...
Add style and compatibility with vim notebook extension
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L424-L445
null
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
reset_default
python
def reset_default(verbose=False): paths = [jupyter_custom, jupyter_nbext] for fpath in paths: custom = '{0}{1}{2}.css'.format(fpath, os.sep, 'custom') try: os.remove(custom) except Exception: pass try: delete_font_files() except Exception: ...
Remove custom.css and custom fonts
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L448-L471
[ "def check_directories():\n # Ensure all install dirs exist\n if not os.path.isdir(jupyter_home):\n os.makedirs(jupyter_home)\n if not os.path.isdir(jupyter_custom):\n os.makedirs(jupyter_custom)\n if not os.path.isdir(jupyter_custom_fonts):\n os.makedirs(jupyter_custom_fonts)\n ...
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
dunovank/jupyter-themes
jupyterthemes/stylefx.py
set_nb_theme
python
def set_nb_theme(name): from IPython.core.display import HTML styles_dir = os.path.join(package_dir, 'styles/compiled/') css_path = glob('{0}/{1}.css'.format(styles_dir, name))[0] customcss = open(css_path, "r").read() return HTML(''.join(['<style> ', customcss, ' </style>']))
Set theme from within notebook
train
https://github.com/dunovank/jupyter-themes/blob/421016c2e4fed75fa1830d664c10478d9bd25ed1/jupyterthemes/stylefx.py#L474-L481
null
import os, sys import lesscpy from shutil import copyfile, rmtree from jupyter_core.paths import jupyter_config_dir, jupyter_data_dir from glob import glob from tempfile import mkstemp # path to local site-packages/jupyterthemes package_dir = os.path.dirname(os.path.realpath(__file__)) # path to user jupyter-themes d...
cs01/gdbgui
gdbgui/htmllistformatter.py
HtmlListFormatter.get_marked_up_list
python
def get_marked_up_list(self, tokensource): # import ipdb; ipdb.set_trace() source = self._format_lines(tokensource) if self.hl_lines: source = self._highlight_lines(source) if not self.nowrap: if self.linenos == 2: source = self._wrap_inlinelinenos...
an updated version of pygments.formatter.format_unencoded
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/htmllistformatter.py#L9-L36
null
class HtmlListFormatter(HtmlFormatter): """A custom pygments class to format html. Returns a list of source code. Each element of the list corresponds to a line of (marked up) source code. """
cs01/gdbgui
gdbgui/SSLify.py
get_ssl_context
python
def get_ssl_context(private_key, certificate): if ( certificate and os.path.isfile(certificate) and private_key and os.path.isfile(private_key) ): context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2) context.load_cert_chain(certificate, private_key) return conte...
Get ssl context from private key and certificate paths. The return value is used when calling Flask. i.e. app.run(ssl_context=get_ssl_context(,,,))
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/SSLify.py#L90-L104
null
"""Module to enable SSL for Flask application. Adapted from https://github.com/kennethreitz/flask-sslify """ import os import ssl from flask import request, redirect YEAR_IN_SECS = 31536000 class SSLify(object): """Secures your Flask App.""" def __init__( self, app=None, age=YEAR_IN_SECS, subdomain...
cs01/gdbgui
gdbgui/SSLify.py
SSLify.init_app
python
def init_app(self, app): app.config.setdefault("SSLIFY_SUBDOMAINS", False) app.config.setdefault("SSLIFY_PERMANENT", False) app.config.setdefault("SSLIFY_SKIPS", None) self.hsts_include_subdomains = ( self.hsts_include_subdomains or app.config["SSLIFY_SUBDOMAINS"] ) ...
Configures the specified Flask app to enforce SSL.
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/SSLify.py#L28-L41
null
class SSLify(object): """Secures your Flask App.""" def __init__( self, app=None, age=YEAR_IN_SECS, subdomains=False, permanent=False, skips=None ): self.app = app self.hsts_age = age self.hsts_include_subdomains = subdomains self.permanent = permanent self....
cs01/gdbgui
gdbgui/SSLify.py
SSLify.set_hsts_header
python
def set_hsts_header(self, response): # Should we add STS header? if request.is_secure and not self.skip: response.headers.setdefault("Strict-Transport-Security", self.hsts_header) return response
Adds HSTS header to each response.
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/SSLify.py#L82-L87
null
class SSLify(object): """Secures your Flask App.""" def __init__( self, app=None, age=YEAR_IN_SECS, subdomains=False, permanent=False, skips=None ): self.app = app self.hsts_age = age self.hsts_include_subdomains = subdomains self.permanent = permanent self....
cs01/gdbgui
gdbgui/backend.py
csrf_protect_all_post_and_cross_origin_requests
python
def csrf_protect_all_post_and_cross_origin_requests(): success = None if is_cross_origin(request): logger.warning("Received cross origin request. Aborting") abort(403) if request.method in ["POST", "PUT"]: token = session.get("csrf_token") if token == request.form.get("csrf_...
returns None upon success
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L116-L133
[ "def is_cross_origin(request):\n \"\"\"Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then\n compare. Return true if they are not equal\n example HTTP_HOST: '127.0.0.1:5000'\n example HTTP_ORIGIN: 'http://127.0.0.1:5000'\n \"\"\"\n origin = request.environ.get(\"HTTP_ORIGIN\"...
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
is_cross_origin
python
def is_cross_origin(request): origin = request.environ.get("HTTP_ORIGIN") host = request.environ.get("HTTP_HOST") if origin is None: # origin is sometimes omitted by the browser when origin and host are equal return False if origin.startswith("http://"): origin = origin.replace(...
Compare headers HOST and ORIGIN. Remove protocol prefix from ORIGIN, then compare. Return true if they are not equal example HTTP_HOST: '127.0.0.1:5000' example HTTP_ORIGIN: 'http://127.0.0.1:5000'
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L136-L152
null
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
csrf_protect
python
def csrf_protect(f): @wraps(f) def wrapper(*args, **kwargs): token = session.get("csrf_token", None) if token is None or token != request.environ.get("HTTP_X_CSRFTOKEN"): logger.warning("Received invalid csrf token. Aborting") abort(403) # call original request h...
A decorator to add csrf protection by validing the X_CSRFTOKEN field in request header
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L155-L168
null
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
setup_backend
python
def setup_backend( serve=True, host=DEFAULT_HOST, port=DEFAULT_PORT, debug=False, open_browser=True, browsername=None, testing=False, private_key=None, certificate=None, LLDB=False, ): app.config["LLDB"] = LLDB kwargs = {} ssl_context = get_ssl_context(private_key, c...
Run the server of the gdb gui
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L180-L260
[ "def get_ssl_context(private_key, certificate): # noqa\n return None\n", "def get_ssl_context(private_key, certificate):\n \"\"\"Get ssl context from private key and certificate paths.\n The return value is used when calling Flask.\n i.e. app.run(ssl_context=get_ssl_context(,,,))\n \"\"\"\n if ...
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
dbprint
python
def dbprint(*args): if app and app.debug: if USING_WINDOWS: print("DEBUG: " + " ".join(args)) else: CYELLOW2 = "\33[93m" NORMAL = "\033[0m" print(CYELLOW2 + "DEBUG: " + " ".join(args) + NORMAL)
print only if app.debug is truthy
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L283-L292
null
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
run_gdb_command
python
def run_gdb_command(message): controller = _state.get_controller_from_client_id(request.sid) if controller is not None: try: # the command (string) or commands (list) to run cmd = message["cmd"] controller.write(cmd, read_response=False) except Exception: ...
Endpoint for a websocket route. Runs a gdb command. Responds only if an error occurs when trying to write the command to gdb
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L347-L366
[ "def get_controller_from_client_id(self, client_id):\n for controller, client_ids in self.controller_to_client_ids.items():\n if client_id in client_ids:\n return controller\n\n return None\n" ]
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
send_msg_to_clients
python
def send_msg_to_clients(client_ids, msg, error=False): if error: stream = "stderr" else: stream = "stdout" response = [{"message": None, "type": "console", "payload": msg, "stream": stream}] for client_id in client_ids: logger.info("emiting message to websocket client id " + cl...
Send message to all clients
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L369-L382
null
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
read_and_forward_gdb_output
python
def read_and_forward_gdb_output(): while True: socketio.sleep(0.05) controllers_to_remove = [] controller_items = _state.controller_to_client_ids.items() for controller, client_ids in controller_items: try: try: response = controller.g...
A task that runs on a different thread, and emits websocket messages of gdb responses
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L418-L460
[ "def send_msg_to_clients(client_ids, msg, error=False):\n \"\"\"Send message to all clients\"\"\"\n if error:\n stream = \"stderr\"\n else:\n stream = \"stdout\"\n\n response = [{\"message\": None, \"type\": \"console\", \"payload\": msg, \"stream\": stream}]\n\n for client_id in client...
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
get_extra_files
python
def get_extra_files(): FILES_TO_SKIP = ["src/gdbgui.js"] THIS_DIR = os.path.dirname(os.path.abspath(__file__)) extra_dirs = [THIS_DIR] extra_files = [] for extra_dir in extra_dirs: for dirname, _, files in os.walk(extra_dir): for filename in files: filepath = os.p...
returns a list of files that should be watched by the Flask server when in debug mode to trigger a reload of the server
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L471-L487
null
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
gdbgui
python
def gdbgui(): interpreter = "lldb" if app.config["LLDB"] else "gdb" gdbpid = request.args.get("gdbpid", 0) initial_gdb_user_command = request.args.get("initial_gdb_user_command", "") add_csrf_token_to_session() THEMES = ["monokai", "light"] # fmt: off initial_data = { "csrf_token":...
Render the main gdbgui interface
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L525-L562
[ "def add_csrf_token_to_session():\n if \"csrf_token\" not in session:\n session[\"csrf_token\"] = binascii.hexlify(os.urandom(20)).decode(\"utf-8\")\n" ]
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
get_last_modified_unix_sec
python
def get_last_modified_unix_sec(): path = request.args.get("path") if path and os.path.isfile(path): try: last_modified = os.path.getmtime(path) return jsonify({"path": path, "last_modified_unix_sec": last_modified}) except Exception as e: return client_error(...
Get last modified unix time for a given file
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L654-L666
[ "def client_error(obj):\n return jsonify(obj), 400\n" ]
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
read_file
python
def read_file(): path = request.args.get("path") start_line = int(request.args.get("start_line")) end_line = int(request.args.get("end_line")) start_line = max(1, start_line) # make sure it's not negative try: highlight = json.loads(request.args.get("highlight", "true")) except Except...
Read a file and return its contents as an array
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L671-L743
[ "def client_error(obj):\n return jsonify(obj), 400\n" ]
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
main
python
def main(): parser = get_parser() args = parser.parse_args() if args.debug: logger.setLevel(logging.NOTSET) initialize_preferences() if args.version: print(__version__) return cmd = args.cmd or args.args if args.no_browser and args.browser: print("Cannot ...
Entry point from command line
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L927-L997
[ "def setup_backend(\n serve=True,\n host=DEFAULT_HOST,\n port=DEFAULT_PORT,\n debug=False,\n open_browser=True,\n browsername=None,\n testing=False,\n private_key=None,\n certificate=None,\n LLDB=False,\n):\n \"\"\"Run the server of the gdb gui\"\"\"\n app.config[\"LLDB\"] = LLDB...
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
cs01/gdbgui
gdbgui/backend.py
warn_startup_with_shell_off
python
def warn_startup_with_shell_off(platform, gdb_args): darwin_match = re.match("darwin-(\d+)\..*", platform) on_darwin = darwin_match is not None and int(darwin_match.groups()[0]) >= 16 if on_darwin: shell_is_off = "startup-with-shell off" in gdb_args return not shell_is_off return False
return True if user may need to turn shell off if mac OS version is 16 (sierra) or higher, may need to set shell off due to os's security requirements http://stackoverflow.com/questions/39702871/gdb-kind-of-doesnt-work-on-macos-sierra
train
https://github.com/cs01/gdbgui/blob/5367f87554f8f7c671d1f4596c133bf1303154f0/gdbgui/backend.py#L1000-L1011
null
#!/usr/bin/env python """ A server that provides a graphical user interface to the gnu debugger (gdb). https://github.com/cs01/gdbgui """ import argparse import binascii from distutils.spawn import find_executable from flask import ( Flask, session, request, Response, render_template, jsonify,...
yoeo/guesslang
guesslang/guesser.py
Guess.language_name
python
def language_name(self, text: str) -> str: values = extract(text) input_fn = _to_func(([values], [])) pos: int = next(self._classifier.predict_classes(input_fn=input_fn)) LOGGER.debug("Predicted language position %s", pos) return sorted(self.languages)[pos]
Predict the programming language name of the given source code. :param text: source code. :return: language name
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L61-L72
[ "def extract(text: str) -> List[float]:\n \"\"\"Transform the text into a vector of float values.\n The vector is a representation of the text.\n\n :param text: the text to represent\n :return: representation\n \"\"\"\n return _normalize(_vectorize(split(text)))\n", "def _to_func(vector: DataSet...
class Guess: """Guess the programming language of a source code. :param model_dir: Guesslang machine learning model directory. """ def __init__(self, model_dir: Optional[str] = None) -> None: model_data = model_info(model_dir) #: `tensorflow` model directory self.model_dir: st...
yoeo/guesslang
guesslang/guesser.py
Guess.scores
python
def scores(self, text: str) -> Dict[str, float]: values = extract(text) input_fn = _to_func(([values], [])) prediction = self._classifier.predict_proba(input_fn=input_fn) probabilities = next(prediction).tolist() sorted_languages = sorted(self.languages) return dict(zip(s...
A score for each language corresponding to the probability that the text is written in the given language. The score is a `float` value between 0.0 and 1.0 :param text: source code. :return: language to score dictionary
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L74-L87
[ "def extract(text: str) -> List[float]:\n \"\"\"Transform the text into a vector of float values.\n The vector is a representation of the text.\n\n :param text: the text to represent\n :return: representation\n \"\"\"\n return _normalize(_vectorize(split(text)))\n", "def _to_func(vector: DataSet...
class Guess: """Guess the programming language of a source code. :param model_dir: Guesslang machine learning model directory. """ def __init__(self, model_dir: Optional[str] = None) -> None: model_data = model_info(model_dir) #: `tensorflow` model directory self.model_dir: st...
yoeo/guesslang
guesslang/guesser.py
Guess.probable_languages
python
def probable_languages( self, text: str, max_languages: int = 3) -> Tuple[str, ...]: scores = self.scores(text) # Sorted from the most probable language to the least probable sorted_scores = sorted(scores.items(), key=itemgetter(1), reverse=True) lang...
List of most probable programming languages, the list is ordered from the most probable to the least probable one. :param text: source code. :param max_languages: maximum number of listed languages. :return: languages list
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L89-L116
[ "def scores(self, text: str) -> Dict[str, float]:\n \"\"\"A score for each language corresponding to the probability that\n the text is written in the given language.\n The score is a `float` value between 0.0 and 1.0\n\n :param text: source code.\n :return: language to score dictionary\n \"\"\"\n...
class Guess: """Guess the programming language of a source code. :param model_dir: Guesslang machine learning model directory. """ def __init__(self, model_dir: Optional[str] = None) -> None: model_data = model_info(model_dir) #: `tensorflow` model directory self.model_dir: st...
yoeo/guesslang
guesslang/guesser.py
Guess.learn
python
def learn(self, input_dir: str) -> float: if self.is_default: LOGGER.error("Cannot learn using default model") raise GuesslangError('Cannot learn using default "readonly" model') languages = self.languages LOGGER.info("Extract training data") extensions = [ext f...
Learn languages features from source files. :raise GuesslangError: when the default model is used for learning :param input_dir: source code files directory. :return: learning accuracy
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/guesser.py#L118-L164
[ "def search_files(source: str, extensions: List[str]) -> List[Path]:\n \"\"\"Retrieve files located the source directory and its subdirectories,\n whose extension match one of the listed extensions.\n\n :raise GuesslangError: when there is not enough files in the directory\n :param source: directory nam...
class Guess: """Guess the programming language of a source code. :param model_dir: Guesslang machine learning model directory. """ def __init__(self, model_dir: Optional[str] = None) -> None: model_data = model_info(model_dir) #: `tensorflow` model directory self.model_dir: st...
yoeo/guesslang
tools/report_graph.py
main
python
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'reportfile', type=argparse.FileType('r'), help="test report file generated by `guesslang --test TESTDIR`") parser.add_argument( '-d', '--debug', default=False, action='store_true', help="...
Report graph creator command line
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/report_graph.py#L25-L42
[ "def config_logging(debug: bool = False) -> None:\n \"\"\"Set-up application and `tensorflow` logging.\n\n :param debug: show or hide debug messages\n \"\"\"\n if debug:\n level = 'DEBUG'\n tf_level = tf.logging.INFO\n else:\n level = 'INFO'\n tf_level = tf.logging.ERROR\n...
#!/usr/bin/env python3 """ Create a graph from a Guesslang test report. """ import argparse import json import logging from pathlib import Path import shutil import tempfile import webbrowser from guesslang.config import config_logging LOGGER = logging.getLogger(__name__) RESOURCES_DIR = Path(__file__).parent.jo...
yoeo/guesslang
guesslang/utils.py
search_files
python
def search_files(source: str, extensions: List[str]) -> List[Path]: files = [ path for path in Path(source).glob('**/*') if path.is_file() and path.suffix.lstrip('.') in extensions] nb_files = len(files) LOGGER.debug("Total files found: %d", nb_files) if nb_files < NB_FILES_MIN: ...
Retrieve files located the source directory and its subdirectories, whose extension match one of the listed extensions. :raise GuesslangError: when there is not enough files in the directory :param source: directory name :param extensions: list of file extensions :return: filenames
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L30-L52
null
"""A set of tools to process files""" import logging import multiprocessing from pathlib import Path import random import signal from typing import List, Dict, Sequence, Tuple import numpy as np from guesslang.extractor import extract LOGGER = logging.getLogger(__name__) random.seed() FILE_ENCODINGS = ('utf-8', ...
yoeo/guesslang
guesslang/utils.py
extract_from_files
python
def extract_from_files( files: List[Path], languages: Dict[str, List[str]]) -> DataSet: enumerator = enumerate(sorted(languages.items())) rank_map = {ext: rank for rank, (_, exts) in enumerator for ext in exts} with multiprocessing.Pool(initializer=_process_init) as pool: file_itera...
Extract arrays of features from the given files. :param files: list of paths :param languages: language name => associated file extension list :return: features
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L55-L73
[ "def _to_arrays(features: List[Tuple[List[float], int]]) -> DataSet:\n # Flatten and split the dataset\n ranks = []\n content_vectors = []\n for content_vector, rank in features:\n ranks.append(rank)\n content_vectors.append(content_vector)\n\n # Convert lists into numpy arrays\n ret...
"""A set of tools to process files""" import logging import multiprocessing from pathlib import Path import random import signal from typing import List, Dict, Sequence, Tuple import numpy as np from guesslang.extractor import extract LOGGER = logging.getLogger(__name__) random.seed() FILE_ENCODINGS = ('utf-8', ...
yoeo/guesslang
guesslang/utils.py
safe_read_file
python
def safe_read_file(file_path: Path) -> str: for encoding in FILE_ENCODINGS: try: return file_path.read_text(encoding=encoding) except UnicodeError: pass # Ignore encoding error raise GuesslangError('Encoding not supported for {!s}'.format(file_path))
Read a text file. Several text encodings are tried until the file content is correctly decoded. :raise GuesslangError: when the file encoding is not supported :param file_path: path to the input file :return: text file content
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/utils.py#L106-L120
null
"""A set of tools to process files""" import logging import multiprocessing from pathlib import Path import random import signal from typing import List, Dict, Sequence, Tuple import numpy as np from guesslang.extractor import extract LOGGER = logging.getLogger(__name__) random.seed() FILE_ENCODINGS = ('utf-8', ...
yoeo/guesslang
guesslang/config.py
config_logging
python
def config_logging(debug: bool = False) -> None: if debug: level = 'DEBUG' tf_level = tf.logging.INFO else: level = 'INFO' tf_level = tf.logging.ERROR logging_config = config_dict('logging.json') for logger in logging_config['loggers'].values(): logger['level'] =...
Set-up application and `tensorflow` logging. :param debug: show or hide debug messages
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L53-L70
[ "def config_dict(name: str) -> Dict[str, Any]:\n \"\"\"Load a JSON configuration dict from Guesslang config directory.\n\n :param name: the JSON file name.\n :return: configuration\n \"\"\"\n try:\n content = resource_string(PACKAGE, DATADIR.format(name)).decode()\n except DistributionNotFo...
"""Load configuration from guesslang `config` directory""" import json import logging.config from pathlib import Path import platform from typing import cast, Dict, Any, Tuple, Optional from pkg_resources import ( Requirement, resource_string, resource_filename, DistributionNotFound) import tensorflow as tf LO...
yoeo/guesslang
guesslang/config.py
config_dict
python
def config_dict(name: str) -> Dict[str, Any]: try: content = resource_string(PACKAGE, DATADIR.format(name)).decode() except DistributionNotFound as error: LOGGER.warning("Cannot load %s from packages: %s", name, error) content = DATA_FALLBACK.joinpath(name).read_text() return cast(D...
Load a JSON configuration dict from Guesslang config directory. :param name: the JSON file name. :return: configuration
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L73-L85
null
"""Load configuration from guesslang `config` directory""" import json import logging.config from pathlib import Path import platform from typing import cast, Dict, Any, Tuple, Optional from pkg_resources import ( Requirement, resource_string, resource_filename, DistributionNotFound) import tensorflow as tf LO...
yoeo/guesslang
guesslang/config.py
model_info
python
def model_info(model_dir: Optional[str] = None) -> Tuple[str, bool]: if model_dir is None: try: model_dir = resource_filename(PACKAGE, DATADIR.format('model')) except DistributionNotFound as error: LOGGER.warning("Cannot load model from packages: %s", error) model...
Retrieve Guesslang model directory name, and tells if it is the default model. :param model_dir: model location, if `None` default model is selected :return: selected model directory with an indication that the model is the default or not
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L88-L110
null
"""Load configuration from guesslang `config` directory""" import json import logging.config from pathlib import Path import platform from typing import cast, Dict, Any, Tuple, Optional from pkg_resources import ( Requirement, resource_string, resource_filename, DistributionNotFound) import tensorflow as tf LO...
yoeo/guesslang
guesslang/config.py
ColorLogFormatter.format
python
def format(self, record: logging.LogRecord) -> str: if platform.system() != 'Linux': # Avoid funny logs on Windows & MacOS return super().format(record) record.msg = ( self.STYLE[record.levelname] + record.msg + self.STYLE['END']) record.levelname = ( self.S...
Format log records to produce colored messages. :param record: log record :return: log message
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/config.py#L37-L50
null
class ColorLogFormatter(logging.Formatter): """Logging formatter that prints pretty colored log messages""" STYLE = { # Log messages styles 'DEBUG': '\033[94m', 'INFO': '\033[0m', 'WARNING': '\033[93m', 'ERROR': '\033[1;91m', 'CRITICAL': '\033[1;95m', # O...
yoeo/guesslang
tools/download_github_repo.py
main
python
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( 'githubtoken', help="Github OAuth token, see https://developer.github.com/v3/oauth/") parser.add_argument('destination', help="location of the downloaded repos") parser.add_argument( '-n', '--...
Github repositories downloaded command line
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/download_github_repo.py#L54-L87
[ "def config_logging(debug: bool = False) -> None:\n \"\"\"Set-up application and `tensorflow` logging.\n\n :param debug: show or hide debug messages\n \"\"\"\n if debug:\n level = 'DEBUG'\n tf_level = tf.logging.INFO\n else:\n level = 'INFO'\n tf_level = tf.logging.ERROR\n...
#!/usr/bin/env python3 """ Download repos from Github. The repositories source files will be used to feed Guesslang model. """ import argparse from contextlib import closing import functools import logging from pathlib import Path import random import time from urllib.parse import quote_plus import requests from ...
yoeo/guesslang
tools/download_github_repo.py
retry
python
def retry(default=None): def decorator(func): """Retry decorator""" @functools.wraps(func) def _wrapper(*args, **kw): for pos in range(1, MAX_RETRIES): try: return func(*args, **kw) except (RuntimeError, requests.ConnectionErr...
Retry functions after failures
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/download_github_repo.py#L117-L140
null
#!/usr/bin/env python3 """ Download repos from Github. The repositories source files will be used to feed Guesslang model. """ import argparse from contextlib import closing import functools import logging from pathlib import Path import random import time from urllib.parse import quote_plus import requests from ...
yoeo/guesslang
tools/make_keywords.py
main
python
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('learn', help="learning source codes directory") parser.add_argument('keywords', help="output keywords file, JSON") parser.add_argument( '-n', '--nbkeywords', type=int, default=10000, help="the number ...
Keywords generator command line
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/make_keywords.py#L29-L87
[ "def config_logging(debug: bool = False) -> None:\n \"\"\"Set-up application and `tensorflow` logging.\n\n :param debug: show or hide debug messages\n \"\"\"\n if debug:\n level = 'DEBUG'\n tf_level = tf.logging.INFO\n else:\n level = 'INFO'\n tf_level = tf.logging.ERROR\n...
#!/usr/bin/env python3 """ Statistically generate keywords. Spot the most representative keywords from the learning files. """ import argparse from collections import Counter import gc import hashlib import json import logging from operator import itemgetter from pathlib import Path from guesslang.config import co...
yoeo/guesslang
guesslang/__main__.py
main
python
def main() -> None: try: _real_main() except GuesslangError as error: LOGGER.critical("Failed: %s", error) sys.exit(-1) except KeyboardInterrupt: LOGGER.critical("Cancelled!") sys.exit(-2)
Run command line
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/__main__.py#L19-L28
[ "def _real_main() -> None:\n # Get the arguments\n parser = argparse.ArgumentParser(description=__doc__)\n parser.add_argument(\n '-i', '--input-file', type=argparse.FileType('r'), default=sys.stdin,\n help=\"source code file. Default is standard input (stdin)\")\n parser.add_argument(\n ...
"""Guess the programming language of a given source file""" import argparse import json import logging from pathlib import Path import sys import time from typing import Any, TextIO from guesslang import Guess, GuesslangError, config_logging LOGGER = logging.getLogger(__name__) REPORT_FILENAME = 'report-{}.json' ...
yoeo/guesslang
guesslang/extractor.py
split
python
def split(text: str) -> List[str]: return [word for word in SEPARATOR.split(text) if word.strip(' \t')]
Split a text into a list of tokens. :param text: the text to split :return: tokens
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/guesslang/extractor.py#L34-L40
null
"""Extract features (floats vector) that represent a given text""" import logging import re import math from typing import cast, Dict, Tuple, List from guesslang.config import config_dict LOGGER = logging.getLogger(__name__) CONTENT_SIZE = 2**10 SPECIAL_KEYWORDS = {'num': '<number>', 'var': '<variable>'} KEYWORDS...
yoeo/guesslang
tools/unzip_repos.py
main
python
def main(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('source', help="location of the downloaded repos") parser.add_argument('destination', help="location of the extracted files") parser.add_argument(...
Files extractor command line
train
https://github.com/yoeo/guesslang/blob/03e33b77c73238c0fe4600147e8c926515a2887f/tools/unzip_repos.py#L30-L65
[ "def config_logging(debug: bool = False) -> None:\n \"\"\"Set-up application and `tensorflow` logging.\n\n :param debug: show or hide debug messages\n \"\"\"\n if debug:\n level = 'DEBUG'\n tf_level = tf.logging.INFO\n else:\n level = 'INFO'\n tf_level = tf.logging.ERROR\n...
#!/usr/bin/env python3 """ Extract files from downloaded repositories to prepare Guesslang learning: * testing files and learning files are retrieved from different repositories * they are stored into two different subdirectories * a limited number of files for each language are retrieved per repository """ impo...
moonso/vcf_parser
vcf_parser/utils/build_models.py
build_models_dict
python
def build_models_dict(annotated_models): logger = getLogger(__name__) logger.debug("Parsing models {0}".format(annotated_models) ) parsed_models = {} for family_annotation in annotated_models: family_id = family_annotation.split(':')[0] logger.debug("Parsing family {0}".format(family...
Take a list with annotated genetic inheritance patterns for each family and returns a dictionary with family_id as key and a list of genetic models as value. Args: annotated_models : A list on the form ['1:AD','2:AR_comp|AD_dn'] Returns: parsed_models : A dictionary on...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/build_models.py#L3-L31
null
from logging import getLogger def build_models_dict(annotated_models): """ Take a list with annotated genetic inheritance patterns for each family and returns a dictionary with family_id as key and a list of genetic models as value. Args: annotated_models : A list on the form ['1:AD','2...
moonso/vcf_parser
vcf_parser/utils/split_variants.py
split_variants
python
def split_variants(variant_dict, header_parser, allele_symbol='0'): logger = getLogger(__name__) logger.info("Allele symbol {0}".format(allele_symbol)) alternatives = variant_dict['ALT'].split(',') reference = variant_dict['REF'] number_of_values = 1 # Go through each of the alternative alleles:...
Checks if there are multiple alternative alleles and splitts the variant. If there are multiple alternatives the info fields, vep annotations and genotype calls will be splitted in the correct way Args: variant_dict: a dictionary with the variant information Yields: varia...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/split_variants.py#L13-L120
[ "def build_info_string(info):\n \"\"\"\n Build a new vcf INFO string based on the information in the info_dict.\n\n The info is a dictionary with vcf info keys as keys and lists of vcf values\n as values. If there is no value False is value in info\n\n Args:\n info (dict): A dictionary with in...
import sys from logging import getLogger if sys.version_info < (2, 7): from ordereddict import OrderedDict else: from collections import OrderedDict from vcf_parser import Genotype from vcf_parser.utils import (build_vep_string, split_genotype, build_info_string) def split_variants(variant_dict, header_pars...
moonso/vcf_parser
vcf_parser/utils/rank_scores.py
build_rank_score_dict
python
def build_rank_score_dict(rank_scores): logger = getLogger(__name__) logger.debug("Checking rank scores: {0}".format(rank_scores)) scores = {} for family in rank_scores: entry = family.split(':') try: family_id = entry[0] logger.debug("Extracting rank score for fa...
Take a list with annotated rank scores for each family and returns a dictionary with family_id as key and a list of genetic models as value. Args: rank_scores : A list on the form ['1:12','2:20'] Returns: scores : A dictionary with family id:s as key and scores as value ...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/rank_scores.py#L3-L34
null
from logging import getLogger def build_rank_score_dict(rank_scores): """ Take a list with annotated rank scores for each family and returns a dictionary with family_id as key and a list of genetic models as value. Args: rank_scores : A list on the form ['1:12','2:20'] Returns: ...
moonso/vcf_parser
vcf_parser/utils/check_info.py
check_info_annotation
python
def check_info_annotation(annotation, info, extra_info, alternatives, individuals=[]): number = extra_info['Number'] if is_number(number): number_of_entrys = float(number) if number_of_entrys != 0: if len(annotation) != number_of_entrys: raise SyntaxError("Info f...
Check if the info annotation corresponds to the metadata specification Arguments: annotation (list): The annotation from the vcf file info (str): Name of the info field extra_info (dict): The metadata specification alternatives (list): A list with the alternative variants ...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/check_info.py#L18-L72
[ "def is_number(s):\n \"\"\"\n Take a string and determin if it is a number\n\n Arguments:\n s (str): A string\n\n Returns:\n bool: True if it is a number, False otherwise\n \"\"\"\n try:\n float(s)\n return True\n except ValueError:\n return False\n" ]
def is_number(s): """ Take a string and determin if it is a number Arguments: s (str): A string Returns: bool: True if it is a number, False otherwise """ try: float(s) return True except ValueError: return False def check_info_annotation(annotatio...
moonso/vcf_parser
vcf_parser/utils/format_variant.py
format_variant
python
def format_variant(line, header_parser, check_info=False): logger = getLogger(__name__) individuals = [] vcf_header = header_parser.header individuals = header_parser.individuals variant_line = line.rstrip().split('\t') logger.debug("Checking if variant line is malformed") if len(vcf_he...
Yield the variant in the right format. If the variants should be splitted on alternative alles one variant for each alternative will be yielded. Arguments: line (str): A string that represents a variant line in the vcf format header_parser (HeaderParser): A HeaderParser object ...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/format_variant.py#L10-L137
[ "def check_info_annotation(annotation, info, extra_info, alternatives, individuals=[]):\n \"\"\"\n Check if the info annotation corresponds to the metadata specification\n\n Arguments:\n annotation (list): The annotation from the vcf file\n info (str): Name of the info field\n extra_in...
from __future__ import absolute_import from logging import getLogger from vcf_parser import Genotype from . import (build_info_dict, build_vep_annotation, check_info_annotation, build_compounds_dict, build_rank_score_dict, build_models_dict) def format_variant(line, header_parser, check_info=False): """ Yie...
moonso/vcf_parser
vcf_parser/utils/build_info.py
build_info_string
python
def build_info_string(info): info_list = [] for annotation in info: if info[annotation]: info_list.append('='.join([annotation, ','.join(info[annotation])])) else: info_list.append(annotation) return ';'.join(info_list)
Build a new vcf INFO string based on the information in the info_dict. The info is a dictionary with vcf info keys as keys and lists of vcf values as values. If there is no value False is value in info Args: info (dict): A dictionary with information from the vcf file Returns: ...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/build_info.py#L10-L33
null
import sys import logging if sys.version_info < (2, 7): from ordereddict import OrderedDict else: from collections import OrderedDict def build_info_string(info): """ Build a new vcf INFO string based on the information in the info_dict. The info is a dictionary with vcf info keys as keys and li...
moonso/vcf_parser
vcf_parser/utils/build_info.py
build_info_dict
python
def build_info_dict(vcf_info): logger = logging.getLogger(__name__) logger.debug("Building info dict") info_dict = OrderedDict() for info in vcf_info.split(';'): info = info.split('=') if len(info) > 1: # If the INFO entry is like key=value, we store the value as a list ...
Build a dictionary from the info of a vcf line The dictionary will have the info keys as keys and info values as values. Values will allways be lists that are splitted on ',' Arguments: vcf_info (str): A string with vcf info Returns: info_dict (OrderedDict): A ordered dict...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/build_info.py#L35-L62
null
import sys import logging if sys.version_info < (2, 7): from ordereddict import OrderedDict else: from collections import OrderedDict def build_info_string(info): """ Build a new vcf INFO string based on the information in the info_dict. The info is a dictionary with vcf info keys as keys and li...
moonso/vcf_parser
vcf_parser/utils/split_genotype.py
split_genotype
python
def split_genotype(genotype, gt_format, alternative_number, allele_symbol = '0'): logger = getLogger(__name__) logger.info("Allele symbol {0}".format(allele_symbol)) splitted_genotype = genotype.split(':') logger.debug("Parsing genotype {0}".format(splitted_genotype)) splitted_gt_format = gt_f...
Take a genotype call and make a new one that is working for the new splitted variant Arguments: genotype (str): The original genotype call gt_format (str): The format of the gt call alternative_number (int): What genotype call should we return allele_symbol (str): How should...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/split_genotype.py#L3-L92
null
from logging import getLogger def split_genotype(genotype, gt_format, alternative_number, allele_symbol = '0'): """ Take a genotype call and make a new one that is working for the new splitted variant Arguments: genotype (str): The original genotype call gt_format (str): The format of ...
moonso/vcf_parser
vcf_parser/header_parser.py
HeaderParser.parse_header_line
python
def parse_header_line(self, line): self.header = line[1:].rstrip().split('\t') if len(self.header) < 9: self.header = line[1:].rstrip().split() self.individuals = self.header[9:]
docstring for parse_header_line
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L178-L183
null
class HeaderParser(object): """Parses a file with family info and creates a family object with individuals.""" def __init__(self): super(HeaderParser, self).__init__() self.logger = getLogger(__name__) self.info_lines=[] self.info_dict=OrderedDict() #This is a dictionary ...
moonso/vcf_parser
vcf_parser/header_parser.py
HeaderParser.print_header
python
def print_header(self): lines_to_print = [] lines_to_print.append('##fileformat='+self.fileformat) if self.filedate: lines_to_print.append('##fileformat='+self.fileformat) for filt in self.filter_dict: lines_to_print.append(self.filter_dict[filt]) ...
Returns a list with the header lines if proper format
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L185-L205
null
class HeaderParser(object): """Parses a file with family info and creates a family object with individuals.""" def __init__(self): super(HeaderParser, self).__init__() self.logger = getLogger(__name__) self.info_lines=[] self.info_dict=OrderedDict() #This is a dictionary ...
moonso/vcf_parser
vcf_parser/header_parser.py
HeaderParser.add_info
python
def add_info(self, info_id, number, entry_type, description): info_line = '##INFO=<ID={0},Number={1},Type={2},Description="{3}">'.format( info_id, number, entry_type, description ) self.logger.info("Adding info line to vcf: {0}".format(info_line)) self.parse_meta_data(info_li...
Add an info line to the header. Arguments: info_id (str): The id of the info line number (str): Integer or any of [A,R,G,.] entry_type (str): Any of [Integer,Float,Flag,Character,String] description (str): A description of the info line
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L238-L254
[ "def parse_meta_data(self, line):\n \"\"\"Parse a vcf metadataline\"\"\"\n line = line.rstrip()\n line_info = line[2:].split('=')\n match = False\n\n if line_info[0] == 'fileformat':\n try:\n self.fileformat = line_info[1]\n except IndexError:\n raise SyntaxError(\...
class HeaderParser(object): """Parses a file with family info and creates a family object with individuals.""" def __init__(self): super(HeaderParser, self).__init__() self.logger = getLogger(__name__) self.info_lines=[] self.info_dict=OrderedDict() #This is a dictionary ...
moonso/vcf_parser
vcf_parser/header_parser.py
HeaderParser.add_version_tracking
python
def add_version_tracking(self, info_id, version, date, command_line=''): other_line = '##Software=<ID={0},Version={1},Date="{2}",CommandLineOptions="{3}">'.format( info_id, version, date, command_line) self.other_dict[info_id] = other_line return
Add a line with information about which software that was run and when to the header. Arguments: info_id (str): The id of the info line version (str): The version of the software used date (str): Date when software was run command_line (str): The...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/header_parser.py#L338-L353
null
class HeaderParser(object): """Parses a file with family info and creates a family object with individuals.""" def __init__(self): super(HeaderParser, self).__init__() self.logger = getLogger(__name__) self.info_lines=[] self.info_dict=OrderedDict() #This is a dictionary ...
moonso/vcf_parser
vcf_parser/utils/build_compounds.py
build_compounds_dict
python
def build_compounds_dict(compounds): logger = getLogger(__name__) logger.debug("Parsing compounds: {0}".format(compounds)) parsed_compounds = {} for family_info in compounds: logger.debug("Parsing entry {0}".format(family_info)) splitted_family_info = family_info.split(':') ...
Take a list with annotated compound variants for each family and returns a dictionary with family_id as key and a list of dictionarys that holds the information about the compounds. Args: compounds : A list that can be either on the form [ ...
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/utils/build_compounds.py#L3-L66
null
from logging import getLogger def build_compounds_dict(compounds): """ Take a list with annotated compound variants for each family and returns a dictionary with family_id as key and a list of dictionarys that holds the information about the compounds. Args: compounds : A list that can...
moonso/vcf_parser
vcf_parser/cli/command_line.py
cli
python
def cli(variant_file, vep, split, outfile, verbose, silent, check_info, allele_symbol, logfile, loglevel): from vcf_parser import logger, init_log if not loglevel: if verbose: loglevel = 'INFO' init_log(logger, logfile, loglevel) nr_of_variants = 0 start = datetime.now(...
Tool for parsing vcf files. Prints the vcf file to output. If --split/-s is used all multiallelic calls will be splitted and printed as single variant calls. For more information, please see github.com/moonso/vcf_parser.
train
https://github.com/moonso/vcf_parser/blob/8e2b6724e31995e0d43af501f25974310c6b843b/vcf_parser/cli/command_line.py#L93-L163
[ "def init_log(logger, filename=None, loglevel=None):\n \"\"\"\n Initializes the log file in the proper format.\n\n Arguments:\n\n filename (str): Path to a file. Or None if logging is to\n be disabled.\n loglevel (str): Determines the level of the log output.\n \"\"...
#!/usr/bin/env python # encoding: utf-8 """ vcf_parser Command Line Interface for vcf_parser Created by Måns Magnusson on 2014-12-12. Copyright (c) 2014 __MoonsoInc__. All rights reserved. """ from __future__ import print_function import sys import os import click from pprint import pprint as pp from datetime impo...