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
beregond/super_state_machine
super_state_machine/utils.py
generate_checker
python
def generate_checker(value): @property @wraps(can_be_) def checker(self): return self.can_be_(value) return checker
Generate state checker for given value.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L74-L81
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def ca...
beregond/super_state_machine
super_state_machine/utils.py
generate_setter
python
def generate_setter(value): @wraps(set_) def setter(self): self.set_(value) return setter
Generate setter for given value.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L84-L90
null
"""Utilities for core.""" from enum import Enum, unique from functools import wraps from .errors import TransitionError def is_(self, state): """Check if machine is in given state.""" translator = self._meta['translator'] state = translator.translate(state) return self.actual_state == state def ca...
beregond/super_state_machine
super_state_machine/utils.py
EnumValueTranslator.translate
python
def translate(self, value): if self._check_if_already_proper(value): return value try: return self.search_table[value] except KeyError: raise ValueError("Value {value} doesn't match any state.".format( value=value ))
Translate value to enum instance. If value is already enum instance, check if this value belongs to base enum.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/utils.py#L127-L142
[ "def _check_if_already_proper(self, value):\n if isinstance(value, Enum):\n if value in self.base_enum:\n return True\n raise ValueError(\n \"Given value ('{value}') doesn't belong to states enum.\"\n .format(value=value)\n )\n return False\n" ]
class EnumValueTranslator(object): """Helps to find enum element by its value.""" def __init__(self, base_enum): """Init. :param enum base_enum: Enum, to which elements values are translated. """ base_enum = unique(base_enum) self.base_enum = base_enum self.ge...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._set_up_context
python
def _set_up_context(cls): cls.context = AttributeDict() cls.context.new_meta = {} cls.context.new_transitions = {} cls.context.new_methods = {}
Create context to keep all needed variables in.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L64-L69
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._check_states_enum
python
def _check_states_enum(cls): states_enum_name = cls.context.get_config('states_enum_name') try: cls.context['states_enum'] = getattr( cls.context.new_class, states_enum_name) except AttributeError: raise ValueError('No states enum given!') proper ...
Check if states enum exists and is proper one.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L72-L90
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._check_if_states_are_strings
python
def _check_if_states_are_strings(cls): for item in list(cls.context.states_enum): if not isinstance(item.value, six.string_types): raise ValueError( 'Item {name} is not string. Only strings are allowed.' .format(name=item.name) ...
Check if all states are strings.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L93-L100
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._check_state_value
python
def _check_state_value(cls): state_value = cls.context.get_config('initial_state', None) state_value = state_value or getattr( cls.context.new_class, cls.context.state_name, None ) if not state_value: raise ValueError( "Empty state is disallowed, ...
Check initial state value - if is proper and translate it. Initial state is required.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L103-L122
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._add_standard_attributes
python
def _add_standard_attributes(cls): setattr( cls.context.new_class, cls.context.new_meta['state_attribute_name'], cls.context.state_value) setattr( cls.context.new_class, cls.context.state_name, utils.state_property) setattr...
Add attributes common to all state machines. These are methods for setting and checking state etc.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L125-L142
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._generate_standard_transitions
python
def _generate_standard_transitions(cls): allowed_transitions = cls.context.get_config('transitions', {}) for key, transitions in allowed_transitions.items(): key = cls.context.new_meta['translator'].translate(key) new_transitions = set() for trans in transitions: ...
Generate methods used for transitions.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L145-L161
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._generate_standard_methods
python
def _generate_standard_methods(cls): for state in cls.context.states_enum: getter_name = 'is_{name}'.format(name=state.value) cls.context.new_methods[getter_name] = utils.generate_getter(state) setter_name = 'set_{name}'.format(name=state.value) cls.context.new_m...
Generate standard setters, getters and checkers.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L164-L179
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._add_new_methods
python
def _add_new_methods(cls): for name, method in cls.context.new_methods.items(): if hasattr(cls.context.new_class, name): raise ValueError( "Name collision in state machine class - '{name}'." .format(name) ) setattr(...
Add all generated methods to result class.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L235-L244
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
beregond/super_state_machine
super_state_machine/machines.py
StateMachineMetaclass._set_complete_option
python
def _set_complete_option(cls): get_config = cls.context.get_config complete = get_config('complete', None) if complete is None: conditions = [ get_config('transitions', False), get_config('named_transitions', False), ] complete ...
Check and set complete option.
train
https://github.com/beregond/super_state_machine/blob/31ad527f4e6b7a01e315ce865735ca18957c223e/super_state_machine/machines.py#L247-L258
null
class StateMachineMetaclass(type): """Metaclass for state machine, to build all its logic.""" def __new__(cls, name, bases, attrs): """Create state machine and add all logic and methods to it.""" cls._set_up_context() new_class = super(cls, cls).__new__(cls, name, bases, attrs) ...
codeforamerica/three
three/api.py
city
python
def city(name=None): info = find_info(name) os.environ['OPEN311_CITY_INFO'] = dumps(info) return Three(**info)
Store the city that will be queried against. >>> three.city('sf')
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L23-L31
[ "def find_info(name=None):\n \"\"\"Find the needed city server information.\"\"\"\n if not name:\n return list(servers.keys()) \n name = name.lower()\n if name in servers:\n info = servers[name]\n else:\n raise CityNotFound(\"Could not find the specified city: %s\" % name)\n r...
""" Simple, top-level functions for working with the Open311 API. """ import os from simplejson import dumps from .cities import find_info from .core import Three def key(key=None): """ Save your API key to the global environment. >>> three.api_key('my_api_key') """ if key: os.environ['...
codeforamerica/three
three/api.py
dev
python
def dev(endpoint, **kwargs): kwargs['endpoint'] = endpoint os.environ['OPEN311_CITY_INFO'] = dumps(kwargs) return Three(**kwargs)
Use an endpoint and any additional keyword arguments rather than one of the pre-defined cities. Similar to the `city` function, but useful for development.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/api.py#L40-L48
null
""" Simple, top-level functions for working with the Open311 API. """ import os from simplejson import dumps from .cities import find_info from .core import Three def key(key=None): """ Save your API key to the global environment. >>> three.api_key('my_api_key') """ if key: os.environ['...
codeforamerica/three
three/cities.py
find_info
python
def find_info(name=None): if not name: return list(servers.keys()) name = name.lower() if name in servers: info = servers[name] else: raise CityNotFound("Could not find the specified city: %s" % name) return info
Find the needed city server information.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/cities.py#L10-L19
null
""" A dict of information needed to query city Open311 servers. """ class CityNotFound(Exception): pass servers = { 'bainbridge': { 'endpoint': 'http://seeclickfix.com/bainbridge-island/open311/' }, 'baltimore': { 'endpoint': 'http://311.baltimorecity.gov/open311/v2/' }, 'bl...
codeforamerica/three
three/core.py
Three.configure
python
def configure(self, endpoint=None, **kwargs): if endpoint: kwargs['endpoint'] = endpoint keywords = self._keywords.copy() keywords.update(kwargs) if 'endpoint' in kwargs: # Then we need to correctly format the endpoint. endpoint = kwargs['endpoint'] ...
Configure a previously initialized instance of the class.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L66-L87
[ "def _global_api_key(self):\n \"\"\"\n If a global Open311 API key is available as an environment variable,\n then it will be used when querying.\n \"\"\"\n if 'OPEN311_API_KEY' in os.environ:\n api_key = os.environ['OPEN311_API_KEY']\n else:\n api_key = ''\n return api_key\n", ...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three._configure_endpoint
python
def _configure_endpoint(self, endpoint): if not endpoint.startswith('http'): endpoint = 'https://' + endpoint if not endpoint.endswith('/'): endpoint += '/' return endpoint
Configure the endpoint with a schema and end slash.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L89-L95
null
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.get
python
def get(self, *args, **kwargs): if 'convert' in kwargs: conversion = kwargs.pop('convert') else: conversion = True kwargs = self._get_keywords(**kwargs) url = self._create_path(*args) request = self.session.get(url, params=kwargs) content = request...
Perform a get request.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L107-L118
[ "def _create_path(self, *args):\n \"\"\"Create URL path for endpoint and args.\"\"\"\n args = filter(None, args)\n path = self.endpoint + '/'.join(args) + '.%s' % (self.format)\n return path\n", "def _get_keywords(self, **kwargs):\n \"\"\"Format GET request parameters and keywords.\"\"\"\n if se...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three._get_keywords
python
def _get_keywords(self, **kwargs): if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'count' in kwargs: kwargs['page_size'] = kwargs.pop('count') if 'start' in kwargs: start = kwargs.pop('start') ...
Format GET request parameters and keywords.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L120-L140
null
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three._format_dates
python
def _format_dates(self, start, end): start = self._split_date(start) end = self._split_date(end) return start, end
Format start and end dates.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L142-L146
null
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three._split_date
python
def _split_date(self, time): if isinstance(time, str): month, day, year = [int(t) for t in re.split(r'-|/', time)] if year < 100: # Quick hack for dates < 2000. year += 2000 time = date(year, month, day) return time.strftime('%Y-%m-%dT%...
Split apart a date string.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L148-L156
null
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.convert
python
def convert(self, content, conversion): if not conversion: data = content elif self.format == 'json': data = json.loads(content) elif self.format == 'xml': content = xml(content) first = list(content.keys())[0] data = content[first] ...
Convert content to Python data structures.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L158-L170
null
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.discovery
python
def discovery(self, url=None): if url: data = self.session.get(url).content elif self.discovery_url: response = self.session.get(self.discovery_url) if self.format == 'xml': # Because, SF doesn't follow the spec. data = xml(response.tex...
Retrieve the standard discovery file that provides routing information. >>> Three().discovery() {'discovery': 'data'}
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L172-L192
[ "def get(self, *args, **kwargs):\n \"\"\"Perform a get request.\"\"\"\n if 'convert' in kwargs:\n conversion = kwargs.pop('convert')\n else:\n conversion = True\n kwargs = self._get_keywords(**kwargs)\n url = self._create_path(*args)\n request = self.session.get(url, params=kwargs)\n...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.services
python
def services(self, code=None, **kwargs): data = self.get('services', code, **kwargs) return data
Retrieve information about available services. You can also enter a specific service code argument. >>> Three().services() {'all': {'service_code': 'data'}} >>> Three().services('033') {'033': {'service_code': 'data'}}
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L194-L205
[ "def get(self, *args, **kwargs):\n \"\"\"Perform a get request.\"\"\"\n if 'convert' in kwargs:\n conversion = kwargs.pop('convert')\n else:\n conversion = True\n kwargs = self._get_keywords(**kwargs)\n url = self._create_path(*args)\n request = self.session.get(url, params=kwargs)\n...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.requests
python
def requests(self, code=None, **kwargs): if code: kwargs['service_code'] = code data = self.get('requests', **kwargs) return data
Retrieve open requests. You can also enter a specific service code argument. >>> Three('api.city.gov').requests() {'all': {'requests': 'data'}} >>> Three('api.city.gov').requests('123') {'123': {'requests': 'data'}}
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L207-L220
[ "def get(self, *args, **kwargs):\n \"\"\"Perform a get request.\"\"\"\n if 'convert' in kwargs:\n conversion = kwargs.pop('convert')\n else:\n conversion = True\n kwargs = self._get_keywords(**kwargs)\n url = self._create_path(*args)\n request = self.session.get(url, params=kwargs)\n...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.request
python
def request(self, id, **kwargs): data = self.get('requests', id, **kwargs) return data
Retrieve a specific request using its service code ID. >>> Three('api.city.gov').request('12345') {'request': {'service_code': {'12345': 'data'}}}
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L222-L230
[ "def get(self, *args, **kwargs):\n \"\"\"Perform a get request.\"\"\"\n if 'convert' in kwargs:\n conversion = kwargs.pop('convert')\n else:\n conversion = True\n kwargs = self._get_keywords(**kwargs)\n url = self._create_path(*args)\n request = self.session.get(url, params=kwargs)\n...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.post
python
def post(self, service_code='0', **kwargs): kwargs['service_code'] = service_code kwargs = self._post_keywords(**kwargs) media = kwargs.pop('media', None) if media: files = {'media': media} else: files = None url = self._create_path('requests') ...
Post a new Open311 request. >>> t = Three('api.city.gov') >>> t.post('123', address='123 Any St', name='Zach Williams', ... phone='555-5555', description='My issue description.', ... media=open('photo.png', 'rb')) {'successful': {'request': 'post'}}
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L232-L257
[ "def _create_path(self, *args):\n \"\"\"Create URL path for endpoint and args.\"\"\"\n args = filter(None, args)\n path = self.endpoint + '/'.join(args) + '.%s' % (self.format)\n return path\n", "def convert(self, content, conversion):\n \"\"\"Convert content to Python data structures.\"\"\"\n i...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three._post_keywords
python
def _post_keywords(self, **kwargs): if self.jurisdiction and 'jurisdiction_id' not in kwargs: kwargs['jurisdiction_id'] = self.jurisdiction if 'address' in kwargs: address = kwargs.pop('address') kwargs['address_string'] = address if 'name' in kwargs: ...
Configure keyword arguments for Open311 POST requests.
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L259-L272
null
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
codeforamerica/three
three/core.py
Three.token
python
def token(self, id, **kwargs): data = self.get('tokens', id, **kwargs) return data
Retrieve a service request ID from a token. >>> Three('api.city.gov').token('12345') {'service_request_id': {'for': {'token': '12345'}}}
train
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L274-L282
[ "def get(self, *args, **kwargs):\n \"\"\"Perform a get request.\"\"\"\n if 'convert' in kwargs:\n conversion = kwargs.pop('convert')\n else:\n conversion = True\n kwargs = self._get_keywords(**kwargs)\n url = self._create_path(*args)\n request = self.session.get(url, params=kwargs)\n...
class Three(object): """The main class for interacting with the Open311 API.""" def __init__(self, endpoint=None, **kwargs): keywords = defaultdict(str) keywords.update(kwargs) if endpoint: endpoint = self._configure_endpoint(endpoint) keywords['endpoint'] = endp...
malramsay64/experi
src/experi/scheduler.py
parse_setup
python
def parse_setup(options: Union[List, str]) -> str: if isinstance(options, str): return options return "\n".join(options)
Convert potentially a list of commands into a single string. This creates a single string with newlines between each element of the list so that they will all run after each other in a bash script.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/scheduler.py#L267-L276
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Generate scheduler files for submission on batch systems. This will generate a .pbs file with all the information required to run a single comm...
malramsay64/experi
src/experi/scheduler.py
create_scheduler_file
python
def create_scheduler_file(scheduler: str, job: Job) -> str: logger.debug("Create Scheduler File Function") if job.scheduler_options is None: scheduler_options: Dict[str, Any] = {} else: scheduler_options = deepcopy(job.scheduler_options) try: setup_string = parse_setup(scheduler...
Substitute values into a template scheduler file.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/scheduler.py#L304-L333
[ "def parse_setup(options: Union[List, str]) -> str:\n \"\"\"Convert potentially a list of commands into a single string.\n\n This creates a single string with newlines between each element of the list\n so that they will all run after each other in a bash script.\n\n \"\"\"\n if isinstance(options, s...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Generate scheduler files for submission on batch systems. This will generate a .pbs file with all the information required to run a single comm...
malramsay64/experi
src/experi/commands.py
Command.get_variables
python
def get_variables(self) -> Set[str]: variables = set() for cmd in self._cmd: for var in self.__formatter.parse(cmd): logger.debug("Checking variable: %s", var) # creates and requires are special class values if var[1] is not None and var[1] not...
Find all the variables specified in a format string. This returns a list of all the different variables specified in a format string, that is the variables inside the braces.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/commands.py#L53-L67
null
class Command: """A command to be run for an experiment.""" _cmd: List[str] variables: Dict[str, Any] _creates: str = "" _requires: str = "" __formatter = Formatter() def __init__( self, cmd: Union[List[str], str], variables: Dict[str, Any] = None, creates: ...
malramsay64/experi
src/experi/commands.py
Job.as_bash_array
python
def as_bash_array(self) -> str: return_string = "( \\\n" for command in self: return_string += '"' + str(command) + '" \\\n' return_string += ")" return return_string
Return a representation as a bash array. This creates a string formatted as a bash array containing all the commands in the job.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/commands.py#L140-L150
null
class Job: """A task to perform within a simulation.""" commands: List[Command] shell: str = "bash" scheduler_options: Optional[Dict[str, Any]] = None use_dependencies: bool = False directory: Optional[Path] = None def __init__( self, commands, scheduler_options=None, directory=Non...
malramsay64/experi
src/experi/run.py
combine_dictionaries
python
def combine_dictionaries(dicts: List[Dict[str, Any]]) -> Dict[str, Any]: return dict(ChainMap(*dicts))
Merge a list of dictionaries into a single dictionary. Where there are collisions the first value in the list will be set as this function is using ChainMap to combine the dicts.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L39-L46
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
iterator_zip
python
def iterator_zip(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: logger.debug("Yielding from zip iterator") if isinstance(variables, list): for item in variables: yield list(variable_matrix(item, parent, "zip")) else: yield list(variable_matrix(variables, parent,...
Apply the zip operator to a set of variables. This uses the python zip iterator to combine multiple lists of variables such that the nth variable in each list is aligned. Args: variables: The variables object parent: Unused
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L49-L66
[ "def variable_matrix(\n variables: VarType, parent: str = None, iterator: str = \"product\"\n) -> Iterable[Dict[str, YamlValue]]:\n \"\"\"Process the variables into a list of the appropriate combinations.\n\n This function performs recursive processing of the input variables, creating an\n iterator whic...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
iterator_product
python
def iterator_product(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: logger.debug("Yielding from product iterator") if isinstance(variables, list): raise ValueError( f"Product only takes mappings of values, got {variables} of type {type(variables)}" ) yield list(...
Apply the product operator to a set of variables. This uses the python itertools.product iterator to combine multiple variables such that all possible combinations are generated. This is the default iterator however this is a method of manually specifying the option. Args: variables: The varia...
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L69-L87
[ "def variable_matrix(\n variables: VarType, parent: str = None, iterator: str = \"product\"\n) -> Iterable[Dict[str, YamlValue]]:\n \"\"\"Process the variables into a list of the appropriate combinations.\n\n This function performs recursive processing of the input variables, creating an\n iterator whic...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
iterator_chain
python
def iterator_chain(variables: VarType, parent: str = None) -> Iterable[VarMatrix]: logger.debug("Yielding from append iterator") if not isinstance(variables, list): raise ValueError( f"Append keyword only takes a list of arguments, got {variables} of type {type(variables)}" ) # ...
This successively appends each element of an array to a single list of values. This takes a list of values and puts all the values generated for each element in the list into a single list of values. It uses the :func:`itertools.chain` function to achieve this. This function is particularly useful for spec...
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L90-L114
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
iterator_arange
python
def iterator_arange(variables: VarType, parent: str) -> Iterable[VarMatrix]: assert parent is not None if isinstance(variables, (int, float)): yield [{parent: i} for i in np.arange(variables)] elif isinstance(variables, dict): if variables.get("stop"): yield [{parent: i} for i i...
Create a list of values using the :func:`numpy.arange` function. Args: variables: The input variables for the creation of the range parent: The variable for which the values are being generated. Returns: A list of dictionaries mapping the parent to each value.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L123-L146
[ "def arange(start=None, stop=None, step=None, dtype=None) -> np.ndarray:\n if stop and not start:\n return np.arange(stop)\n return np.arange(start=start, stop=stop, step=step, dtype=dtype)\n" ]
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
iterator_cycle
python
def iterator_cycle(variables: VarType, parent: str) -> Iterable[VarMatrix]: if isinstance(variables, dict): if variables.get("times"): times = int(variables["times"]) del variables["times"] yield list(variable_matrix(variables, parent, "product")) * times else: ...
Cycle through a list of values a specified number of times Args: variables: The input variables for the creation of the range parent: The variable for which the values are being generated. Returns: A list of dictionaries mapping the parent to each value.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L149-L171
[ "def variable_matrix(\n variables: VarType, parent: str = None, iterator: str = \"product\"\n) -> Iterable[Dict[str, YamlValue]]:\n \"\"\"Process the variables into a list of the appropriate combinations.\n\n This function performs recursive processing of the input variables, creating an\n iterator whic...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
variable_matrix
python
def variable_matrix( variables: VarType, parent: str = None, iterator: str = "product" ) -> Iterable[Dict[str, YamlValue]]: _iters: Dict[str, Callable] = {"product": product, "zip": zip} _special_keys: Dict[str, Callable[[VarType, Any], Iterable[VarMatrix]]] = { "zip": iterator_zip, "product...
Process the variables into a list of the appropriate combinations. This function performs recursive processing of the input variables, creating an iterator which has all the combinations of variables specified in the input.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L174-L226
[ "def variable_matrix(\n variables: VarType, parent: str = None, iterator: str = \"product\"\n) -> Iterable[Dict[str, YamlValue]]:\n \"\"\"Process the variables into a list of the appropriate combinations.\n\n This function performs recursive processing of the input variables, creating an\n iterator whic...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
uniqueify
python
def uniqueify(my_list: Any) -> List[Any]: if sys.version_info >= (3, 6): # An implementation specific detail of py3.6 is the retention of order # within a dictionary. In py3.7 this becomes the documented behaviour. return list(dict.fromkeys(my_list)) # Slower method of order preserving ...
Remove duplicate entries in a list retaining order.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L229-L238
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
process_command
python
def process_command(command: CommandInput, matrix: VarMatrix) -> List[Command]: assert command is not None if isinstance(command, str): command_list = [Command(command, variables=variables) for variables in matrix] elif isinstance(command, list): command_list = [Command(command, variables=va...
Generate all combinations of commands given a variable matrix. Processes the commands to be sequences of strings.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L263-L286
[ "def uniqueify(my_list: Any) -> List[Any]:\n \"\"\"Remove duplicate entries in a list retaining order.\"\"\"\n if sys.version_info >= (3, 6):\n # An implementation specific detail of py3.6 is the retention of order\n # within a dictionary. In py3.7 this becomes the documented behaviour.\n ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
read_file
python
def read_file(filename: PathLike = "experiment.yml") -> Dict[str, Any]: logger.debug("Input file: %s", filename) with open(filename, "r") as stream: structure = yaml.safe_load(stream) return structure
Read and parse yaml file.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L289-L295
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
run_bash_jobs
python
def run_bash_jobs( jobs: Iterator[Job], directory: PathLike = Path.cwd(), dry_run: bool = False ) -> None: logger.debug("Running commands in bash shell") # iterate through command groups for job in jobs: # Check shell exists if shutil.which(job.shell) is None: raise ProcessLo...
Submit commands to the bash shell. This function runs the commands iteratively but handles errors in the same way as with the pbs_commands function. A command will run for all combinations of variables in the variable matrix, however if any one of those commands fails then the next command will not run...
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L361-L395
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
run_scheduler_jobs
python
def run_scheduler_jobs( scheduler: str, jobs: Iterator[Job], directory: PathLike = Path.cwd(), basename: str = "experi", dry_run: bool = False, ) -> None: submit_job = True logger.debug("Creating commands in %s files.", scheduler) # Check scheduler submit command exists if scheduler...
Submit a series of commands to a batch scheduler. This takes a list of strings which are the contents of the pbs files, writes the files to disk and submits the job to the scheduler. Files which match the pattern of the resulting files <basename>_<index>.pbs are deleted before writing the new files. T...
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L398-L483
[ "def create_scheduler_file(scheduler: str, job: Job) -> str:\n \"\"\"Substitute values into a template scheduler file.\"\"\"\n logger.debug(\"Create Scheduler File Function\")\n\n if job.scheduler_options is None:\n scheduler_options: Dict[str, Any] = {}\n else:\n scheduler_options = deepc...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
malramsay64/experi
src/experi/run.py
determine_scheduler
python
def determine_scheduler( scheduler: Optional[str], experiment_definition: Dict[str, YamlValue] ) -> str: # Scheduler value from command line has first priority if scheduler is not None: if scheduler in ["shell", "pbs", "slurm"]: return scheduler raise ValueError( "Ar...
Determine the scheduler to use to run the jobs.
train
https://github.com/malramsay64/experi/blob/7159644df0420e4a395c87c0c08e11567f401443/src/experi/run.py#L486-L514
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 Malcolm Ramsay <malramsay64@gmail.com> # # Distributed under terms of the MIT license. """Run an experiment varying a number of variables.""" import logging import os import shutil import subprocess import sys from collections import...
numan/py-analytics
analytics/backends/redis.py
Redis._get_closest_week
python
def _get_closest_week(self, metric_date): #find the offset to the closest monday days_after_monday = metric_date.isoweekday() - 1 return metric_date - datetime.timedelta(days=days_after_monday)
Gets the closest monday to the date provided.
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L58-L65
null
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis._get_daily_date_range
python
def _get_daily_date_range(self, metric_date, delta): dates = [metric_date] start_date = metric_date end_date = metric_date + delta while start_date.month < end_date.month or start_date.year < end_date.year: days_in_month = calendar.monthrange(start_date.year, start_date.mont...
Get the range of months that we need to use as keys to scan redis.
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L97-L112
null
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis._get_weekly_date_range
python
def _get_weekly_date_range(self, metric_date, delta): dates = [metric_date] end_date = metric_date + delta #Figure out how many years our metric range spans spanning_years = end_date.year - metric_date.year for i in range(spanning_years): #for the weekly keys, we only...
Gets the range of years that we need to use as keys to get metrics from redis.
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L114-L127
null
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.clear_all
python
def clear_all(self): keys = self._analytics_backend.keys() for key in itertools.chain(*keys): with self._analytics_backend.map() as conn: if key.startswith(self._prefix): conn.delete(key)
Deletes all ``sandsnake`` related data from redis. .. warning:: Very expensive and destructive operation. Use with causion
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L151-L164
null
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.track_count
python
def track_count(self, unique_identifier, metric, inc_amt=1, **kwargs): return self._analytics_backend.incr(self._prefix + ":" + "analy:%s:count:%s" % (unique_identifier, metric), inc_amt)
Tracks a metric just by count. If you track a metric this way, you won't be able to query the metric by day, week or month. :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want to track :param inc_amt: The...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L166-L176
null
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.track_metric
python
def track_metric(self, unique_identifier, metric, date=None, inc_amt=1, **kwargs): metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_identifier ...
Tracks a metric for a specific ``unique_identifier`` for a certain date. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowing for tracking of multiple metrics for multiple unique_identifiers efficiently. Not all backends may support this. :param unique_identif...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L178-L216
[ "def _get_closest_week(self, metric_date):\n \"\"\"\n Gets the closest monday to the date provided.\n \"\"\"\n #find the offset to the closest monday\n days_after_monday = metric_date.isoweekday() - 1\n\n return metric_date - datetime.timedelta(days=days_after_monday)\n", "def _get_daily_metric_...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.get_metric_by_day
python
def get_metric_by_day(self, unique_identifier, metric, from_date, limit=30, **kwargs): conn = kwargs.get("connection", None) date_generator = (from_date + datetime.timedelta(days=i) for i in itertools.count()) metric_key_date_range = self._get_daily_date_range(from_date, datetime.timedelta(days=...
Returns the ``metric`` for ``unique_identifier`` segmented by day starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want to track :param from_date: A python date object :pa...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L218-L246
[ "def _get_daily_date_range(self, metric_date, delta):\n \"\"\"\n Get the range of months that we need to use as keys to scan redis.\n \"\"\"\n dates = [metric_date]\n start_date = metric_date\n end_date = metric_date + delta\n\n while start_date.month < end_date.month or start_date.year < end_d...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.get_metric_by_week
python
def get_metric_by_week(self, unique_identifier, metric, from_date, limit=10, **kwargs): conn = kwargs.get("connection", None) closest_monday_from_date = self._get_closest_week(from_date) metric_key_date_range = self._get_weekly_date_range(closest_monday_from_date, datetime.timedelta(weeks=limit)...
Returns the ``metric`` for ``unique_identifier`` segmented by week starting from``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want to track :param from_date: A python date object :p...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L248-L278
[ "def _get_closest_week(self, metric_date):\n \"\"\"\n Gets the closest monday to the date provided.\n \"\"\"\n #find the offset to the closest monday\n days_after_monday = metric_date.isoweekday() - 1\n\n return metric_date - datetime.timedelta(days=days_after_monday)\n", "def _get_weekly_date_r...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.get_metric_by_month
python
def get_metric_by_month(self, unique_identifier, metric, from_date, limit=10, **kwargs): conn = kwargs.get("connection", None) first_of_month = datetime.date(year=from_date.year, month=from_date.month, day=1) metric_key_date_range = self._get_weekly_date_range( first_of_month, relati...
Returns the ``metric`` for ``unique_identifier`` segmented by month starting from``from_date``. It will retrieve metrics data starting from the 1st of the month specified in ``from_date`` :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A ...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L280-L313
[ "def _get_weekly_date_range(self, metric_date, delta):\n \"\"\"\n Gets the range of years that we need to use as keys to get metrics from redis.\n \"\"\"\n dates = [metric_date]\n end_date = metric_date + delta\n #Figure out how many years our metric range spans\n spanning_years = end_date.year...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.get_metrics
python
def get_metrics(self, metric_identifiers, from_date, limit=10, group_by="week", **kwargs): results = [] #validation of types: allowed_types = { "day": self.get_metric_by_day, "week": self.get_metric_by_week, "month": self.get_metric_by_month, } ...
Retrieves a multiple metrics as efficiently as possible. :param metric_identifiers: a list of tuples of the form `(unique_identifier, metric_name`) identifying which metrics to retrieve. For example [('user:1', 'people_invited',), ('user:2', 'people_invited',), ('user:1', 'comments_posted',), ('user:2'...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L315-L344
null
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.get_count
python
def get_count(self, unique_identifier, metric, start_date=None, end_date=None, **kwargs): result = None if start_date and end_date: start_date, end_date = (start_date, end_date,) if start_date < end_date else (end_date, start_date,) start_date = start_date if hasattr(start_date,...
Gets the count for the ``metric`` for ``unique_identifier``. You can specify a ``start_date`` and an ``end_date``, to only get metrics within that time range. :param unique_identifier: Unique string indetifying the object this metric is for :param metric: A unique name for the metric you want t...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L346-L389
[ "def _parse_and_process_metrics(self, series, list_of_metrics):\n formatted_result_list = []\n series = [dt.strftime(\"%Y-%m-%d\") for dt in series]\n for result in list_of_metrics:\n values = {}\n for index, date_string in enumerate(series):\n values[date_string] = int(result[inde...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.get_counts
python
def get_counts(self, metric_identifiers, **kwargs): parsed_results = [] results = [ self.get_count(unique_identifier, metric, **kwargs) for unique_identifier, metric in metric_identifiers] for result in results: try: parsed_result = int(result...
Retrieves a multiple metrics as efficiently as possible. :param metric_identifiers: a list of tuples of the form `(unique_identifier, metric_name`) identifying which metrics to retrieve. For example [('user:1', 'people_invited',), ('user:2', 'people_invited',), ('user:1', 'comments_posted',), ('user:2'...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L391-L411
null
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.set_metric_by_day
python
def set_metric_by_day(self, unique_identifier, metric, date, count, sync_agg=True, update_counter=True): metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) e...
Sets the count for the ``metric`` for ``unique_identifier``. You must specify a ``date`` for the ``count`` to be set on. Useful for resetting a metric count to 0 or decrementing a metric. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowing for the setting of ...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L413-L448
[ "def _get_daily_metric_key(self, unique_identifier, metric_date):\n \"\"\"\n Redis key for daily metric\n \"\"\"\n return self._prefix + \":\" + \"user:%s:analy:%s\" % (unique_identifier, metric_date.strftime(\"%y-%m\"),)\n", "def _get_daily_metric_name(self, metric, metric_date):\n \"\"\"\n Has...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.sync_agg_metric
python
def sync_agg_metric(self, unique_identifier, metric, start_date, end_date): self.sync_week_metric(unique_identifier, metric, start_date, end_date) self.sync_month_metric(unique_identifier, metric, start_date, end_date)
Uses the count for each day in the date range to recalculate the counters for the associated weeks and months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day. The redis backend supports lists for both ``unique_identifier`` ...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L450-L464
[ "def sync_week_metric(self, unique_identifier, metric, start_date, end_date):\n \"\"\"\n Uses the count for each day in the date range to recalculate the counters for the weeks for\n the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month\n after using set_metric_by...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.sync_week_metric
python
def sync_week_metric(self, unique_identifier, metric, start_date, end_date): metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_identifier ...
Uses the count for each day in the date range to recalculate the counters for the weeks for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day. The redis backend supports lists for both ``unique_identifier`` and ``metric``...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L466-L498
[ "def _get_closest_week(self, metric_date):\n \"\"\"\n Gets the closest monday to the date provided.\n \"\"\"\n #find the offset to the closest monday\n days_after_monday = metric_date.isoweekday() - 1\n\n return metric_date - datetime.timedelta(days=days_after_monday)\n", "def _get_weekly_metric...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/backends/redis.py
Redis.sync_month_metric
python
def sync_month_metric(self, unique_identifier, metric, start_date, end_date): metric = [metric] if isinstance(metric, basestring) else metric unique_identifier = [unique_identifier] if not isinstance(unique_identifier, (types.ListType, types.TupleType, types.GeneratorType,)) else unique_identifier ...
Uses the count for each day in the date range to recalculate the counters for the months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after using set_metric_by_day. The redis backend supports lists for both ``unique_identifier`` and ``metric`` allowi...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/backends/redis.py#L500-L532
[ "def _get_weekly_metric_key(self, unique_identifier, metric_date):\n \"\"\"\n Redis key for weekly metric\n \"\"\"\n return self._prefix + \":\" + \"user:%s:analy:%s\" % (unique_identifier, metric_date.strftime(\"%y\"),)\n", "def _get_monthly_metric_name(self, metric, metric_date):\n \"\"\"\n Ha...
class Redis(BaseAnalyticsBackend): def __init__(self, settings, **kwargs): nydus_hosts = {} hosts = settings.get("hosts", []) if not hosts: raise Exception("No redis hosts specified") for i, host in enumerate(hosts): nydus_hosts[i] = host defaults =...
numan/py-analytics
analytics/__init__.py
create_analytic_backend
python
def create_analytic_backend(settings): backend = settings.get('backend') if isinstance(backend, basestring): backend = import_string(backend) elif backend: backend = backend else: raise KeyError('backend') return backend(settings.get("settings", {}))
Creates a new Analytics backend from the settings :param settings: Dictionary of settings for the analytics backend :returns: A backend object implementing the analytics api >>> >>> analytics = create_analytic({ >>> 'backend': 'analytics.backends.redis.Redis', >>> 'settings': { >>>...
train
https://github.com/numan/py-analytics/blob/abbc814925c6cc200b3329c7de9f1868e1cb8c01/analytics/__init__.py#L27-L55
[ "def import_string(import_name, silent=False):\n \"\"\"Imports an object based on a string. If *silent* is True the return\n value will be None if the import fails.\n\n Simplified version of the function with same name from `Werkzeug`_.\n\n :param import_name:\n The dotted name for the object to ...
""" Copyright 2012 Numan Sachwani <numan@7Geese.com> This file is provided to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable...
udragon/pybrctl
pybrctl/pybrctl.py
_runshell
python
def _runshell(cmd, exception): p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) if p.wait() != 0: raise BridgeException(exception) return p
Run a shell command. if fails, raise a proper exception.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L145-L150
null
import subprocess from distutils import spawn brctlexe = spawn.find_executable("brctl") ipexe = spawn.find_executable("ip") class BridgeException(Exception): pass class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): ...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.addif
python
def addif(self, iname): _runshell([brctlexe, 'addif', self.name, iname], "Could not add interface %s to %s." % (iname, self.name))
Add an interface to the bridge
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L24-L27
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.delif
python
def delif(self, iname): _runshell([brctlexe, 'delif', self.name, iname], "Could not delete interface %s from %s." % (iname, self.name))
Delete an interface from the bridge.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L29-L32
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.hairpin
python
def hairpin(self, port, val=True): """ Turn harpin on/off on a port. """ if val: state = 'on' else: state = 'off' _runshell([brctlexe, 'hairpin', self.name, port, state], "Could not set hairpin in port %s in %s." % (port, self.name))
Turn harpin on/off on a port.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L34-L39
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.stp
python
def stp(self, val=True): if val: state = 'on' else: state = 'off' _runshell([brctlexe, 'stp', self.name, state], "Could not set stp on %s." % self.name)
Turn STP protocol on/off.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L41-L46
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.setageing
python
def setageing(self, time): _runshell([brctlexe, 'setageing', self.name, str(time)], "Could not set ageing time in %s." % self.name)
Set bridge ageing time.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L48-L51
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.setbridgeprio
python
def setbridgeprio(self, prio): _runshell([brctlexe, 'setbridgeprio', self.name, str(prio)], "Could not set bridge priority in %s." % self.name)
Set bridge priority value.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L53-L56
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.setfd
python
def setfd(self, time): _runshell([brctlexe, 'setfd', self.name, str(time)], "Could not set forward delay in %s." % self.name)
Set bridge forward delay time value.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L58-L61
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.sethello
python
def sethello(self, time): _runshell([brctlexe, 'sethello', self.name, str(time)], "Could not set hello time in %s." % self.name)
Set bridge hello time value.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L63-L66
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.setmaxage
python
def setmaxage(self, time): _runshell([brctlexe, 'setmaxage', self.name, str(time)], "Could not set max message age in %s." % self.name)
Set bridge max message age time.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L68-L71
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.setpathcost
python
def setpathcost(self, port, cost): _runshell([brctlexe, 'setpathcost', self.name, port, str(cost)], "Could not set path cost in port %s in %s." % (port, self.name))
Set port path cost value for STP protocol.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L73-L76
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge.setportprio
python
def setportprio(self, port, prio): _runshell([brctlexe, 'setportprio', self.name, port, str(prio)], "Could not set priority in port %s in %s." % (port, self.name))
Set port priority value.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L78-L81
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
Bridge._show
python
def _show(self): """ Return a list of unsorted bridge details. """ p = _runshell([brctlexe, 'show', self.name], "Could not show %s." % self.name) return p.stdout.read().split()[7:]
Return a list of unsorted bridge details.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L83-L87
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class Bridge(object): def __init__(self, name): """ Initialize a bridge object. """ self.name = name def __str__(self): """ Return a string of the bridge name. """ return self.name def __repr__(self): """ Return a representaion of a bridge object. """ return "<Br...
udragon/pybrctl
pybrctl/pybrctl.py
BridgeController.addbr
python
def addbr(self, name): _runshell([brctlexe, 'addbr', name], "Could not create bridge %s." % name) _runshell([ipexe, 'link', 'set', 'dev', name, 'up'], "Could not set link up for %s." % name) return Bridge(name)
Create a bridge and set the device up.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L112-L118
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class BridgeController(object): def delbr(self, name): """ Set the device down and delete the bridge. """ self.getbr(name) # Check if exists _runshell([ipexe, 'link', 'set', 'dev', name, 'down'], "Could not set link down for %s." % name) _runshell([brctlexe, 'delbr', na...
udragon/pybrctl
pybrctl/pybrctl.py
BridgeController.delbr
python
def delbr(self, name): self.getbr(name) # Check if exists _runshell([ipexe, 'link', 'set', 'dev', name, 'down'], "Could not set link down for %s." % name) _runshell([brctlexe, 'delbr', name], "Could not delete bridge %s." % name)
Set the device down and delete the bridge.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L120-L126
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n", "def getbr(self, name):\n \"\"\" Return a...
class BridgeController(object): def addbr(self, name): """ Create a bridge and set the device up. """ _runshell([brctlexe, 'addbr', name], "Could not create bridge %s." % name) _runshell([ipexe, 'link', 'set', 'dev', name, 'up'], "Could not set link up for %s." % nam...
udragon/pybrctl
pybrctl/pybrctl.py
BridgeController.showall
python
def showall(self): p = _runshell([brctlexe, 'show'], "Could not show bridges.") wlist = map(str.split, p.stdout.read().splitlines()[1:]) brwlist = filter(lambda x: len(x) != 1, wlist) brlist = map(lambda x: x[0], brwlist) return map(Bridge, brlist)
Return a list of all available bridges.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L128-L135
[ "def _runshell(cmd, exception):\n \"\"\" Run a shell command. if fails, raise a proper exception. \"\"\"\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n if p.wait() != 0:\n raise BridgeException(exception)\n return p\n" ]
class BridgeController(object): def addbr(self, name): """ Create a bridge and set the device up. """ _runshell([brctlexe, 'addbr', name], "Could not create bridge %s." % name) _runshell([ipexe, 'link', 'set', 'dev', name, 'up'], "Could not set link up for %s." % nam...
udragon/pybrctl
pybrctl/pybrctl.py
BridgeController.getbr
python
def getbr(self, name): for br in self.showall(): if br.name == name: return br raise BridgeException("Bridge does not exist.")
Return a bridge object.
train
https://github.com/udragon/pybrctl/blob/9e834a605b57bd969a81c56a886dee81f7d715c1/pybrctl/pybrctl.py#L137-L142
[ "def showall(self):\n \"\"\" Return a list of all available bridges. \"\"\"\n p = _runshell([brctlexe, 'show'],\n \"Could not show bridges.\")\n wlist = map(str.split, p.stdout.read().splitlines()[1:])\n brwlist = filter(lambda x: len(x) != 1, wlist)\n brlist = map(lambda x: x[0], brwlist)\n ...
class BridgeController(object): def addbr(self, name): """ Create a bridge and set the device up. """ _runshell([brctlexe, 'addbr', name], "Could not create bridge %s." % name) _runshell([ipexe, 'link', 'set', 'dev', name, 'up'], "Could not set link up for %s." % nam...
9b/frisbee
frisbee/modules/bing.py
Module._format
python
def _format(self): self.log.debug("Formatting URLs to request") items = list() for i in range(0, self.limit, 10): query = '"%s" %s' % (self.domain, self.modifier) url = self.host + "/search?q=" + query + "&first=" + str(i) items.append(url) self.log.de...
Format search queries to perform in bulk. Build up the URLs to call for the search engine. These will be ran through a bulk processor and returned to a detailer.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/bing.py#L30-L43
null
class Module(Base): """Custom search module.""" def __init__(self, domain=None, modifier=None, engine="bing", greedy=False, fuzzy=False, limit=500): """Setup the primary client instance.""" super(Base, self).__init__() self.name = "Bing" self.host = "https://ww...
9b/frisbee
frisbee/modules/bing.py
Module._process
python
def _process(self, responses): self.log.debug("Processing search results") items = list() for response in responses: try: soup = BeautifulSoup(response.content, 'html.parser', from_encoding="iso-8859-1") except: ...
Process search engine results for detailed analysis. Search engine result pages (SERPs) come back with each request and will need to be extracted in order to crawl the actual hits.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/bing.py#L45-L63
null
class Module(Base): """Custom search module.""" def __init__(self, domain=None, modifier=None, engine="bing", greedy=False, fuzzy=False, limit=500): """Setup the primary client instance.""" super(Base, self).__init__() self.name = "Bing" self.host = "https://ww...
9b/frisbee
frisbee/modules/bing.py
Module._fetch
python
def _fetch(self, urls): responses = self._request_bulk(urls) for response in responses: try: soup = BeautifulSoup(response.content, 'html.parser', from_encoding="iso-8859-1") text = soup.get_text() except Except...
Perform bulk collection of data and return the content. Gathering responses is handled by the base class and uses futures to speed up the processing. Response data is saved inside a local variable to be used later in extraction.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/bing.py#L65-L81
[ "def _request_bulk(self, urls: List[str]) -> List:\n \"\"\"Batch the requests going out.\"\"\"\n if not urls:\n raise Exception(\"No results were found\")\n session: FuturesSession = FuturesSession(max_workers=len(urls))\n self.log.info(\"Bulk requesting: %d\" % len(urls))\n futures = [session...
class Module(Base): """Custom search module.""" def __init__(self, domain=None, modifier=None, engine="bing", greedy=False, fuzzy=False, limit=500): """Setup the primary client instance.""" super(Base, self).__init__() self.name = "Bing" self.host = "https://ww...
9b/frisbee
frisbee/modules/bing.py
Module._extract
python
def _extract(self): self.log.debug("Extracting emails from text content") for item in self.data: emails = extract_emails(item, self.domain, self.fuzzy) self.results.extend(emails) self.log.debug("Email extraction completed") return list(set(self.results))
Extract email addresses from results. Text content from all crawled pages are ran through a simple email extractor. Data is cleaned prior to running pattern expressions.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/bing.py#L83-L94
[ "def extract_emails(results: str, domain: str, fuzzy: bool) -> List[str]:\n \"\"\"Grab email addresses from raw text data.\"\"\"\n pattern: Pattern = re.compile(r'([\\w.-]+@[\\w.-]+)')\n hits: List[str] = pattern.findall(results)\n if fuzzy:\n seed = domain.split('.')[0]\n emails: List[str...
class Module(Base): """Custom search module.""" def __init__(self, domain=None, modifier=None, engine="bing", greedy=False, fuzzy=False, limit=500): """Setup the primary client instance.""" super(Base, self).__init__() self.name = "Bing" self.host = "https://ww...
9b/frisbee
frisbee/modules/bing.py
Module.search
python
def search(self): requests = self._format() serps = self._fetch(requests) urls = self._process(serps) details = self._fetch(urls) emails = self._extract() return {'emails': emails, 'processed': len(self.data)}
Run the full search process. Simple public method to abstract the steps needed to produce a full search using the engine.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/bing.py#L96-L107
[ "def _format(self):\n \"\"\"Format search queries to perform in bulk.\n\n Build up the URLs to call for the search engine. These will be ran\n through a bulk processor and returned to a detailer.\n \"\"\"\n self.log.debug(\"Formatting URLs to request\")\n items = list()\n for i in range(0, self...
class Module(Base): """Custom search module.""" def __init__(self, domain=None, modifier=None, engine="bing", greedy=False, fuzzy=False, limit=500): """Setup the primary client instance.""" super(Base, self).__init__() self.name = "Bing" self.host = "https://ww...
9b/frisbee
frisbee/utils.py
gen_logger
python
def gen_logger(name: str, log_level: int=logging.INFO) -> logging.Logger: logger = logging.getLogger(name) logger.setLevel(log_level) shandler: logging.StreamHandler = logging.StreamHandler(sys.stdout) fmt: str = '\033[1;32m%(levelname)-5s %(module)s:%(funcName)s():' fmt += '%(lineno)d %(asctime)s\0...
Create a logger to be used between processes. :returns: Logging instance.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/utils.py#L13-L25
null
#!/usr/bin/env python import datetime import logging import os import random import re import sys from typing import Dict from typing import List from typing import Pattern def gen_headers() -> Dict[str, str]: """Generate a header pairing.""" ua_list: List[str] = ['Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWe...
9b/frisbee
frisbee/utils.py
gen_headers
python
def gen_headers() -> Dict[str, str]: ua_list: List[str] = ['Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.117 Safari/537.36'] headers: Dict[str, str] = {'User-Agent': ua_list[random.randint(0, len(ua_list) - 1)]} return headers
Generate a header pairing.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/utils.py#L28-L32
null
#!/usr/bin/env python import datetime import logging import os import random import re import sys from typing import Dict from typing import List from typing import Pattern def gen_logger(name: str, log_level: int=logging.INFO) -> logging.Logger: """Create a logger to be used between processes. :returns: Log...
9b/frisbee
frisbee/utils.py
extract_emails
python
def extract_emails(results: str, domain: str, fuzzy: bool) -> List[str]: pattern: Pattern = re.compile(r'([\w.-]+@[\w.-]+)') hits: List[str] = pattern.findall(results) if fuzzy: seed = domain.split('.')[0] emails: List[str] = [x.lower() for x in hits if x.split('@')[1].__contains__(seed)] ...
Grab email addresses from raw text data.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/utils.py#L45-L54
null
#!/usr/bin/env python import datetime import logging import os import random import re import sys from typing import Dict from typing import List from typing import Pattern def gen_logger(name: str, log_level: int=logging.INFO) -> logging.Logger: """Create a logger to be used between processes. :returns: Log...
9b/frisbee
frisbee/__init__.py
Frisbee._reset
python
def _reset(self) -> None: self.project: str = namesgenerator.get_random_name() self._processed: List = list() self.results: List = list()
Reset some of the state in the class for multi-searches.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/__init__.py#L48-L52
null
class Frisbee: """Class to interact with the core code.""" NAME: ClassVar[str] = "Frisbee" PROCESSES: ClassVar[int] = 100 MODULE_PATH: ClassVar[str] = 'frisbee.modules' def __init__(self, project: str = namesgenerator.get_random_name(), log_level: int = logging.INFO, save: bool =...
9b/frisbee
frisbee/__init__.py
Frisbee._config_bootstrap
python
def _config_bootstrap(self) -> None: if self.output: self.folder: str = os.getcwd() + "/" + self.project os.mkdir(self.folder)
Handle the basic setup of the tool prior to user control. Bootstrap will load all the available modules for searching and set them up for use by this main class.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/__init__.py#L54-L62
null
class Frisbee: """Class to interact with the core code.""" NAME: ClassVar[str] = "Frisbee" PROCESSES: ClassVar[int] = 100 MODULE_PATH: ClassVar[str] = 'frisbee.modules' def __init__(self, project: str = namesgenerator.get_random_name(), log_level: int = logging.INFO, save: bool =...
9b/frisbee
frisbee/__init__.py
Frisbee._dyn_loader
python
def _dyn_loader(self, module: str, kwargs: str): package_directory: str = os.path.dirname(os.path.abspath(__file__)) modules: str = package_directory + "/modules" module = module + ".py" if module not in os.listdir(modules): raise Exception("Module %s is not valid" % module) ...
Dynamically load a specific module instance.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/__init__.py#L64-L75
null
class Frisbee: """Class to interact with the core code.""" NAME: ClassVar[str] = "Frisbee" PROCESSES: ClassVar[int] = 100 MODULE_PATH: ClassVar[str] = 'frisbee.modules' def __init__(self, project: str = namesgenerator.get_random_name(), log_level: int = logging.INFO, save: bool =...
9b/frisbee
frisbee/__init__.py
Frisbee._job_handler
python
def _job_handler(self) -> bool: while True: try: task = self._unfullfilled.get_nowait() except queue.Empty: break else: self._log.debug("Job: %s" % str(task)) engine = self._dyn_loader(task['engine'], task) ...
Process the work items.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/__init__.py#L77-L94
null
class Frisbee: """Class to interact with the core code.""" NAME: ClassVar[str] = "Frisbee" PROCESSES: ClassVar[int] = 100 MODULE_PATH: ClassVar[str] = 'frisbee.modules' def __init__(self, project: str = namesgenerator.get_random_name(), log_level: int = logging.INFO, save: bool =...
9b/frisbee
frisbee/__init__.py
Frisbee._save
python
def _save(self) -> None: self._log.info("Saving results to '%s'" % self.folder) path: str = self.folder + "/" for job in self.results: if job['domain'] in self.saved: continue job['start_time'] = str_datetime(job['start_time']) job['end_time'] ...
Save output to a directory.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/__init__.py#L96-L116
null
class Frisbee: """Class to interact with the core code.""" NAME: ClassVar[str] = "Frisbee" PROCESSES: ClassVar[int] = 100 MODULE_PATH: ClassVar[str] = 'frisbee.modules' def __init__(self, project: str = namesgenerator.get_random_name(), log_level: int = logging.INFO, save: bool =...
9b/frisbee
frisbee/__init__.py
Frisbee.search
python
def search(self, jobs: List[Dict[str, str]]) -> None: if not isinstance(jobs, list): raise Exception("Jobs must be of type list.") self._log.info("Project: %s" % self.project) self._log.info("Processing jobs: %d", len(jobs)) for _, job in enumerate(jobs): self._un...
Perform searches based on job orders.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/__init__.py#L118-L162
null
class Frisbee: """Class to interact with the core code.""" NAME: ClassVar[str] = "Frisbee" PROCESSES: ClassVar[int] = 100 MODULE_PATH: ClassVar[str] = 'frisbee.modules' def __init__(self, project: str = namesgenerator.get_random_name(), log_level: int = logging.INFO, save: bool =...
9b/frisbee
frisbee/cli/client.py
main
python
def main(): parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('search') setup_parser.add_argument('-e', '--engine', dest='engine', required=True, help='Search engine to use.', choices=['bing']) ...
Run the core.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/cli/client.py#L10-L57
[ "def search(self, jobs: List[Dict[str, str]]) -> None:\n \"\"\"Perform searches based on job orders.\"\"\"\n if not isinstance(jobs, list):\n raise Exception(\"Jobs must be of type list.\")\n self._log.info(\"Project: %s\" % self.project)\n self._log.info(\"Processing jobs: %d\", len(jobs))\n ...
#!/usr/bin/env python """Conduct searches for email addresses across different modules.""" import logging import sys from argparse import ArgumentParser from frisbee import Frisbee
9b/frisbee
frisbee/modules/base.py
Base.set_log_level
python
def set_log_level(self, level: str) -> None: if level == 'info': to_set = logging.INFO if level == 'debug': to_set = logging.DEBUG if level == 'error': to_set = logging.ERROR self.log.setLevel(to_set)
Override the default log level of the class.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/base.py#L25-L33
null
class Base(object): """Base module class to assist in writing new modules.""" name: ClassVar[str] = 'base' log: ClassVar[logging.Logger] = gen_logger(name, logging.INFO) limit: ClassVar[int] = 500 def __init__(self, log_level=logging.INFO) -> None: """Local variables for the module.""" ...
9b/frisbee
frisbee/modules/base.py
Base._request_bulk
python
def _request_bulk(self, urls: List[str]) -> List: if not urls: raise Exception("No results were found") session: FuturesSession = FuturesSession(max_workers=len(urls)) self.log.info("Bulk requesting: %d" % len(urls)) futures = [session.get(u, headers=gen_headers(), timeout=3)...
Batch the requests going out.
train
https://github.com/9b/frisbee/blob/2c958ec1d09bf5b28e6d1c867539b1a5325e6ce7/frisbee/modules/base.py#L35-L49
null
class Base(object): """Base module class to assist in writing new modules.""" name: ClassVar[str] = 'base' log: ClassVar[logging.Logger] = gen_logger(name, logging.INFO) limit: ClassVar[int] = 500 def __init__(self, log_level=logging.INFO) -> None: """Local variables for the module.""" ...
daethnir/authprogs
authprogs/authprogs.py
main
python
def main(): # pylint: disable-msg=R0912,R0915 parser = optparse.OptionParser() parser.usage = textwrap.dedent("""\ %prog {--run|--install_key|--dump_config} [options] SSH command authenticator. Used to restrict which commands can be run via trusted SSH keys. """) group = optparse.OptionG...
Main.
train
https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L449-L569
[ "def log(self, message):\n \"\"\"Log information.\"\"\"\n if self.logfh:\n self.logfh.write(message) # pylint: disable-msg=E1103\n", "def dump_config(self):\n \"\"\"Pretty print the configuration dict to stdout.\"\"\"\n yaml_content = self.get_merged_config()\n print('YAML Configuration\\n%...
"""authprogs: SSH command authenticator module. Used to restrict which commands can be run via trusted SSH keys.""" # Copyright (C) 2013 Bri Hatch (daethnir) <bri@ifokr.org> # # This file is part of authprogs. # # Authprogs is free software: you can redistribute it and/or modify # it under the terms of th...
daethnir/authprogs
authprogs/authprogs.py
AuthProgs.raise_and_log_error
python
def raise_and_log_error(self, error, message): self.log('raising %s, traceback %s\n' % (error, traceback.format_exc())) raise error(message)
Raise error, including message and original traceback. error: the error to raise message: the user-facing error message
train
https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L128-L136
[ "def log(self, message):\n \"\"\"Log information.\"\"\"\n if self.logfh:\n self.logfh.write(message) # pylint: disable-msg=E1103\n" ]
class AuthProgs(object): # pylint: disable-msg=R0902 """AuthProgs class""" def __init__(self, logfile=None, configfile=None, configdir=None, debug=False, **kwargs): """AuthProgs constructor. kwargs include: authprogs_binary: path to this binary, when creating ...
daethnir/authprogs
authprogs/authprogs.py
AuthProgs.get_client_ip
python
def get_client_ip(self): if self.client_ip: return self.client_ip try: client = os.environ.get('SSH_CONNECTION', os.environ.get('SSH_CLIENT')) self.client_ip = client.split()[0] self.logdebug('client_ip: %s\n' % self.c...
Return the client IP from the environment.
train
https://github.com/daethnir/authprogs/blob/0b1e13a609ebeabdb0f10d11fc5dc6e0b20c0343/authprogs/authprogs.py#L138-L152
[ "def logdebug(self, message):\n \"\"\"Log debugging information.\"\"\"\n if self.debug:\n self.log(message)\n" ]
class AuthProgs(object): # pylint: disable-msg=R0902 """AuthProgs class""" def __init__(self, logfile=None, configfile=None, configdir=None, debug=False, **kwargs): """AuthProgs constructor. kwargs include: authprogs_binary: path to this binary, when creating ...