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
hover2pi/svo_filters
svo_filters/svo.py
Filter.load_xml
python
def load_xml(self, filepath): # Parse the XML file vot = vo.parse_single_table(filepath) self.raw = np.array([list(i) for i in vot.array]).T # Parse the filter metadata for p in [str(p).split() for p in vot.params]: # Extract the key/value pairs key = p[...
Load the filter from a txt file Parameters ---------- filepath: str The filepath for the filter
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L548-L586
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.overlap
python
def overlap(self, spectrum): swave = self.wave[np.where(self.throughput != 0)] s1, s2 = swave.min(), swave.max() owave = spectrum[0] o1, o2 = owave.min(), owave.max() if (s1 >= o1 and s2 <= o2): ans = 'full' elif (s2 < o1) or (o2 < s1): ans = 'n...
Tests for overlap of this filter with a spectrum Example of full overlap: |---------- spectrum ----------| |------ self ------| Examples of partial overlap: : |---------- self ----------| |------ spectrum ------| |---- spectrum ----|...
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L588-L638
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.plot
python
def plot(self, fig=None, draw=True): COLORS = color_gen('Category10') # Make the figure if fig is None: xlab = 'Wavelength [{}]'.format(self.wave_units) ylab = 'Throughput' title = self.filterID fig = figure(title=title, x_axis_label=xlab, y_axis_...
Plot the filter Parameters ---------- fig: bokeh.plotting.figure (optional) A figure to plot on draw: bool Draw the figure, else return it Returns ------- bokeh.plotting.figure The filter figure
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L640-L677
[ "def color_gen(colormap='viridis', key=None, n=15):\n \"\"\"Color generator for Bokeh plots\n\n Parameters\n ----------\n colormap: str, sequence\n The name of the color map\n\n Returns\n -------\n generator\n A generator for the color palette\n \"\"\"\n if colormap in dir(b...
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.rsr
python
def rsr(self): arr = np.array([self.wave.value, self.throughput]).swapaxes(0, 1) return arr
A getter for the relative spectral response (rsr) curve
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L680-L684
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.throughput
python
def throughput(self, points): # Test shape if not points.shape == self.wave.shape: raise ValueError("Throughput and wavelength must be same shape.") self._throughput = points
A setter for the throughput Parameters ---------- throughput: sequence The array of throughput points
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L692-L704
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.wave
python
def wave(self, wavelength): # Test units if not isinstance(wavelength, q.quantity.Quantity): raise ValueError("Wavelength must be in length units.") self._wave = wavelength self.wave_units = wavelength.unit
A setter for the wavelength Parameters ---------- wavelength: astropy.units.quantity.Quantity The array with units
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L712-L725
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
hover2pi/svo_filters
svo_filters/svo.py
Filter.wave_units
python
def wave_units(self, units): # Make sure it's length units if not units.is_equivalent(q.m): raise ValueError(units, ": New wavelength units must be a length.") # Update the units self._wave_units = units # Update all the wavelength values self._wave = self.w...
A setter for the wavelength units Parameters ---------- units: str, astropy.units.core.PrefixUnit The wavelength units
train
https://github.com/hover2pi/svo_filters/blob/f0587c4908baf636d4bdf030fa95029e8f31b975/svo_filters/svo.py#L733-L760
null
class Filter: """ Creates a Filter object to store a photometric filter profile and metadata Attributes ---------- path: str The absolute filepath for the bandpass data, an ASCII file with a wavelength column in Angstroms and a response column of values ranging from 0 to...
tweekmonster/moult
moult/utils.py
load_stdlib
python
def load_stdlib(): '''Scans sys.path for standard library modules. ''' if _stdlib: return _stdlib prefixes = tuple({os.path.abspath(p) for p in ( sys.prefix, getattr(sys, 'real_prefix', sys.prefix), getattr(sys, 'base_prefix', sys.prefix), )}) for sp in sys.path...
Scans sys.path for standard library modules.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L18-L54
null
import os import re import sys from .classes import PyModule from .pip_importer import * from .compat import str_ _stdlib = set() _import_paths = [] __all__ = ('dist_is_local', 'dist_in_usersite', 'get_installed_distributions', 'running_under_virtualenv', 'ignore_packages', 'search_packages_in...
tweekmonster/moult
moult/utils.py
import_path_from_file
python
def import_path_from_file(filename, as_list=False): '''Returns a tuple of the import path and root module directory for the supplied file. ''' module_path = [] basename = os.path.splitext(os.path.basename(filename))[0] if basename != '__init__': module_path.append(basename) dirname ...
Returns a tuple of the import path and root module directory for the supplied file.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L69-L85
null
import os import re import sys from .classes import PyModule from .pip_importer import * from .compat import str_ _stdlib = set() _import_paths = [] __all__ = ('dist_is_local', 'dist_in_usersite', 'get_installed_distributions', 'running_under_virtualenv', 'ignore_packages', 'search_packages_in...
tweekmonster/moult
moult/utils.py
file_containing_import
python
def file_containing_import(import_path, import_root): '''Finds the file that might contain the import_path. ''' if not _import_paths: load_stdlib() if os.path.isfile(import_root): import_root = os.path.dirname(import_root) search_paths = [import_root] + _import_paths module_par...
Finds the file that might contain the import_path.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L88-L107
[ "def load_stdlib():\n '''Scans sys.path for standard library modules.\n '''\n if _stdlib:\n return _stdlib\n\n prefixes = tuple({os.path.abspath(p) for p in (\n sys.prefix,\n getattr(sys, 'real_prefix', sys.prefix),\n getattr(sys, 'base_prefix', sys.prefix),\n )})\n\n f...
import os import re import sys from .classes import PyModule from .pip_importer import * from .compat import str_ _stdlib = set() _import_paths = [] __all__ = ('dist_is_local', 'dist_in_usersite', 'get_installed_distributions', 'running_under_virtualenv', 'ignore_packages', 'search_packages_in...
tweekmonster/moult
moult/utils.py
resolve_import
python
def resolve_import(import_path, from_module): '''Resolves relative imports from a module. ''' if not import_path or not import_path.startswith('.'): return import_path from_module = from_module.split('.') dots = 0 for c in import_path: if c == '.': dots += 1 ...
Resolves relative imports from a module.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L110-L131
null
import os import re import sys from .classes import PyModule from .pip_importer import * from .compat import str_ _stdlib = set() _import_paths = [] __all__ = ('dist_is_local', 'dist_in_usersite', 'get_installed_distributions', 'running_under_virtualenv', 'ignore_packages', 'search_packages_in...
tweekmonster/moult
moult/utils.py
find_package
python
def find_package(name, installed, package=False): '''Finds a package in the installed list. If `package` is true, match package names, otherwise, match import paths. ''' if package: name = name.lower() tests = ( lambda x: x.user and name == x.name.lower(), lambda...
Finds a package in the installed list. If `package` is true, match package names, otherwise, match import paths.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L134-L160
null
import os import re import sys from .classes import PyModule from .pip_importer import * from .compat import str_ _stdlib = set() _import_paths = [] __all__ = ('dist_is_local', 'dist_in_usersite', 'get_installed_distributions', 'running_under_virtualenv', 'ignore_packages', 'search_packages_in...
tweekmonster/moult
moult/utils.py
is_script
python
def is_script(filename): '''Checks if a file has a hashbang. ''' if not os.path.isfile(filename): return False try: with open(filename, 'rb') as fp: return fp.read(2) == b'#!' except IOError: pass return False
Checks if a file has a hashbang.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L163-L175
null
import os import re import sys from .classes import PyModule from .pip_importer import * from .compat import str_ _stdlib = set() _import_paths = [] __all__ = ('dist_is_local', 'dist_in_usersite', 'get_installed_distributions', 'running_under_virtualenv', 'ignore_packages', 'search_packages_in...
tweekmonster/moult
moult/utils.py
is_python_script
python
def is_python_script(filename): '''Checks a file to see if it's a python script of some sort. ''' if filename.lower().endswith('.py'): return True if not os.path.isfile(filename): return False try: with open(filename, 'rb') as fp: if fp.read(2) != b'#!': ...
Checks a file to see if it's a python script of some sort.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/utils.py#L178-L195
null
import os import re import sys from .classes import PyModule from .pip_importer import * from .compat import str_ _stdlib = set() _import_paths = [] __all__ = ('dist_is_local', 'dist_in_usersite', 'get_installed_distributions', 'running_under_virtualenv', 'ignore_packages', 'search_packages_in...
tweekmonster/moult
moult/printer.py
output
python
def output(*args, **kwargs): '''Analog of print() but with an indent option ''' indent = kwargs.pop('indent', 0) sep = kwargs.pop('sep', None) kwargs['sep'] = u'' # Sanity if sep is None: sep = u' ' indent_str = u' ' * (indent * tab_width) text = sep.join(map(str_, args)) co...
Analog of print() but with an indent option
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/printer.py#L21-L35
null
from __future__ import print_function import os import sys import time from .utils import running_under_virtualenv from .color import * from .exceptions import MoultCommandError from .compat import str_ from . import __version__ __all__ = ('enable_debug', 'output', 'error', 'wrap', 'print_module') enable_debug = ...
tweekmonster/moult
moult/frameworks/django.py
scan_django_settings
python
def scan_django_settings(values, imports): '''Recursively scans Django settings for values that appear to be imported modules. ''' if isinstance(values, (str, bytes)): if utils.is_import_str(values): imports.add(values) elif isinstance(values, dict): for k, v in values.it...
Recursively scans Django settings for values that appear to be imported modules.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/frameworks/django.py#L21-L37
[ "def import_path_from_file(filename, as_list=False):\n '''Returns a tuple of the import path and root module directory for the\n supplied file.\n '''\n module_path = []\n basename = os.path.splitext(os.path.basename(filename))[0]\n if basename != '__init__':\n module_path.append(basename)\n...
from __future__ import absolute_import, unicode_literals import re import os import sys import time from .. import utils, log _excluded_settings = ( 'ALLOWED_HOSTS', ) _filescan_modules = ( 'django.db.backends', 'django.core.cache.backends', ) def handle_django_settings(filename): '''Attempts to...
tweekmonster/moult
moult/frameworks/django.py
handle_django_settings
python
def handle_django_settings(filename): '''Attempts to load a Django project and get package dependencies from settings. Tested using Django 1.4 and 1.8. Not sure if some nuances are missed in the other versions. ''' old_sys_path = sys.path[:] dirpath = os.path.dirname(filename) project =...
Attempts to load a Django project and get package dependencies from settings. Tested using Django 1.4 and 1.8. Not sure if some nuances are missed in the other versions.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/frameworks/django.py#L40-L132
[ "def import_path_from_file(filename, as_list=False):\n '''Returns a tuple of the import path and root module directory for the\n supplied file.\n '''\n module_path = []\n basename = os.path.splitext(os.path.basename(filename))[0]\n if basename != '__init__':\n module_path.append(basename)\n...
from __future__ import absolute_import, unicode_literals import re import os import sys import time from .. import utils, log _excluded_settings = ( 'ALLOWED_HOSTS', ) _filescan_modules = ( 'django.db.backends', 'django.core.cache.backends', ) def scan_django_settings(values, imports): '''Recursi...
tweekmonster/moult
moult/filesystem_scanner.py
_scan_file
python
def _scan_file(filename, sentinel, source_type='import'): '''Generator that performs the actual scanning of files. Yeilds a tuple containing import type, import path, and an extra file that should be scanned. Extra file scans should be the file or directory that relates to the import name. ''' ...
Generator that performs the actual scanning of files. Yeilds a tuple containing import type, import path, and an extra file that should be scanned. Extra file scans should be the file or directory that relates to the import name.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/filesystem_scanner.py#L20-L48
null
import os import re from .classes import PyModule from .ast_scanner import ast_scan_file from .frameworks import django from . import utils, log max_directory_depth = 20 max_file_size = 1024 * 1204 # Common ignorable directories _dir_ignore = re.compile(r'(\.(git|hg|svn|tox)|CVS|__pycache__)\b') # Files to not eve...
tweekmonster/moult
moult/filesystem_scanner.py
_scan_directory
python
def _scan_directory(directory, sentinel, depth=0): '''Basically os.listdir with some filtering. ''' directory = os.path.abspath(directory) real_directory = os.path.realpath(directory) if depth < max_directory_depth and real_directory not in sentinel \ and os.path.isdir(directory): ...
Basically os.listdir with some filtering.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/filesystem_scanner.py#L51-L71
null
import os import re from .classes import PyModule from .ast_scanner import ast_scan_file from .frameworks import django from . import utils, log max_directory_depth = 20 max_file_size = 1024 * 1204 # Common ignorable directories _dir_ignore = re.compile(r'(\.(git|hg|svn|tox)|CVS|__pycache__)\b') # Files to not eve...
tweekmonster/moult
moult/filesystem_scanner.py
scan_file
python
def scan_file(pym, filename, sentinel, installed): '''Entry point scan that creates a PyModule instance if needed. ''' if not utils.is_python_script(filename): return if not pym: # This is for finding a previously created instance, not finding an # installed module with the same...
Entry point scan that creates a PyModule instance if needed.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/filesystem_scanner.py#L74-L111
[ "def _scan_file(filename, sentinel, source_type='import'):\n '''Generator that performs the actual scanning of files.\n\n Yeilds a tuple containing import type, import path, and an extra file\n that should be scanned. Extra file scans should be the file or directory\n that relates to the import name.\n ...
import os import re from .classes import PyModule from .ast_scanner import ast_scan_file from .frameworks import django from . import utils, log max_directory_depth = 20 max_file_size = 1024 * 1204 # Common ignorable directories _dir_ignore = re.compile(r'(\.(git|hg|svn|tox)|CVS|__pycache__)\b') # Files to not eve...
tweekmonster/moult
moult/filesystem_scanner.py
scan_directory
python
def scan_directory(pym, directory, sentinel, installed, depth=0): '''Entry point scan that creates a PyModule instance if needed. ''' if not pym: d = os.path.abspath(directory) basename = os.path.basename(d) pym = utils.find_package(basename, installed) if not pym: ...
Entry point scan that creates a PyModule instance if needed.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/filesystem_scanner.py#L114-L149
[ "def _scan_directory(directory, sentinel, depth=0):\n '''Basically os.listdir with some filtering.\n '''\n directory = os.path.abspath(directory)\n real_directory = os.path.realpath(directory)\n\n if depth < max_directory_depth and real_directory not in sentinel \\\n and os.path.isdir(dire...
import os import re from .classes import PyModule from .ast_scanner import ast_scan_file from .frameworks import django from . import utils, log max_directory_depth = 20 max_file_size = 1024 * 1204 # Common ignorable directories _dir_ignore = re.compile(r'(\.(git|hg|svn|tox)|CVS|__pycache__)\b') # Files to not eve...
tweekmonster/moult
moult/ast_scanner.py
ast_value
python
def ast_value(val, scope, return_name=False): '''Recursively parse out an AST value. This makes no attempt to load modules or reconstruct functions on purpose. We do not want to inadvertently call destructive code. ''' # :TODO: refactor the hell out of this try: if isinstance(val, (ast...
Recursively parse out an AST value. This makes no attempt to load modules or reconstruct functions on purpose. We do not want to inadvertently call destructive code.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L22-L106
[ "def ast_value(val, scope, return_name=False):\n '''Recursively parse out an AST value. This makes no attempt to load\n modules or reconstruct functions on purpose. We do not want to\n inadvertently call destructive code.\n '''\n # :TODO: refactor the hell out of this\n try:\n if isinstan...
from __future__ import unicode_literals import io import re import ast from .exceptions import MoultScannerError from .compat import str_ from . import utils, log _fallback_re = re.compile(r''' ^[\ \t]*( from[\ \t]+[\w\.]+[\ \t]+import\s+\([\s\w,]+\)| from[\ \t]+[\w\.]+[\ \t]+import[\ \t\w,]+| ...
tweekmonster/moult
moult/ast_scanner.py
get_args
python
def get_args(args, kwargs, arg_names): '''Get arguments as a dict. ''' n_args = len(arg_names) if len(args) + len(kwargs) > n_args: raise MoultScannerError('Too many arguments supplied. Expected: {}'.format(n_args)) out_args = {} for i, a in enumerate(args): out_args[arg_names[i...
Get arguments as a dict.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L123-L139
null
from __future__ import unicode_literals import io import re import ast from .exceptions import MoultScannerError from .compat import str_ from . import utils, log _fallback_re = re.compile(r''' ^[\ \t]*( from[\ \t]+[\w\.]+[\ \t]+import\s+\([\s\w,]+\)| from[\ \t]+[\w\.]+[\ \t]+import[\ \t\w,]+| ...
tweekmonster/moult
moult/ast_scanner.py
ast_scan_file
python
def ast_scan_file(filename, re_fallback=True): '''Scans a file for imports using AST. In addition to normal imports, try to get imports via `__import__` or `import_module` calls. The AST parser should be able to resolve simple variable assignments in cases where these functions are called with vari...
Scans a file for imports using AST. In addition to normal imports, try to get imports via `__import__` or `import_module` calls. The AST parser should be able to resolve simple variable assignments in cases where these functions are called with variables instead of strings.
train
https://github.com/tweekmonster/moult/blob/38d3a3b9002336219897ebe263ca1d8dcadbecf5/moult/ast_scanner.py#L291-L319
[ "def _ast_scan_file_re(filename):\n try:\n with io.open(filename, 'rt', encoding='utf8') as fp:\n script = fp.read()\n normalized = ''\n for imp in _fallback_re.finditer(script):\n imp_line = imp.group(1)\n try:\n imp_line =...
from __future__ import unicode_literals import io import re import ast from .exceptions import MoultScannerError from .compat import str_ from . import utils, log _fallback_re = re.compile(r''' ^[\ \t]*( from[\ \t]+[\w\.]+[\ \t]+import\s+\([\s\w,]+\)| from[\ \t]+[\w\.]+[\ \t]+import[\ \t\w,]+| ...
oemof/oemof.db
oemof/db/tools.py
get_polygon_from_nuts
python
def get_polygon_from_nuts(conn, nuts): r"""A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : array_like Array_like means all th...
r"""A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : array_like Array_like means all those objects -- lists, nested lists, etc. --...
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L40-L133
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/tools.py
get_polygon_from_postgis
python
def get_polygon_from_postgis(conn, schema, table, gcol='geom', union=False): r"""A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : arra...
r"""A one-line summary that does not use variable names or the function name. Several sentences providing an extended description. Refer to variables using back-ticks, e.g. `var`. Parameters ---------- var1 : array_like Array_like means all those objects -- lists, nested lists, etc. --...
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L136-L231
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/tools.py
tz_from_geom
python
def tz_from_geom(connection, geometry): r"""Finding the timezone of a given point or polygon geometry, assuming that the polygon is not crossing a border of a timezone. For a given point or polygon geometry not located within the timezone dataset (e.g. sea) the nearest timezone based on the bounding box...
r"""Finding the timezone of a given point or polygon geometry, assuming that the polygon is not crossing a border of a timezone. For a given point or polygon geometry not located within the timezone dataset (e.g. sea) the nearest timezone based on the bounding boxes of the geometries is returned. Param...
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L234-L272
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/tools.py
get_windzone
python
def get_windzone(conn, geometry): 'Find windzone from map.' # TODO@Günni if geometry.geom_type in ['Polygon', 'MultiPolygon']: coords = geometry.centroid else: coords = geometry sql = """ SELECT zone FROM oemof_test.windzones WHERE st_contains(geom, ST_PointFromText('...
Find windzone from map.
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L275-L291
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/tools.py
create_empty_table_serial_primary
python
def create_empty_table_serial_primary(conn, schema, table, columns=None, id_col='id'): r"""New database table with primary key type serial and empty columns Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schem...
r"""New database table with primary key type serial and empty columns Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table columns : list, optional Columns that ...
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L294-L330
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/tools.py
grant_db_access
python
def grant_db_access(conn, schema, table, role): r"""Gives access to database users/ groups Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table role : str da...
r"""Gives access to database users/ groups Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table role : str database role that access is granted to
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L332-L351
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/tools.py
add_primary_key
python
def add_primary_key(conn, schema, table, pk_col): r"""Adds primary key to database table Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table pk_col : str Co...
r"""Adds primary key to database table Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table pk_col : str Column that primary key is applied to
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L354-L372
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/tools.py
change_owner_to
python
def change_owner_to(conn, schema, table, role): r"""Changes table's ownership to role Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table role : str databas...
r"""Changes table's ownership to role Parameters ---------- conn : sqlalchemy connection object A valid connection to a database schema : str The database schema table : str The database table role : str database role that access is granted to
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/tools.py#L375-L395
null
# -*- coding: utf-8 -*- """ Created on Mon Aug 17 11:08:15 2015 This is a collection of helper functions which work on there own an can be used by various classes. If there are too many helper-functions, they will be sorted in different modules. All special import should be in try/except loops to avoid import errors....
oemof/oemof.db
oemof/db/coastdat.py
get_weather
python
def get_weather(conn, geometry, year): r""" Get the weather data for the given geometry and create an oemof weather object. """ rename_dc = { 'ASWDIFD_S': 'dhi', 'ASWDIR_S': 'dirhi', 'PS': 'pressure', 'T_2M': 'temp_air', 'WSS_10M': 'v_wind', 'Z0': 'z0'...
r""" Get the weather data for the given geometry and create an oemof weather object.
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L14-L51
[ "def fetch_raw_data(sql, connection, geometry):\n \"\"\"\n Fetch the coastdat2 from the database, adapt it to the local time zone\n and create a time index.\n \"\"\"\n tmp_dc = {}\n weather_df = pd.DataFrame(\n connection.execute(sql).fetchall(), columns=[\n 'gid', 'geom_point', ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging import pandas as pd import numpy as np from pytz import timezone from datetime import datetime import feedinlib.weather as weather from . import tools from shapely.wkt import loads as wkt_loads def sql_weather_string(year, sql_part): """ Creates an s...
oemof/oemof.db
oemof/db/coastdat.py
fetch_raw_data
python
def fetch_raw_data(sql, connection, geometry): tmp_dc = {} weather_df = pd.DataFrame( connection.execute(sql).fetchall(), columns=[ 'gid', 'geom_point', 'geom_polygon', 'data_id', 'time_series', 'dat_id', 'type_id', 'type', 'height', 'year', 'leap_year']).drop( 'dat_id', ...
Fetch the coastdat2 from the database, adapt it to the local time zone and create a time index.
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L92-L128
[ "def tz_from_geom(connection, geometry):\n r\"\"\"Finding the timezone of a given point or polygon geometry, assuming\n that the polygon is not crossing a border of a timezone. For a given point\n or polygon geometry not located within the timezone dataset (e.g. sea) the\n nearest timezone based on the ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging import pandas as pd import numpy as np from pytz import timezone from datetime import datetime import feedinlib.weather as weather from . import tools from shapely.wkt import loads as wkt_loads def get_weather(conn, geometry, year): r""" Get the weath...
oemof/oemof.db
oemof/db/coastdat.py
create_single_weather
python
def create_single_weather(df, rename_dc): my_weather = weather.FeedinWeather() data_height = {} name = None # Create a pandas.DataFrame with the time series of the weather data set weather_df = pd.DataFrame(index=df.time_series.iloc[0].index) for row in df.iterrows(): key = rename_dc[row...
Create an oemof weather object for the given geometry
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L131-L150
null
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging import pandas as pd import numpy as np from pytz import timezone from datetime import datetime import feedinlib.weather as weather from . import tools from shapely.wkt import loads as wkt_loads def get_weather(conn, geometry, year): r""" Get the weath...
oemof/oemof.db
oemof/db/coastdat.py
create_multi_weather
python
def create_multi_weather(df, rename_dc): weather_list = [] # Create a pandas.DataFrame with the time series of the weather data set # for each data set and append them to a list. for gid in df.gid.unique(): gid_df = df[df.gid == gid] obj = create_single_weather(gid_df, rename_dc) ...
Create a list of oemof weather objects if the given geometry is a polygon
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/coastdat.py#L153-L163
[ "def create_single_weather(df, rename_dc):\n \"\"\"Create an oemof weather object for the given geometry\"\"\"\n my_weather = weather.FeedinWeather()\n data_height = {}\n name = None\n # Create a pandas.DataFrame with the time series of the weather data set\n weather_df = pd.DataFrame(index=df.tim...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging import pandas as pd import numpy as np from pytz import timezone from datetime import datetime import feedinlib.weather as weather from . import tools from shapely.wkt import loads as wkt_loads def get_weather(conn, geometry, year): r""" Get the weath...
oemof/oemof.db
oemof/db/feedin_pg.py
Feedin.aggregate_cap_val
python
def aggregate_cap_val(self, conn, **kwargs): ''' Returns the normalised feedin profile and installed capacity for a given region. Parameters ---------- region : Region instance region.geom : shapely.geometry object Geo-spatial data with information fo...
Returns the normalised feedin profile and installed capacity for a given region. Parameters ---------- region : Region instance region.geom : shapely.geometry object Geo-spatial data with information for location/region-shape. The geometry can be a polygo...
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/feedin_pg.py#L21-L58
[ "def get_timeseries(self, conn, **kwargs):\n ''\n weather = coastdat.get_weather(\n conn, kwargs['geometry'], kwargs['year'])\n\n pv_df = 0\n pv_cap = {}\n wind_df = 0\n wind_cap = {}\n\n if not isinstance(weather, list):\n weather = [weather]\n\n for w_cell in weather:\n ...
class Feedin: '' def __init__(self): '' pass def get_timeseries(self, conn, **kwargs): '' weather = coastdat.get_weather( conn, kwargs['geometry'], kwargs['year']) pv_df = 0 pv_cap = {} wind_df = 0 wind_cap = {} if not ...
oemof/oemof.db
oemof/db/config.py
load_config
python
def load_config(filename): if filename is None: filename = '' abs_filename = os.path.join(os.getcwd(), filename) global FILE # find the config file if os.path.isfile(filename): FILE = filename elif os.path.isfile(abs_filename): FILE = abs_filename elif os.path.isf...
Load data from config file to `cfg` that can be accessed by get, set afterwards. Specify absolute or relative path to your config file. :param filename: Relative or absolute path :type filename: str
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/config.py#L48-L81
[ "def init(FILE):\n \"\"\"\n Read config file\n\n :param FILE: Absolute path to config file (incl. filename)\n :type FILE: str\n \"\"\"\n try:\n cfg.read(FILE)\n global _loaded\n _loaded = True\n except:\n file_not_found_message(FILE)\n" ]
# -*- coding: utf-8 -*- """ Created on Fri Sep 5 12:26:40 2014 :module-author: steffen :filename: config.py This module provides a highlevel layer for reading and writing config files. There must be a file called "config.ini" in the root-folder of the project. The file has to be of the following structure to be imp...
oemof/oemof.db
oemof/db/config.py
init
python
def init(FILE): try: cfg.read(FILE) global _loaded _loaded = True except: file_not_found_message(FILE)
Read config file :param FILE: Absolute path to config file (incl. filename) :type FILE: str
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/config.py#L113-L125
[ "def file_not_found_message(file_not_found):\n \"\"\"\n Show error message incl. help if file not found\n\n :param filename:\n :type filename: str\n \"\"\"\n\n logging.error(\n \"\"\"\n Config file {file} cannot be found. Make sure this file exists!\n\n An exemplary section i...
# -*- coding: utf-8 -*- """ Created on Fri Sep 5 12:26:40 2014 :module-author: steffen :filename: config.py This module provides a highlevel layer for reading and writing config files. There must be a file called "config.ini" in the root-folder of the project. The file has to be of the following structure to be imp...
oemof/oemof.db
oemof/db/config.py
get
python
def get(section, key): # FILE = 'config_misc' if not _loaded: init(FILE) try: return cfg.getfloat(section, key) except Exception: try: return cfg.getint(section, key) except: try: return cfg.getboolean(section, key) exce...
returns the value of a given key of a given section of the main config file. :param section: the section. :type section: str. :param key: the key. :type key: str. :returns: the value which will be casted to float, int or boolean. if no cast is successfull, the raw string will be returned.
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/config.py#L128-L154
[ "def init(FILE):\n \"\"\"\n Read config file\n\n :param FILE: Absolute path to config file (incl. filename)\n :type FILE: str\n \"\"\"\n try:\n cfg.read(FILE)\n global _loaded\n _loaded = True\n except:\n file_not_found_message(FILE)\n" ]
# -*- coding: utf-8 -*- """ Created on Fri Sep 5 12:26:40 2014 :module-author: steffen :filename: config.py This module provides a highlevel layer for reading and writing config files. There must be a file called "config.ini" in the root-folder of the project. The file has to be of the following structure to be imp...
oemof/oemof.db
oemof/db/__init__.py
url
python
def url(section="postGIS", config_file=None): cfg.load_config(config_file) try: pw = keyring.get_password(cfg.get(section, "database"), cfg.get(section, "username")) except NoSectionError as e: print("There is no section {section} in your config file. Plea...
Retrieve the URL used to connect to the database. Use this if you have your own means of accessing the database and do not want to use :func:`engine` or :func:`connection`. Parameters ---------- section : str, optional The `config.ini` section corresponding to the targeted database. ...
train
https://github.com/oemof/oemof.db/blob/d51ac50187f03a875bd7ce5991ed4772e8b77b93/oemof/db/__init__.py#L11-L73
null
from configparser import NoOptionError as option, NoSectionError from sqlalchemy import create_engine import keyring from . import config as cfg from oemof.db.tools import db_table2pandas import getpass __version__ = '0.0.6dev' def engine(section="postGIS", config_file=None): """Creates engine object for datab...
wooga/play-deliver
playdeliver/sync_command.py
SyncCommand.execute
python
def execute(self): try: if self.upstream: if self.options['listings'] is True: listing.upload(self.client, self.source_directory) self.client.commit() if self.options['images'] is True: image.upload(self.clie...
Execute the command.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/sync_command.py#L43-L66
[ "def upload(client, source_dir):\n \"\"\"\n Upload images to play store.\n\n The function will iterate through source_dir and upload all matching\n image_types found in folder herachy.\n \"\"\"\n print('')\n print('upload images')\n print('-------------')\n base_image_folders = [\n ...
class SyncCommand(object): """The Sync command executes the up-/download of items from play.""" def __init__(self, package_name, source_directory, upstream, credentials, **options): """ Create new SyncCommand with given params. package_name the app package to upload d...
wooga/play-deliver
playdeliver/inapp_product.py
upload
python
def upload(client, source_dir): print('') print('upload inappproducs') print('---------------------') products_folder = os.path.join(source_dir, 'products') product_files = filter(os.path.isfile, list_dir_abspath(products_folder)) current_product_skus = map(lambda product: product['sku'], clie...
Upload inappproducts to play store.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/inapp_product.py#L7-L30
[ "def list_dir_abspath(path):\n \"\"\"\n Return a list absolute file paths.\n\n see mkdir_p os.listdir.\n \"\"\"\n return map(lambda f: os.path.join(path, f), os.listdir(path))\n" ]
"""This module helps for uploading and downloading inappproducts from/to play.""" import os import json from file_util import mkdir_p from file_util import list_dir_abspath def download(client, target_dir): """Download inappproducts from play store.""" print('') print("download inappproducts") print(...
wooga/play-deliver
playdeliver/inapp_product.py
download
python
def download(client, target_dir): print('') print("download inappproducts") print('---------------------') products = client.list_inappproducts() for product in products: path = os.path.join(target_dir, 'products') del product['packageName'] mkdir_p(path) with open(o...
Download inappproducts from play store.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/inapp_product.py#L33-L48
[ "def mkdir_p(path):\n \"\"\"Create a new directory with with all missing folders in between.\"\"\"\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n" ]
"""This module helps for uploading and downloading inappproducts from/to play.""" import os import json from file_util import mkdir_p from file_util import list_dir_abspath def upload(client, source_dir): """Upload inappproducts to play store.""" print('') print('upload inappproducs') print('----------...
wooga/play-deliver
playdeliver/client.py
Client.list
python
def list(self, service_name, **params): result = self._invoke_call(service_name, 'list', **params) if result is not None: return result.get(service_name, list()) return list()
convinent access method for list. service_name describes the endpoint to call the `list` function on. images.list or apks.list.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L25-L37
[ "def _invoke_call(self, service_name, function_name, **params):\n self.ensure_edit_id()\n params = self.build_params(params)\n service_impl = getattr(self.edits(), service_name)\n method = getattr(service_impl(), function_name)\n\n if method and callable(method):\n return method(**params).exec...
class Client(object): """ Client object which handles google api edits. It hold the service user credentials and app package name. """ def __init__(self, package_name, service): """ create new client object. package_name = the app package you want to access credent...
wooga/play-deliver
playdeliver/client.py
Client.list_inappproducts
python
def list_inappproducts(self): result = self.service.inappproducts().list( packageName=self.package_name).execute() if result is not None: return result.get('inappproduct', list()) return list()
temp function to list inapp products.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L39-L46
null
class Client(object): """ Client object which handles google api edits. It hold the service user credentials and app package name. """ def __init__(self, package_name, service): """ create new client object. package_name = the app package you want to access credent...
wooga/play-deliver
playdeliver/client.py
Client.commit
python
def commit(self): request = self.edits().commit(**self.build_params()).execute() print 'Edit "%s" has been committed' % (request['id']) self.edit_id = None
commit current edits.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L89-L94
[ "def build_params(self, params={}):\n \"\"\"\n build a params dictionary with current editId and packageName.\n\n use optional params parameter\n to merge additional params into resulting dictionary.\n \"\"\"\n z = params.copy()\n z.update({'editId': self.edit_id, 'packageName': self.package_na...
class Client(object): """ Client object which handles google api edits. It hold the service user credentials and app package name. """ def __init__(self, package_name, service): """ create new client object. package_name = the app package you want to access credent...
wooga/play-deliver
playdeliver/client.py
Client.build_params
python
def build_params(self, params={}): z = params.copy() z.update({'editId': self.edit_id, 'packageName': self.package_name}) return z
build a params dictionary with current editId and packageName. use optional params parameter to merge additional params into resulting dictionary.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L107-L116
null
class Client(object): """ Client object which handles google api edits. It hold the service user credentials and app package name. """ def __init__(self, package_name, service): """ create new client object. package_name = the app package you want to access credent...
wooga/play-deliver
playdeliver/client.py
Client.ensure_edit_id
python
def ensure_edit_id(self): if self.edit_id is None: edit_request = self.edits().insert( body={}, packageName=self.package_name) result = edit_request.execute() self.edit_id = result['id']
create edit id if edit id is None.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/client.py#L122-L128
[ "def edits(self):\n \"\"\"Return current edits object.\"\"\"\n return self.service.edits()\n" ]
class Client(object): """ Client object which handles google api edits. It hold the service user credentials and app package name. """ def __init__(self, package_name, service): """ create new client object. package_name = the app package you want to access credent...
wooga/play-deliver
playdeliver/file_util.py
list_dir_abspath
python
def list_dir_abspath(path): return map(lambda f: os.path.join(path, f), os.listdir(path))
Return a list absolute file paths. see mkdir_p os.listdir.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/file_util.py#L7-L13
null
"""module with utility functions for the file system.""" import os import errno def mkdir_p(path): """Create a new directory with with all missing folders in between.""" try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): ...
wooga/play-deliver
playdeliver/playdeliver.py
execute
python
def execute(options): # Load the key in PKCS 12 format that you downloaded from the Google APIs # Console when you created your Service account. package_name = options['<package>'] source_directory = options['<output_dir>'] if options['upload'] is True: upstream = True else: ups...
execute the tool with given options.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/playdeliver.py#L20-L42
[ "def create_credentials(credentials_file=None,\n service_email=None,\n service_key=None,\n scope='https://www.googleapis.com/auth/androidpublisher'):\n \"\"\"\n Create Google credentials object.\n\n If given credentials_file is None, try to ...
#!/usr/bin/env python """starting point for the playdeliver tool.""" import os import sys from sync_command import SyncCommand from oauth2client import client def _load_key(location): if location is not None and os.path.isfile(location): f = open(location, 'rb') key = f.read() f.close() ...
wooga/play-deliver
playdeliver/playdeliver.py
create_credentials
python
def create_credentials(credentials_file=None, service_email=None, service_key=None, scope='https://www.googleapis.com/auth/androidpublisher'): credentials = None if service_email is None and service_key is None: print(credentials_file)...
Create Google credentials object. If given credentials_file is None, try to retrieve file path from environment or look up file in homefolder.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/playdeliver.py#L45-L79
[ "def _load_key(location):\n if location is not None and os.path.isfile(location):\n f = open(location, 'rb')\n key = f.read()\n f.close()\n return key\n else:\n sys.exit(\"no key file found\")\n" ]
#!/usr/bin/env python """starting point for the playdeliver tool.""" import os import sys from sync_command import SyncCommand from oauth2client import client def _load_key(location): if location is not None and os.path.isfile(location): f = open(location, 'rb') key = f.read() f.close() ...
wooga/play-deliver
playdeliver/listing.py
upload
python
def upload(client, source_dir): print('') print('upload store listings') print('---------------------') listings_folder = os.path.join(source_dir, 'listings') langfolders = filter(os.path.isdir, list_dir_abspath(listings_folder)) for language_dir in langfolders: language = os.path.basen...
Upload listing files in source_dir. folder herachy.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/listing.py#L8-L24
[ "def list_dir_abspath(path):\n \"\"\"\n Return a list absolute file paths.\n\n see mkdir_p os.listdir.\n \"\"\"\n return map(lambda f: os.path.join(path, f), os.listdir(path))\n" ]
"""This module helps for uploading and downloading listings from/to play.""" import os import json from file_util import mkdir_p from file_util import list_dir_abspath def download(client, target_dir): """Download listing files from play and saves them into folder herachy.""" print('') print('download st...
wooga/play-deliver
playdeliver/listing.py
download
python
def download(client, target_dir): print('') print('download store listings') print('---------------------') listings = client.list('listings') for listing in listings: path = os.path.join(target_dir, 'listings', listing['language']) mkdir_p(path) with open(os.path.join(path, ...
Download listing files from play and saves them into folder herachy.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/listing.py#L27-L40
[ "def mkdir_p(path):\n \"\"\"Create a new directory with with all missing folders in between.\"\"\"\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n" ]
"""This module helps for uploading and downloading listings from/to play.""" import os import json from file_util import mkdir_p from file_util import list_dir_abspath def upload(client, source_dir): """Upload listing files in source_dir. folder herachy.""" print('') print('upload store listings') pri...
wooga/play-deliver
playdeliver/image.py
upload
python
def upload(client, source_dir): print('') print('upload images') print('-------------') base_image_folders = [ os.path.join(source_dir, 'images', x) for x in image_types] for type_folder in base_image_folders: if os.path.exists(type_folder): image_type = os.path.basename...
Upload images to play store. The function will iterate through source_dir and upload all matching image_types found in folder herachy.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L23-L43
[ "def list_dir_abspath(path):\n \"\"\"\n Return a list absolute file paths.\n\n see mkdir_p os.listdir.\n \"\"\"\n return map(lambda f: os.path.join(path, f), os.listdir(path))\n", "def delete_and_upload_images(client, image_type, language, base_dir):\n \"\"\"\n Delete and upload images with g...
"""This module helps for uploading and downloading images from/to play.""" import imghdr import httplib2 import os from file_util import mkdir_p from file_util import list_dir_abspath image_types = ["featureGraphic", "icon", "phoneScreenshots", "promoGraphic", ...
wooga/play-deliver
playdeliver/image.py
delete_and_upload_images
python
def delete_and_upload_images(client, image_type, language, base_dir): print('{0} {1}'.format(image_type, language)) files_in_dir = os.listdir(os.path.join(base_dir, language)) delete_result = client.deleteall( 'images', imageType=image_type, language=language) deleted = delete_result.get('delet...
Delete and upload images with given image_type and language. Function will stage delete and stage upload all found images in matching folders.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L46-L69
null
"""This module helps for uploading and downloading images from/to play.""" import imghdr import httplib2 import os from file_util import mkdir_p from file_util import list_dir_abspath image_types = ["featureGraphic", "icon", "phoneScreenshots", "promoGraphic", ...
wooga/play-deliver
playdeliver/image.py
download
python
def download(client, target_dir): print('download image previews') print( "Warning! Downloaded images are only previews!" "They may be to small for upload.") tree = {} listings = client.list('listings') languages = map(lambda listing: listing['language'], listings) parameters = ...
Download images from play store into folder herachy.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L72-L118
[ "def mkdir_p(path):\n \"\"\"Create a new directory with with all missing folders in between.\"\"\"\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n", "def load_and...
"""This module helps for uploading and downloading images from/to play.""" import imghdr import httplib2 import os from file_util import mkdir_p from file_util import list_dir_abspath image_types = ["featureGraphic", "icon", "phoneScreenshots", "promoGraphic", ...
wooga/play-deliver
playdeliver/image.py
load_and_save_image
python
def load_and_save_image(url, destination): from urllib2 import Request, urlopen, URLError, HTTPError # create the url and the request req = Request(url) # Open the url try: f = urlopen(req) print "downloading " + url # Open our local file for writing local_file = o...
Download image from given url and saves it to destination.
train
https://github.com/wooga/play-deliver/blob/9de0f35376f5342720b3a90bd3ca296b1f3a3f4c/playdeliver/image.py#L121-L154
null
"""This module helps for uploading and downloading images from/to play.""" import imghdr import httplib2 import os from file_util import mkdir_p from file_util import list_dir_abspath image_types = ["featureGraphic", "icon", "phoneScreenshots", "promoGraphic", ...
Kopachris/seshet
seshet/bot.py
_add_channel_names
python
def _add_channel_names(client, e): chan = IRCstr(e.channel) names = set([IRCstr(n) for n in e.name_list]) client.channels[chan] = SeshetChannel(chan, names)
Add a new channel to self.channels and initialize its user list. Called as event handler for RPL_NAMES events. Do not call directly.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L517-L525
null
"""Implement SeshetBot as subclass of ircutils3.bot.SimpleBot.""" import logging import os from io import StringIO from datetime import datetime from ircutils3 import bot, client from .utils import KVStore, Storage, IRCstr class SeshetUser(object): """Represent one IRC user.""" def __init__(self, nick, us...
Kopachris/seshet
seshet/bot.py
SeshetUser.join
python
def join(self, channel): if channel not in self.channels: channel.users.add(self.nick) self.channels.append(channel)
Add this user to the channel's user list and add the channel to this user's list of joined channels.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L23-L30
null
class SeshetUser(object): """Represent one IRC user.""" def __init__(self, nick, user, host): logging.debug("Building new SeshetUser, %s", nick) self.nick = IRCstr(nick) self.user = user self.host = host self.channels = [] def join(self, channel): """Add thi...
Kopachris/seshet
seshet/bot.py
SeshetUser.part
python
def part(self, channel): if channel in self.channels: channel.users.remove(self.nick) self.channels.remove(channel)
Remove this user from the channel's user list and remove the channel from this user's list of joined channels.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L32-L39
null
class SeshetUser(object): """Represent one IRC user.""" def __init__(self, nick, user, host): logging.debug("Building new SeshetUser, %s", nick) self.nick = IRCstr(nick) self.user = user self.host = host self.channels = [] def join(self, channel): """Add thi...
Kopachris/seshet
seshet/bot.py
SeshetUser.quit
python
def quit(self): for c in self.channels: c.users.remove(self.nick) self.channels = []
Remove this user from all channels and reinitialize the user's list of joined channels.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L41-L48
null
class SeshetUser(object): """Represent one IRC user.""" def __init__(self, nick, user, host): logging.debug("Building new SeshetUser, %s", nick) self.nick = IRCstr(nick) self.user = user self.host = host self.channels = [] def join(self, channel): """Add thi...
Kopachris/seshet
seshet/bot.py
SeshetUser.change_nick
python
def change_nick(self, nick): old_nick = self.nick self.nick = IRCstr(nick) for c in self.channels: c.users.remove(old_nick) c.users.add(self.nick)
Update this user's nick in all joined channels.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L50-L58
null
class SeshetUser(object): """Represent one IRC user.""" def __init__(self, nick, user, host): logging.debug("Building new SeshetUser, %s", nick) self.nick = IRCstr(nick) self.user = user self.host = host self.channels = [] def join(self, channel): """Add thi...
Kopachris/seshet
seshet/bot.py
SeshetChannel.log_message
python
def log_message(self, user, message): if isinstance(user, SeshetUser): user = user.nick elif not isinstance(user, IRCstr): user = IRCstr(user) time = datetime.utcnow() self.message_log.append((time, user, message)) while len...
Log a channel message. This log acts as a sort of cache so that recent activity can be searched by the bot and command modules without querying the database.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L77-L94
null
class SeshetChannel(object): """Represent one IRC channel.""" def __init__(self, name, users, log_size=100): self.name = IRCstr(name) self.users = users self.message_log = [] self._log_size = log_size def log_message(self, user, message): """Log a channel message. ...
Kopachris/seshet
seshet/bot.py
SeshetBot.log
python
def log(self, etype, source, msg='', target='', hostmask='', params=''): self.db.event_log.insert(event_type=etype, event_time=datetime.utcnow(), source=source, target=target, ...
Log an event in the database. Required: `etype` - event type. One of 'PRIVMSG', 'QUIT', 'PART', 'ACTION', 'NICK', 'JOIN', 'MODE', 'KICK', 'CTCP', or 'ERROR'. Enforced by database model. `source` - source of the event. Usually a user. For NICK eve...
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L163-L194
null
class SeshetBot(bot.SimpleBot): """Extend `ircutils3.bot.SimpleBot`. Each instance represents one bot, connected to one IRC network. Each instance should have its own database, but can make use of any shared command modules. The modules may have to be added to the bot's database if the bot wasn't c...
Kopachris/seshet
seshet/bot.py
SeshetBot.get_unique_users
python
def get_unique_users(self, chan): chan = IRCstr(chan) these_users = self.channels[chan].users other_users = set() for c in self.channels.values(): if c.name != chan: other_users |= c.users return these_users - other_users
Get the set of users that are unique to the given channel (i.e. not present in any other channel the bot is in).
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L279-L292
null
class SeshetBot(bot.SimpleBot): """Extend `ircutils3.bot.SimpleBot`. Each instance represents one bot, connected to one IRC network. Each instance should have its own database, but can make use of any shared command modules. The modules may have to be added to the bot's database if the bot wasn't c...
Kopachris/seshet
seshet/bot.py
SeshetBot.connect
python
def connect(self, *args, **kwargs): defaults = {} for i, k in enumerate(('host', 'port', 'channel', 'use_ssl', 'password')): if i < len(args): defaults[k] = args[i] elif k in kwargs: defaults[k] = kwargs[k] else: def_k ...
Extend `client.SimpleClient.connect()` with defaults
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L430-L454
null
class SeshetBot(bot.SimpleBot): """Extend `ircutils3.bot.SimpleBot`. Each instance represents one bot, connected to one IRC network. Each instance should have its own database, but can make use of any shared command modules. The modules may have to be added to the bot's database if the bot wasn't c...
Kopachris/seshet
seshet/bot.py
SeshetBot._log_to_file
python
def _log_to_file(self, etype, source, msg='', target='', hostmask='', params=''): today = datetime.utcnow() # TODO: Use self.locale['timezone'] for changing time date = today.strftime(self.locale['date_fmt']) time = today.strftime(self.locale['time_fmt']) datetime_s = today.strft...
Override `log()` if bot is not initialized with a database connection. Do not call this method directly.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L460-L482
null
class SeshetBot(bot.SimpleBot): """Extend `ircutils3.bot.SimpleBot`. Each instance represents one bot, connected to one IRC network. Each instance should have its own database, but can make use of any shared command modules. The modules may have to be added to the bot's database if the bot wasn't c...
Kopachris/seshet
seshet/bot.py
SeshetBot._loop
python
def _loop(self, map): try: from asyncore import poll except ImportError: raise Exception("Couldn't find poll function. Cannot start bot.") while map: self.before_poll() poll(timeout=30.0, map=map) self.after_poll()
The main loop. Poll sockets for I/O and run any other functions that need to be run every loop.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/bot.py#L502-L514
[ "def before_poll(self):\n \"\"\"Called each loop before polling sockets for I/O.\"\"\"\n pass\n", "def after_poll(self):\n \"\"\"Called each loop after polling sockets for I/O and\n handling any queued events.\n \"\"\"\n pass\n" ]
class SeshetBot(bot.SimpleBot): """Extend `ircutils3.bot.SimpleBot`. Each instance represents one bot, connected to one IRC network. Each instance should have its own database, but can make use of any shared command modules. The modules may have to be added to the bot's database if the bot wasn't c...
Kopachris/seshet
seshet/config.py
build_db_tables
python
def build_db_tables(db): if not isinstance(db, DAL) or not db._uri: raise Exception("Need valid DAL object to define tables") # event log - self-explanatory, logs all events db.define_table('event_log', Field('event_type'), Field('event_time', 'datetime'...
Build Seshet's basic database schema. Requires one parameter, `db` as `pydal.DAL` instance.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/config.py#L121-L153
null
"""Define default configuration, read configuration file, and apply configuration to SeshetBot instance. """ from configparser import ConfigParser from pydal import DAL, Field default_config = """ [connection] # passed to SeshetBot.connect() server: chat.freenode.net port: 6667 channels: #botwar ssl: False [client...
Kopachris/seshet
seshet/config.py
build_bot
python
def build_bot(config_file=None): from . import bot config = ConfigParser(interpolation=None) if config_file is None: config.read_string(default_config) elif isinstance(config_file, ConfigParser): config = config_file else: config.read(config_file) # shorter nam...
Parse a config and return a SeshetBot instance. After, the bot can be run simply by calling .connect() and then .start() Optional arguments: config_file - valid file path or ConfigParser instance If config_file is None, will read default config defined in this module.
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/config.py#L156-L222
[ "def build_db_tables(db):\n \"\"\"Build Seshet's basic database schema. Requires one parameter,\n `db` as `pydal.DAL` instance.\n \"\"\"\n\n if not isinstance(db, DAL) or not db._uri:\n raise Exception(\"Need valid DAL object to define tables\")\n\n # event log - self-explanatory, logs all eve...
"""Define default configuration, read configuration file, and apply configuration to SeshetBot instance. """ from configparser import ConfigParser from pydal import DAL, Field default_config = """ [connection] # passed to SeshetBot.connect() server: chat.freenode.net port: 6667 channels: #botwar ssl: False [client...
Kopachris/seshet
seshet/utils.py
Storage.getlist
python
def getlist(self, key): value = self.get(key, []) if value is None or isinstance(value, (list, tuple)): return value else: return [value]
Returns a Storage value as a list. If the value is a list it will be returned as-is. If object is None, an empty list will be returned. Otherwise, `[value]` will be returned. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage() >>...
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L94-L120
null
class Storage(dict): """A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`, and setting obj.foo = None deletes item foo. Example: >>> o = Storage(a=1) >>> print o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> print o[...
Kopachris/seshet
seshet/utils.py
Storage.getfirst
python
def getfirst(self, key, default=None): values = self.getlist(key) return values[0] if values else default
Returns the first value of a list or the value itself when given a `request.vars` style key. If the value is a list, its first item will be returned; otherwise, the value will be returned as-is. Example output for a query string of `?x=abc&y=abc&y=def`:: >>> request = Stor...
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L122-L144
[ "def getlist(self, key):\n \"\"\"Returns a Storage value as a list.\n\n If the value is a list it will be returned as-is.\n If object is None, an empty list will be returned.\n Otherwise, `[value]` will be returned.\n\n Example output for a query string of `?x=abc&y=abc&y=def`::\n\n >>> reques...
class Storage(dict): """A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`, and setting obj.foo = None deletes item foo. Example: >>> o = Storage(a=1) >>> print o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> print o[...
Kopachris/seshet
seshet/utils.py
Storage.getlast
python
def getlast(self, key, default=None): values = self.getlist(key) return values[-1] if values else default
Returns the last value of a list or value itself when given a `request.vars` style key. If the value is a list, the last item will be returned; otherwise, the value will be returned as-is. Simulated output with a query string of `?x=abc&y=abc&y=def`:: >>> request = Storage...
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L146-L168
[ "def getlist(self, key):\n \"\"\"Returns a Storage value as a list.\n\n If the value is a list it will be returned as-is.\n If object is None, an empty list will be returned.\n Otherwise, `[value]` will be returned.\n\n Example output for a query string of `?x=abc&y=abc&y=def`::\n\n >>> reques...
class Storage(dict): """A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`, and setting obj.foo = None deletes item foo. Example: >>> o = Storage(a=1) >>> print o.a 1 >>> o['a'] 1 >>> o.a = 2 >>> print o[...
Kopachris/seshet
seshet/utils.py
KVStore.popitem
python
def popitem(self): all_items = self.items() removed_item = random.choice(all_items) self[removed_item[0]] = None return removed_item
Unlike `dict.popitem()`, this is actually random
train
https://github.com/Kopachris/seshet/blob/d55bae01cff56762c5467138474145a2c17d1932/seshet/utils.py#L381-L386
[ "def items(self):\n return zip(self.keys(), self.values())\n" ]
class KVStore: """Create a key/value store in the bot's database for each command module to use for persistent storage. Can be accessed either like a class: >>> store = KVStore(db) >>> store.foo = 'bar' >>> store.foo 'bar' Or like a dict: >>> store['spam'] = 'e...
zlobspb/txtarantool
txtarantool.py
Request.pack_int_base128
python
def pack_int_base128(cls, value): assert isinstance(value, int) if value < 1 << 14: return cls._int_base128[value] if value < 1 << 21: return struct_BBB.pack( value >> 14 & 0xff | 0x80, value >> 7 & 0xff | 0x80, value & 0x7...
Pack integer value using LEB128 encoding :param value: integer value to encode :type value: int :return: encoded value :rtype: bytes
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L156-L193
null
class Request(object): """ Represents a single request to the server in compliance with the Tarantool protocol. Responsible for data encapsulation and builds binary packet to be sent to the server. This is the abstract base class. Specific request types are implemented by the inherited classes. """...
zlobspb/txtarantool
txtarantool.py
Request.pack_str
python
def pack_str(cls, value): assert isinstance(value, str) value_len_packed = cls.pack_int_base128(len(value)) return struct.pack("<%ds%ds" % (len(value_len_packed), len(value)), value_len_packed, value)
Pack string field <field> ::= <int32_varint><data> :param value: string to be packed :type value: bytes or str :return: packed value :rtype: bytes
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L196-L209
[ "def pack_int_base128(cls, value):\n \"\"\"\n Pack integer value using LEB128 encoding\n :param value: integer value to encode\n :type value: int\n\n :return: encoded value\n :rtype: bytes\n \"\"\"\n assert isinstance(value, int)\n if value < 1 << 14:\n return cls._int_base128[valu...
class Request(object): """ Represents a single request to the server in compliance with the Tarantool protocol. Responsible for data encapsulation and builds binary packet to be sent to the server. This is the abstract base class. Specific request types are implemented by the inherited classes. """...
zlobspb/txtarantool
txtarantool.py
Request.pack_unicode
python
def pack_unicode(cls, value, charset="utf-8", errors="strict"): assert isinstance(value, unicode) try: value = value.encode(charset, errors) except UnicodeEncodeError as e: raise InvalidData("Error encoding unicode value '%s': %s" % (repr(value), e)) value_len_p...
Pack string field <field> ::= <int32_varint><data> :param value: string to be packed :type value: unicode :return: packed value :rtype: bytes
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L212-L231
[ "def pack_int_base128(cls, value):\n \"\"\"\n Pack integer value using LEB128 encoding\n :param value: integer value to encode\n :type value: int\n\n :return: encoded value\n :rtype: bytes\n \"\"\"\n assert isinstance(value, int)\n if value < 1 << 14:\n return cls._int_base128[valu...
class Request(object): """ Represents a single request to the server in compliance with the Tarantool protocol. Responsible for data encapsulation and builds binary packet to be sent to the server. This is the abstract base class. Specific request types are implemented by the inherited classes. """...
zlobspb/txtarantool
txtarantool.py
Request.pack_field
python
def pack_field(self, value): if isinstance(value, str): return self.pack_str(value) elif isinstance(value, unicode): return self.pack_unicode(value, self.charset, self.errors) elif isinstance(value, int): return self.pack_int(value) elif isinstance(val...
Pack single field (string or integer value) <field> ::= <int32_varint><data> :param value: value to be packed :type value: bytes, str, int or long :return: packed value :rtype: bytes
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L233-L253
[ "def pack_int(value):\n \"\"\"\n Pack integer field\n <field> ::= <int32_varint><data>\n\n :param value: integer value to be packed\n :type value: int\n\n :return: packed value\n :rtype: bytes\n \"\"\"\n assert isinstance(value, (int, long))\n return struct_BL.pack(4, value)\n", "def...
class Request(object): """ Represents a single request to the server in compliance with the Tarantool protocol. Responsible for data encapsulation and builds binary packet to be sent to the server. This is the abstract base class. Specific request types are implemented by the inherited classes. """...
zlobspb/txtarantool
txtarantool.py
Request.pack_tuple
python
def pack_tuple(self, values): assert isinstance(values, (tuple, list)) cardinality = [struct_L.pack(len(values))] packed_items = [self.pack_field(v) for v in values] return b''.join(itertools.chain(cardinality, packed_items))
Pack tuple of values <tuple> ::= <cardinality><field>+ :param value: tuple to be packed :type value: tuple of scalar values (bytes, str or int) :return: packed tuple :rtype: bytes
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L255-L269
null
class Request(object): """ Represents a single request to the server in compliance with the Tarantool protocol. Responsible for data encapsulation and builds binary packet to be sent to the server. This is the abstract base class. Specific request types are implemented by the inherited classes. """...
zlobspb/txtarantool
txtarantool.py
Response._unpack_int_base128
python
def _unpack_int_base128(varint, offset): res = ord(varint[offset]) if ord(varint[offset]) >= 0x80: offset += 1 res = ((res - 0x80) << 7) + ord(varint[offset]) if ord(varint[offset]) >= 0x80: offset += 1 res = ((res - 0x80) << 7) + ord(v...
Implement Perl unpack's 'w' option, aka base 128 decoding.
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L548-L563
null
class Response(list): """ Represents a single response from the server in compliance with the Tarantool protocol. Responsible for data encapsulation (i.e. received list of tuples) and parses binary packet received from the server. """ def __init__(self, header, body, charset="utf-8", errors="st...
zlobspb/txtarantool
txtarantool.py
Response._unpack_tuple
python
def _unpack_tuple(self, buff): cardinality = struct_L.unpack_from(buff)[0] _tuple = ['']*cardinality offset = 4 # The first 4 bytes in the response body is the <count> we have already read for i in xrange(cardinality): field_size, offset = self._unpack_int_base128(buff, of...
Unpacks the tuple from byte buffer <tuple> ::= <cardinality><field>+ :param buff: byte array of the form <cardinality><field>+ :type buff: ctypes buffer or bytes :return: tuple of unpacked values :rtype: tuple
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L565-L585
null
class Response(list): """ Represents a single response from the server in compliance with the Tarantool protocol. Responsible for data encapsulation (i.e. received list of tuples) and parses binary packet received from the server. """ def __init__(self, header, body, charset="utf-8", errors="st...
zlobspb/txtarantool
txtarantool.py
Response._unpack_body
python
def _unpack_body(self, buff): # Unpack <return_code> and <count> (how many records affected or selected) self._return_code = struct_L.unpack_from(buff, offset=0)[0] # Separate return_code and completion_code self._completion_status = self._return_code & 0x00ff self._return_code...
Parse the response body. After body unpacking its data available as python list of tuples For each request type the response body has the same format: <insert_response_body> ::= <count> | <count><fq_tuple> <update_response_body> ::= <count> | <count><fq_tuple> <delete_response_b...
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L587-L639
[ "def _unpack_tuple(self, buff):\n \"\"\"\n Unpacks the tuple from byte buffer\n <tuple> ::= <cardinality><field>+\n\n :param buff: byte array of the form <cardinality><field>+\n :type buff: ctypes buffer or bytes\n\n :return: tuple of unpacked values\n :rtype: tuple\n \"\"\"\n cardinality...
class Response(list): """ Represents a single response from the server in compliance with the Tarantool protocol. Responsible for data encapsulation (i.e. received list of tuples) and parses binary packet received from the server. """ def __init__(self, header, body, charset="utf-8", errors="st...
zlobspb/txtarantool
txtarantool.py
Response._cast_field
python
def _cast_field(self, cast_to, value): if cast_to in (int, long, str): return cast_to(value) elif cast_to == unicode: try: value = value.decode(self.charset, self.errors) except UnicodeEncodeError, e: raise InvalidData("Error encoding u...
Convert field type from raw bytes to native python type :param cast_to: native python type to cast to :type cast_to: a type object (one of bytes, int, unicode (str for py3k)) :param value: raw value from the database :type value: bytes :return: converted value :rtype: v...
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L686-L710
null
class Response(list): """ Represents a single response from the server in compliance with the Tarantool protocol. Responsible for data encapsulation (i.e. received list of tuples) and parses binary packet received from the server. """ def __init__(self, header, body, charset="utf-8", errors="st...
zlobspb/txtarantool
txtarantool.py
Response._cast_tuple
python
def _cast_tuple(self, values): result = [] for i, value in enumerate(values): if i < len(self.field_types): result.append(self._cast_field(self.field_types[i], value)) else: result.append(self._cast_field(self.field_types[-1], value)) retu...
Convert values of the tuple from raw bytes to native python types :param values: tuple of the raw database values :type value: tuple of bytes :return: converted tuple value :rtype: value of native python types (bytes, int, unicode (or str for py3k))
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L712-L729
null
class Response(list): """ Represents a single response from the server in compliance with the Tarantool protocol. Responsible for data encapsulation (i.e. received list of tuples) and parses binary packet received from the server. """ def __init__(self, header, body, charset="utf-8", errors="st...
zlobspb/txtarantool
txtarantool.py
TarantoolProtocol.ping
python
def ping(self): d = self.replyQueue.get_ping() packet = RequestPing(self.charset, self.errors) self.transport.write(bytes(packet)) return d.addCallback(self.handle_reply, self.charset, self.errors, None)
send ping packet to tarantool server and receive response with empty body
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L865-L872
null
class TarantoolProtocol(IprotoPacketReceiver, policies.TimeoutMixin, object): """ Tarantool client protocol. """ space_no = 0 def __init__(self, charset="utf-8", errors="strict"): self.charset = charset self.errors = errors self.replyQueue = IproDeferredQueue() def con...
zlobspb/txtarantool
txtarantool.py
TarantoolProtocol.insert
python
def insert(self, space_no, *args): d = self.replyQueue.get() packet = RequestInsert(self.charset, self.errors, d._ipro_request_id, space_no, Request.TNT_FLAG_ADD, *args) self.transport.write(bytes(packet)) return d.addCallback(self.handle_reply, self.charset, self.errors, None)
insert tuple, if primary key exists server will return error
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L874-L881
null
class TarantoolProtocol(IprotoPacketReceiver, policies.TimeoutMixin, object): """ Tarantool client protocol. """ space_no = 0 def __init__(self, charset="utf-8", errors="strict"): self.charset = charset self.errors = errors self.replyQueue = IproDeferredQueue() def con...
zlobspb/txtarantool
txtarantool.py
TarantoolProtocol.select
python
def select(self, space_no, index_no, field_types, *args): d = self.replyQueue.get() packet = RequestSelect(self.charset, self.errors, d._ipro_request_id, space_no, index_no, 0, 0xffffffff, *args) self.transport.write(bytes(packet)) return d.addCallback(self.handle_reply, self.charset, se...
select tuple(s)
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L893-L900
null
class TarantoolProtocol(IprotoPacketReceiver, policies.TimeoutMixin, object): """ Tarantool client protocol. """ space_no = 0 def __init__(self, charset="utf-8", errors="strict"): self.charset = charset self.errors = errors self.replyQueue = IproDeferredQueue() def con...
zlobspb/txtarantool
txtarantool.py
TarantoolProtocol.update
python
def update(self, space_no, key_tuple, op_list): d = self.replyQueue.get() packet = RequestUpdate(self.charset, self.errors, d._ipro_request_id, space_no, 0, key_tuple, op_list) self.transport.write(bytes(packet)) return d.addCallback(self.handle_reply, self.charset, self.errors, None)
send update command(s)
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L911-L918
null
class TarantoolProtocol(IprotoPacketReceiver, policies.TimeoutMixin, object): """ Tarantool client protocol. """ space_no = 0 def __init__(self, charset="utf-8", errors="strict"): self.charset = charset self.errors = errors self.replyQueue = IproDeferredQueue() def con...
zlobspb/txtarantool
txtarantool.py
TarantoolProtocol.update_ret
python
def update_ret(self, space_no, field_types, key_tuple, op_list): d = self.replyQueue.get() packet = RequestUpdate(self.charset, self.errors, d._ipro_request_id, space_no, Request.TNT_FLAG_RETURN, key_tuple, op_list) self.transport.write(bytes(packet)) retur...
send update command(s), updated tuple(s) is(are) sent back
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L920-L928
null
class TarantoolProtocol(IprotoPacketReceiver, policies.TimeoutMixin, object): """ Tarantool client protocol. """ space_no = 0 def __init__(self, charset="utf-8", errors="strict"): self.charset = charset self.errors = errors self.replyQueue = IproDeferredQueue() def con...
zlobspb/txtarantool
txtarantool.py
TarantoolProtocol.delete
python
def delete(self, space_no, *args): d = self.replyQueue.get() packet = RequestDelete(self.charset, self.errors, d._ipro_request_id, space_no, 0, *args) self.transport.write(bytes(packet)) return d.addCallback(self.handle_reply, self.charset, self.errors, None)
delete tuple by primary key
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L930-L937
null
class TarantoolProtocol(IprotoPacketReceiver, policies.TimeoutMixin, object): """ Tarantool client protocol. """ space_no = 0 def __init__(self, charset="utf-8", errors="strict"): self.charset = charset self.errors = errors self.replyQueue = IproDeferredQueue() def con...
zlobspb/txtarantool
txtarantool.py
TarantoolProtocol.call
python
def call(self, proc_name, field_types, *args): d = self.replyQueue.get() packet = RequestCall(self.charset, self.errors, d._ipro_request_id, proc_name, 0, *args) self.transport.write(bytes(packet)) return d.addCallback(self.handle_reply, self.charset, self.errors, field_types)
call server procedure
train
https://github.com/zlobspb/txtarantool/blob/e8d451d53e1c99ccf1f23ce36a9c589fa2ed0350/txtarantool.py#L985-L992
null
class TarantoolProtocol(IprotoPacketReceiver, policies.TimeoutMixin, object): """ Tarantool client protocol. """ space_no = 0 def __init__(self, charset="utf-8", errors="strict"): self.charset = charset self.errors = errors self.replyQueue = IproDeferredQueue() def con...
mayfield/cellulario
cellulario/tier.py
Tier.make_gatherer
python
def make_gatherer(cls, cell, source_tiers, gatherby): pending = collections.defaultdict(dict) tier_hashes = [hash(x) for x in source_tiers] @asyncio.coroutine def organize(route, *args): srchash = hash(route.source) key = gatherby(*args) group = pendi...
Produce a single source tier that gathers from a set of tiers when the key function returns a unique result for each tier.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L77-L93
null
class Tier(object): """ A managed layer of IO operations. Generally speaking a tier should consist of one or more IO operations that are of consistent complexity with a single emit data type. A tier emits data instead of returning it. Emissions flow from one tier to the next set of tiers until the fin...
mayfield/cellulario
cellulario/tier.py
Tier.enqueue_task
python
def enqueue_task(self, source, *args): yield from self.cell.coord.enqueue(self) route = Route(source, self.cell, self.spec, self.emit) self.cell.loop.create_task(self.coord_wrap(route, *args)) # To guarantee that the event loop works fluidly, we manually yield # once. The coordin...
Enqueue a task execution. It will run in the background as soon as the coordinator clears it to do so.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L132-L141
null
class Tier(object): """ A managed layer of IO operations. Generally speaking a tier should consist of one or more IO operations that are of consistent complexity with a single emit data type. A tier emits data instead of returning it. Emissions flow from one tier to the next set of tiers until the fin...
mayfield/cellulario
cellulario/tier.py
Tier.coord_wrap
python
def coord_wrap(self, *args): yield from self.cell.coord.start(self) yield from self.coro(*args) yield from self.cell.coord.finish(self)
Wrap the coroutine with coordination throttles.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L144-L148
null
class Tier(object): """ A managed layer of IO operations. Generally speaking a tier should consist of one or more IO operations that are of consistent complexity with a single emit data type. A tier emits data instead of returning it. Emissions flow from one tier to the next set of tiers until the fin...
mayfield/cellulario
cellulario/tier.py
Tier.emit
python
def emit(self, *args): if self.buffer is not None: self.buffer.extend(args) if self.buffer_max_size is not None: flush = len(self.buffer) >= self.buffer_max_size else: flush = yield from self.cell.coord.flush(self) if flush: ...
Send data to the next tier(s). This call can be delayed if the coordinator thinks the backlog is too high for any of the emit destinations. Likewise when buffering emit values prior to enqueuing them we ask the coordinator if we should flush the buffer each time in case the coordinator...
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L151-L168
null
class Tier(object): """ A managed layer of IO operations. Generally speaking a tier should consist of one or more IO operations that are of consistent complexity with a single emit data type. A tier emits data instead of returning it. Emissions flow from one tier to the next set of tiers until the fin...
mayfield/cellulario
cellulario/tier.py
Tier.flush
python
def flush(self): if self.buffer is None: return data = self.buffer self.buffer = [] for x in self.dests: yield from x.enqueue_task(self, *data)
Flush the buffer of buffered tiers to our destination tiers.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L171-L178
null
class Tier(object): """ A managed layer of IO operations. Generally speaking a tier should consist of one or more IO operations that are of consistent complexity with a single emit data type. A tier emits data instead of returning it. Emissions flow from one tier to the next set of tiers until the fin...
mayfield/cellulario
cellulario/tier.py
Tier.add_source
python
def add_source(self, tier): tier.add_dest(self) self.sources.append(tier)
Schedule this tier to be called when another tier emits.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L180-L183
null
class Tier(object): """ A managed layer of IO operations. Generally speaking a tier should consist of one or more IO operations that are of consistent complexity with a single emit data type. A tier emits data instead of returning it. Emissions flow from one tier to the next set of tiers until the fin...
mayfield/cellulario
cellulario/tier.py
Tier.close
python
def close(self): self.cell = None self.coro = None self.buffer = None del self.dests[:] del self.sources[:]
Free any potential cycles.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/tier.py#L189-L195
null
class Tier(object): """ A managed layer of IO operations. Generally speaking a tier should consist of one or more IO operations that are of consistent complexity with a single emit data type. A tier emits data instead of returning it. Emissions flow from one tier to the next set of tiers until the fin...
mayfield/cellulario
cellulario/iocell.py
IOCell.init_event_loop
python
def init_event_loop(self): self.loop = asyncio.new_event_loop() self.loop.set_debug(self.debug) if hasattr(self.loop, '_set_coroutine_wrapper'): self.loop._set_coroutine_wrapper(self.debug) elif self.debug: warnings.warn("Cannot set debug on loop: %s" % self.loop)...
Every cell should have its own event loop for proper containment. The type of event loop is not so important however.
train
https://github.com/mayfield/cellulario/blob/e9dc10532a0357bc90ebaa2655b36822f9249673/cellulario/iocell.py#L82-L97
null
class IOCell(object): """ A consolidated multi-level bundle of IO operations. This is a useful facility when doing tiered IO calls such as http requests to get a list of things and then a fanout of http requests on each of those things and so forth. The aim of this code is to provide simplified inputs...