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 |
|---|---|---|---|---|---|---|---|---|---|
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_child | python | def get_child(self, *types):
children = list(self.get_children(*types))
return children[0] if any(children) else None | :param types: list of requested types.
:return: the first (and in most useful cases only) child of specific type(s). | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L109-L115 | [
"def get_children(self, *types):\n \"\"\" Get all children of the requested types.\n\n :param attribute: requested children types.\n :return: list of all children of the requested types.\n \"\"\"\n pass\n"
] | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_by_type | python | def get_objects_by_type(self, *types):
if not types:
return self.objects.values()
types_l = [o.lower() for o in types]
return [o for o in self.objects.values() if o.obj_type().lower() in types_l] | Returned objects stored in memory (without re-reading them from the TGN).
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L144-L156 | null | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_object_by_type | python | def get_object_by_type(self, *types):
children = self.get_objects_by_type(*types)
return children[0] if any(children) else None | :param types: requested object types.
:return: the child of the specified types. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L158-L164 | [
"def get_objects_by_type(self, *types):\n \"\"\" Returned objects stored in memory (without re-reading them from the TGN).\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\... | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_by_type_in_subtree | python | def get_objects_by_type_in_subtree(self, *types):
typed_objects = self.get_objects_by_type(*types)
for child in self.objects.values():
typed_objects += child.get_objects_by_type_in_subtree(*types)
return typed_objects | :param types: requested object types.
:return: all children of the specified types. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L166-L175 | [
"def get_objects_by_type(self, *types):\n \"\"\" Returned objects stored in memory (without re-reading them from the TGN).\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\... | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_or_children_by_type | python | def get_objects_or_children_by_type(self, *types):
objects = self.get_objects_by_type(*types)
return objects if objects else self.get_children(*types) | Get objects if children already been read or get children.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L177-L187 | [
"def get_objects_by_type(self, *types):\n \"\"\" Returned objects stored in memory (without re-reading them from the TGN).\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\... | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_object_or_child_by_type | python | def get_object_or_child_by_type(self, *types):
objects = self.get_objects_or_children_by_type(*types)
return objects[0] if any(objects) else None | Get object if child already been read or get child.
Use this method for fast access to objects in case of static configurations.
:param types: requested object types.
:return: all children of the specified types. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L189-L199 | [
"def get_objects_or_children_by_type(self, *types):\n \"\"\" Get objects if children already been read or get children.\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\"\n... | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_with_object | python | def get_objects_with_object(self, obj_type, *child_types):
return [o for o in self.get_objects_by_type(obj_type) if
o.get_objects_by_type(*child_types)] | :param obj_type: requested object type.
:param child_type: requested child types.
:return: all children of the requested type that have the requested child types. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L201-L209 | [
"def get_objects_by_type(self, *types):\n \"\"\" Returned objects stored in memory (without re-reading them from the TGN).\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\... | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_without_object | python | def get_objects_without_object(self, obj_type, *child_types):
return [o for o in self.get_objects_by_type(obj_type) if
not o.get_objects_by_type(*child_types)] | :param obj_type: requested object type.
:param child_type: unrequested child types.
:return: all children of the requested type that do not have the unrequested child types. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L211-L218 | [
"def get_objects_by_type(self, *types):\n \"\"\" Returned objects stored in memory (without re-reading them from the TGN).\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\... | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_with_attribute | python | def get_objects_with_attribute(self, obj_type, attribute, value):
return [o for o in self.get_objects_by_type(obj_type) if o.get_attribute(attribute) == value] | :param obj_type: requested object type.
:param attribute: requested attribute.
:param value: requested attribute value.
:return: all children of the requested type that have the requested attribute == requested value. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L220-L227 | [
"def get_objects_by_type(self, *types):\n \"\"\" Returned objects stored in memory (without re-reading them from the TGN).\n\n Use this method for fast access to objects in case of static configurations.\n\n :param types: requested object types.\n :return: all children of the specified types.\n \"\"\... | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_ancestor_object_by_type | python | def get_ancestor_object_by_type(self, obj_type):
if self.type.lower() == obj_type.lower():
return self
else:
if not self.parent:
return None
return self.parent.get_ancestor_object_by_type(obj_type) | :param obj_type: requested ancestor type.
:return: the ancestor of the object who's type is obj_type if exists else None. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L229-L240 | null | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.del_object_from_parent | python | def del_object_from_parent(self):
if self.parent:
self.parent.objects.pop(self.ref) | Delete object from parent object. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L249-L252 | null | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_object.py | TgnObject.get_objects_of_class | python | def get_objects_of_class(cls):
return list(o for o in gc.get_objects() if isinstance(o, cls)) | :return: all instances of the requested class. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_object.py#L262-L266 | null | class TgnObject(object):
""" Base class for all TGN classes. """
objects = OrderedDict()
""" Dictionary of child objects <object reference: object name>. """
def __init__(self, **data):
""" Create new TGN object in the API.
If object does not exist on the chassis, create it on the cha... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | get_args_pairs | python | def get_args_pairs(arguments):
return ' '.join(' '.join(['-' + k, tcl_str(str(v))]) for k, v in arguments.items()) | :param arguments: Python dictionary of TGN API command arguments <key, value>.
:returns: Tcl list of argument pairs <-key, value> to be used in TGN API commands. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L46-L52 | null | """
Base class and utilities for TGN Python Tcl wrapper.
@author: yoram.shamir
"""
import sys
from os import path
import logging
import time
import re
from threading import Thread
from queue import Queue
from trafficgenerator.tgn_utils import new_log_file
# IxExplorer only uses Tcl utilities (over socket) without T... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | tcl_list_2_py_list | python | def tcl_list_2_py_list(tcl_list, within_tcl_str=False):
if not within_tcl_str:
tcl_list = tcl_str(tcl_list)
return tcl_interp_g.eval('join ' + tcl_list + ' LiStSeP').split('LiStSeP') if tcl_list else [] | Convert Tcl list to Python list using Tcl interpreter.
:param tcl_list: string representing the Tcl string.
:param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string.
:return: Python list equivalent to the Tcl ist.
:rtye: list | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L68-L79 | [
"def tcl_str(string=''):\n \"\"\"\n :param string: Python string.\n :returns: Tcl string surrounded by {}.\n \"\"\"\n\n return ' {' + string + '} '\n"
] | """
Base class and utilities for TGN Python Tcl wrapper.
@author: yoram.shamir
"""
import sys
from os import path
import logging
import time
import re
from threading import Thread
from queue import Queue
from trafficgenerator.tgn_utils import new_log_file
# IxExplorer only uses Tcl utilities (over socket) without T... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | py_list_to_tcl_list | python | def py_list_to_tcl_list(py_list):
py_list_str = [str(s) for s in py_list]
return tcl_str(tcl_interp_g.eval('split' + tcl_str('\t'.join(py_list_str)) + '\\t')) | Convert Python list to Tcl list using Tcl interpreter.
:param py_list: Python list.
:type py_list: list
:return: string representing the Tcl string equivalent to the Python list. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L82-L91 | [
"def tcl_str(string=''):\n \"\"\"\n :param string: Python string.\n :returns: Tcl string surrounded by {}.\n \"\"\"\n\n return ' {' + string + '} '\n"
] | """
Base class and utilities for TGN Python Tcl wrapper.
@author: yoram.shamir
"""
import sys
from os import path
import logging
import time
import re
from threading import Thread
from queue import Queue
from trafficgenerator.tgn_utils import new_log_file
# IxExplorer only uses Tcl utilities (over socket) without T... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | TgnTclConsole.eval | python | def eval(self, command):
# Some operations (like take ownership) may take long time.
con_command_out = self._con.send_cmd(command, timeout=256)
if 'ERROR_SEND_CMD_EXIT_DUE_TO_TIMEOUT' in con_command_out:
raise Exception('{} - command timeout'.format(command))
command = comman... | @summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L158-L177 | null | class TgnTclConsole(object):
""" Tcl interpreter over console.
Current implementation is a sample extracted from actual project where the console is telnet to Windows machine.
"""
def __init__(self, con, tcl_exe):
""" Start Tcl interpreter on console.
:param con: console.
:par... |
shmir/PyTrafficGenerator | trafficgenerator/tgn_tcl.py | TgnTclWrapper.eval | python | def eval(self, command):
if self.logger.handlers:
self.logger.debug(command.decode('utf-8'))
if self.tcl_script:
self.tcl_script.info(command)
self.rc = self.tcl_interp.eval(command)
if self.logger.handlers:
self.logger.debug('\t' + self.rc.decode('ut... | Execute Tcl command.
Write the command to tcl script (.tcl) log file.
Execute the command.
Write the command and the output to general (.txt) log file.
:param command: Command to execute.
:returns: command raw output. | train | https://github.com/shmir/PyTrafficGenerator/blob/382e5d549c83404af2a6571fe19c9e71df8bac14/trafficgenerator/tgn_tcl.py#L208-L226 | null | class TgnTclWrapper(object):
""" Tcl connectivity for TGN projects. """
def __init__(self, logger, tcl_interp=None):
""" Init Python Tk package.
Add logger to log Tcl commands only.
This creates a clean Tcl script that can be used later for debug.
We assume that there might hav... |
bluedynamics/cone.ugm | src/cone/ugm/browser/autoincrement.py | AutoIncrementForm.prepare | python | def prepare(_next, self):
_next(self)
if not self.autoincrement_support:
return
id_field = self.form['id']
del id_field.attrs['required']
id_field.attrs['disabled'] = 'disabled'
id_field.getter = _('auto_incremented', default='auto incremented') | Hook after prepare and set 'id' disabled. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/autoincrement.py#L52-L61 | null | class AutoIncrementForm(Behavior):
"""Plumbing behavior for setting user id by auto increment logic.
For user add form.
"""
@default
@property
def autoincrement_support(self):
cfg = ugm_general(self.model)
return cfg.attrs['user_id_autoincrement'] == 'True'
@default
@p... |
bluedynamics/cone.ugm | src/cone/ugm/browser/actions.py | delete_user_action | python | def delete_user_action(model, request):
try:
users = model.parent.backend
uid = model.model.name
del users[uid]
users()
model.parent.invalidate()
localizer = get_localizer(request)
message = localizer.translate(_(
'delete_user_from_database',
... | Delete user from database. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/actions.py#L67-L90 | null | from cone.ugm.model.group import Group
from cone.ugm.model.user import User
from pyramid.i18n import get_localizer
from pyramid.i18n import TranslationStringFactory
from pyramid.view import view_config
_ = TranslationStringFactory('cone.ugm')
#########################################################################... |
bluedynamics/cone.ugm | src/cone/ugm/browser/actions.py | user_add_to_group_action | python | def user_add_to_group_action(model, request):
group_id = request.params.get('id')
if not group_id:
group_ids = request.params.getall('id[]')
else:
group_ids = [group_id]
try:
user = model.model
validate_add_users_to_groups(model, [user.id], group_ids)
groups = use... | Add user to group. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/actions.py#L99-L151 | [
"def validate_add_users_to_groups(model, user_ids, group_ids):\n if not model.local_manager_consider_for_user:\n return\n lm_gids = model.local_manager_target_gids\n for group_id in group_ids:\n if group_id not in lm_gids:\n raise ManageMembershipError(LM_TARGET_GID_NOT_ALLOWED, gr... | from cone.ugm.model.group import Group
from cone.ugm.model.user import User
from pyramid.i18n import get_localizer
from pyramid.i18n import TranslationStringFactory
from pyramid.view import view_config
_ = TranslationStringFactory('cone.ugm')
#########################################################################... |
bluedynamics/cone.ugm | src/cone/ugm/browser/actions.py | delete_group_action | python | def delete_group_action(model, request):
try:
groups = model.parent.backend
uid = model.model.name
del groups[uid]
groups()
model.parent.invalidate()
except Exception as e:
return {
'success': False,
'message': str(e)
}
localize... | Delete group from database. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/actions.py#L237-L259 | null | from cone.ugm.model.group import Group
from cone.ugm.model.user import User
from pyramid.i18n import get_localizer
from pyramid.i18n import TranslationStringFactory
from pyramid.view import view_config
_ = TranslationStringFactory('cone.ugm')
#########################################################################... |
bluedynamics/cone.ugm | src/cone/ugm/browser/actions.py | group_add_user_action | python | def group_add_user_action(model, request):
user_id = request.params.get('id')
if not user_id:
user_ids = request.params.getall('id[]')
else:
user_ids = [user_id]
try:
group = model.model
validate_add_users_to_groups(model, user_ids, [group.id])
for user_id in user... | Add user to group. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/actions.py#L268-L319 | [
"def validate_add_users_to_groups(model, user_ids, group_ids):\n if not model.local_manager_consider_for_user:\n return\n lm_gids = model.local_manager_target_gids\n for group_id in group_ids:\n if group_id not in lm_gids:\n raise ManageMembershipError(LM_TARGET_GID_NOT_ALLOWED, gr... | from cone.ugm.model.group import Group
from cone.ugm.model.user import User
from pyramid.i18n import get_localizer
from pyramid.i18n import TranslationStringFactory
from pyramid.view import view_config
_ = TranslationStringFactory('cone.ugm')
#########################################################################... |
bluedynamics/cone.ugm | src/cone/ugm/browser/roles.py | PrincipalRolesForm.prepare | python | def prepare(_next, self):
_next(self)
if not self.roles_support:
return
if not self.request.has_permission('manage', self.model.parent):
# XXX: yafowil selection display renderer
return
value = []
if self.action_resource == 'edit':
... | Hook after prepare and set 'principal_roles' as selection to
``self.form``. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/roles.py#L26-L52 | null | class PrincipalRolesForm(Behavior):
@default
@property
def roles_vocab(self):
from cone.app.security import DEFAULT_ROLES
return DEFAULT_ROLES
@default
@property
def roles_support(self):
return ugm_roles(self.model).ldap_roles_container_valid
@plumb
@plumb
... |
bluedynamics/cone.ugm | src/cone/ugm/__init__.py | initialize_ugm | python | def initialize_ugm(config, global_config, local_config):
# custom UGM styles
cfg.merged.css.protected.append((static_resources, 'styles.css'))
# custom UGM javascript
cfg.merged.js.protected.append((static_resources, 'ugm.js'))
# UGM settings
register_config('ugm_general', GeneralSettings)
... | Initialize UGM. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/__init__.py#L62-L103 | null | from cone.app import cfg
from cone.app import get_root
from cone.app import main_hook
from cone.app import register_config
from cone.app import register_entry
from cone.app.security import acl_registry
from cone.app.ugm import ugm_backend
from cone.app.ugm import UGMFactory
from cone.ugm.browser import static_resources... |
bluedynamics/cone.ugm | src/cone/ugm/browser/expires.py | expiration_extractor | python | def expiration_extractor(widget, data):
active = int(data.request.get('%s.active' % widget.name, '0'))
if not active:
return 0
expires = data.extracted
if expires:
return time.mktime(expires.utctimetuple())
return UNSET | Extract expiration information.
- If active flag not set, Account is disabled (value 0).
- If active flag set and value is UNSET, account never expires.
- If active flag set and datetime choosen, account expires at given
datetime.
- Timestamp in seconds since epoch is returned. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/expires.py#L23-L38 | null | from cone.ugm.model.utils import ugm_general
from datetime import datetime
from plumber import Behavior
from plumber import plumb
from pyramid.i18n import TranslationStringFactory
from yafowil.base import factory
from yafowil.base import fetch_value
from yafowil.base import UNSET
from yafowil.common import generic_extr... |
bluedynamics/cone.ugm | src/cone/ugm/browser/expires.py | ExpirationForm.prepare | python | def prepare(_next, self):
_next(self)
cfg = ugm_general(self.model)
if cfg.attrs['users_account_expiration'] != 'True':
return
mode = 'edit'
if not self.request.has_permission(
'manage_expiration', self.model.parent):
mode = 'display'
... | Hook after prepare and set expiration widget to
``self.form``. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/expires.py#L127-L158 | [
"def ugm_general(model):\n return model.root['settings']['ugm_general']\n"
] | class ExpirationForm(Behavior):
"""Expiration field plumbing behavior for user forms.
"""
@plumb
@plumb
def save(_next, self, widget, data):
if self.request.has_permission(
'manage_expiration', self.model.parent):
cfg = ugm_general(self.model)
if cf... |
bluedynamics/cone.ugm | src/cone/ugm/browser/portrait.py | portrait_image | python | def portrait_image(model, request):
response = Response()
cfg = ugm_general(model)
response.body = model.attrs[cfg.attrs['users_portrait_attr']]
response.headers['Content-Type'] = 'image/jpeg'
response.headers['Cache-Control'] = 'max-age=0'
return response | XXX: needs polishing. Return configured default portrait if not set
on user. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/portrait.py#L22-L31 | [
"def ugm_general(model):\n return model.root['settings']['ugm_general']\n"
] | from cone.app.browser.utils import make_url
from cone.ugm.model.user import User
from cone.ugm.model.utils import ugm_general
from io import BytesIO
from plumber import Behavior
from plumber import default
from plumber import plumb
from pyramid.i18n import TranslationStringFactory
from pyramid.response import Response
... |
bluedynamics/cone.ugm | src/cone/ugm/browser/portrait.py | PortraitForm.prepare | python | def prepare(_next, self):
_next(self)
if not self.portrait_support:
return
model = self.model
request = self.request
if request.has_permission('edit_user', model.parent):
mode = 'edit'
else:
mode = 'display'
cfg = ugm_general(mo... | Hook after prepare and set 'portrait' as image widget to
``self.form``. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/portrait.py#L45-L92 | [
"def ugm_general(model):\n return model.root['settings']['ugm_general']\n"
] | class PortraitForm(Behavior):
"""Plumbing behavior for setting user portrait image.
"""
@default
@property
def portrait_support(self):
cfg = ugm_general(self.model)
return cfg.attrs['users_portrait'] == 'True'
@plumb
@plumb
def save(_next, self, widget, data):
... |
bluedynamics/cone.ugm | src/cone/ugm/model/localmanager.py | LocalManager.local_manager_consider_for_user | python | def local_manager_consider_for_user(self):
if not self.local_management_enabled:
return False
request = get_current_request()
if authenticated_userid(request) == security.ADMIN_USER:
return False
roles = security.authenticated_user(request).roles
if 'admin... | Flag whether local manager ACL should be considered for current
authenticated user. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/model/localmanager.py#L73-L85 | null | class LocalManager(Behavior):
"""Behavior providing local manager information for authenticated user.
"""
@finalize
@property
def local_management_enabled(self):
"""Flag whether local management is enabled.
"""
general_settings = self.root['settings']['ugm_general']
... |
bluedynamics/cone.ugm | src/cone/ugm/model/localmanager.py | LocalManager.local_manager_gid | python | def local_manager_gid(self):
config = self.root['settings']['ugm_localmanager'].attrs
user = security.authenticated_user(get_current_request())
if not user:
return None
gids = user.group_ids
adm_gids = list()
for gid in gids:
rule = config.get(gid)... | Group id of local manager group of current authenticated member.
Currently a user can be assigned only to one local manager group. If
more than one local manager group is configured, an error is raised. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/model/localmanager.py#L89-L114 | null | class LocalManager(Behavior):
"""Behavior providing local manager information for authenticated user.
"""
@finalize
@property
def local_management_enabled(self):
"""Flag whether local management is enabled.
"""
general_settings = self.root['settings']['ugm_general']
... |
bluedynamics/cone.ugm | src/cone/ugm/model/localmanager.py | LocalManager.local_manager_rule | python | def local_manager_rule(self):
adm_gid = self.local_manager_gid
if not adm_gid:
return None
config = self.root['settings']['ugm_localmanager'].attrs
return config[adm_gid] | Return rule for local manager. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/model/localmanager.py#L118-L125 | null | class LocalManager(Behavior):
"""Behavior providing local manager information for authenticated user.
"""
@finalize
@property
def local_management_enabled(self):
"""Flag whether local management is enabled.
"""
general_settings = self.root['settings']['ugm_general']
... |
bluedynamics/cone.ugm | src/cone/ugm/model/localmanager.py | LocalManager.local_manager_target_uids | python | def local_manager_target_uids(self):
groups = self.root['groups'].backend
managed_uids = set()
for gid in self.local_manager_target_gids:
group = groups.get(gid)
if group:
managed_uids.update(group.member_ids)
return list(managed_uids) | Target uid's for local manager. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/model/localmanager.py#L149-L158 | null | class LocalManager(Behavior):
"""Behavior providing local manager information for authenticated user.
"""
@finalize
@property
def local_management_enabled(self):
"""Flag whether local management is enabled.
"""
general_settings = self.root['settings']['ugm_general']
... |
bluedynamics/cone.ugm | src/cone/ugm/model/localmanager.py | LocalManager.local_manager_is_default | python | def local_manager_is_default(self, adm_gid, gid):
config = self.root['settings']['ugm_localmanager'].attrs
rule = config[adm_gid]
if gid not in rule['target']:
raise Exception(u"group '%s' not managed by '%s'" % (gid, adm_gid))
return gid in rule['default'] | Check whether gid is default group for local manager group. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/model/localmanager.py#L161-L168 | null | class LocalManager(Behavior):
"""Behavior providing local manager information for authenticated user.
"""
@finalize
@property
def local_management_enabled(self):
"""Flag whether local management is enabled.
"""
general_settings = self.root['settings']['ugm_general']
... |
bluedynamics/cone.ugm | src/cone/ugm/browser/user.py | UserForm.form_field_definitions | python | def form_field_definitions(self):
schema = copy.deepcopy(form_field_definitions.user)
uid, login = self._get_auth_attrs()
if uid != login:
field = schema.get(login, schema['default'])
if field['chain'].find('*optional_login') == -1:
field['chain'] = '%s:%s... | Hook optional_login extractor if necessary for form defaults. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/user.py#L183-L198 | [
"def _get_auth_attrs(self):\n config = ugm_users(self.model)\n aliases = config.attrs.users_aliases_attrmap\n return aliases['id'], aliases['login']\n"
] | class UserForm(PrincipalForm):
form_name = 'userform'
@property
def form_attrmap(self):
settings = ugm_users(self.model)
return settings.attrs.users_form_attrmap
@property
def exists(self, widget, data):
uid = data.extracted
if uid is UNSET:
return dat... |
bluedynamics/cone.ugm | src/cone/ugm/browser/remote.py | remote_add_user | python | def remote_add_user(model, request):
params = request.params
uid = params.get('id')
if not uid:
return {
'success': False,
'message': u"No user ID given.",
}
users = model.backend
if uid in users:
return {
'success': False,
'm... | Add user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
New user id.
password
User password to be set ... | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/remote.py#L12-L124 | [
"def ugm_users(model):\n return model.root['settings']['ugm_users']\n"
] | from cone.ugm.model.users import Users
from cone.ugm.model.utils import ugm_users
from pyramid.view import view_config
@view_config(
name='remote_add_user',
accept='application/json',
renderer='json',
context=Users,
permission='add_user')
@view_config(
name='remote_delete_user',
accept=... |
bluedynamics/cone.ugm | src/cone/ugm/browser/remote.py | remote_delete_user | python | def remote_delete_user(model, request):
params = request.params
uid = params.get('id')
if not uid:
return {
'success': False,
'message': u"No user ID given.",
}
users = model.backend
if uid not in users:
return {
'success': False,
... | Remove user via remote service.
Returns a JSON response containing success state and a message indicating
what happened::
{
success: true, // respective false
message: 'message'
}
Expected request parameters:
id
Id of user to delete. | train | https://github.com/bluedynamics/cone.ugm/blob/3c197075f3f6e94781289311c5637bb9c8e5597c/src/cone/ugm/browser/remote.py#L133-L180 | null | from cone.ugm.model.users import Users
from cone.ugm.model.utils import ugm_users
from pyramid.view import view_config
@view_config(
name='remote_add_user',
accept='application/json',
renderer='json',
context=Users,
permission='add_user')
def remote_add_user(model, request):
"""Add user via re... |
alfredodeza/notario | notario/store.py | create_store | python | def create_store():
new_storage = _proxy('store')
_state.store = type('store', (object,), {})
new_storage.store = dict()
return new_storage.store | A helper for setting the _proxy and slapping the store
object for us.
:return: A thread-local storage as a dictionary | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/store.py#L25-L35 | [
"def _proxy(key):\n class ObjectProxy(object):\n def __getattr__(self, attr):\n obj = getattr(_state, key)\n return getattr(obj, attr)\n\n def __setattr__(self, attr, value):\n obj = getattr(_state, key)\n return setattr(obj, attr, value)\n\n def _... | """
Thread-safe storage for Notario.
"""
from threading import local
_state = local()
def _proxy(key):
class ObjectProxy(object):
def __getattr__(self, attr):
obj = getattr(_state, key)
return getattr(obj, attr)
def __setattr__(self, attr, value):
obj = getatt... |
alfredodeza/notario | notario/validators/types.py | string | python | def string(_object):
if is_callable(_object):
_validator = _object
@wraps(_validator)
def decorated(value):
ensure(isinstance(value, basestring), "not of type string")
return _validator(value)
return decorated
ensure(isinstance(_object, basestring), "not ... | Validates a given input is of type string.
Example usage::
data = {'a' : 21}
schema = (string, 21)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the argument is a callable, the decorating... | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/validators/types.py#L10-L34 | [
"def ensure(assertion, message=None):\n \"\"\"\n Checks an assertion argument for truth-ness. Will return ``True`` or\n explicitly raise ``AssertionError``. This is to deal with environments\n using ``python -O` or ``PYTHONOPTIMIZE=``.\n\n :param assertion: some value to evaluate for truth-ness\n ... | """
Basic type validators
"""
from functools import wraps
from notario._compat import basestring
from notario.exceptions import Invalid
from notario.utils import is_callable, forced_leaf_validator, ensure
def boolean(_object):
"""
Validates a given input is of type boolean.
Example usage::
data... |
alfredodeza/notario | notario/validators/types.py | boolean | python | def boolean(_object):
if is_callable(_object):
_validator = _object
@wraps(_validator)
def decorated(value):
ensure(isinstance(value, bool), "not of type boolean")
return _validator(value)
return decorated
ensure(isinstance(_object, bool), "not of type bo... | Validates a given input is of type boolean.
Example usage::
data = {'a' : True}
schema = ('a', boolean)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the argument is a callable, the decor... | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/validators/types.py#L37-L62 | [
"def ensure(assertion, message=None):\n \"\"\"\n Checks an assertion argument for truth-ness. Will return ``True`` or\n explicitly raise ``AssertionError``. This is to deal with environments\n using ``python -O` or ``PYTHONOPTIMIZE=``.\n\n :param assertion: some value to evaluate for truth-ness\n ... | """
Basic type validators
"""
from functools import wraps
from notario._compat import basestring
from notario.exceptions import Invalid
from notario.utils import is_callable, forced_leaf_validator, ensure
def string(_object):
"""
Validates a given input is of type string.
Example usage::
data = ... |
alfredodeza/notario | notario/validators/types.py | dictionary | python | def dictionary(_object, *args):
error_msg = 'not of type dictionary'
if is_callable(_object):
_validator = _object
@wraps(_validator)
def decorated(value):
ensure(isinstance(value, dict), error_msg)
return _validator(value)
return decorated
try:
... | Validates a given input is of type dictionary.
Example usage::
data = {'a' : {'b': 1}}
schema = ('a', dictionary)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the argument is a callable,... | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/validators/types.py#L66-L98 | [
"def ensure(assertion, message=None):\n \"\"\"\n Checks an assertion argument for truth-ness. Will return ``True`` or\n explicitly raise ``AssertionError``. This is to deal with environments\n using ``python -O` or ``PYTHONOPTIMIZE=``.\n\n :param assertion: some value to evaluate for truth-ness\n ... | """
Basic type validators
"""
from functools import wraps
from notario._compat import basestring
from notario.exceptions import Invalid
from notario.utils import is_callable, forced_leaf_validator, ensure
def string(_object):
"""
Validates a given input is of type string.
Example usage::
data = ... |
alfredodeza/notario | notario/validators/types.py | array | python | def array(_object):
if is_callable(_object):
_validator = _object
@wraps(_validator)
def decorated(value):
ensure(isinstance(value, list), "not of type array")
return _validator(value)
return decorated
ensure(isinstance(_object, list), "not of type array"... | Validates a given input is of type list.
Example usage::
data = {'a' : [1,2]}
schema = ('a', array)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the argument is a callable, the decoratin... | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/validators/types.py#L101-L126 | [
"def ensure(assertion, message=None):\n \"\"\"\n Checks an assertion argument for truth-ness. Will return ``True`` or\n explicitly raise ``AssertionError``. This is to deal with environments\n using ``python -O` or ``PYTHONOPTIMIZE=``.\n\n :param assertion: some value to evaluate for truth-ness\n ... | """
Basic type validators
"""
from functools import wraps
from notario._compat import basestring
from notario.exceptions import Invalid
from notario.utils import is_callable, forced_leaf_validator, ensure
def string(_object):
"""
Validates a given input is of type string.
Example usage::
data = ... |
alfredodeza/notario | notario/validators/types.py | integer | python | def integer(_object):
if is_callable(_object):
_validator = _object
@wraps(_validator)
def decorated(value):
ensure(isinstance(value, int), "not of type int")
return _validator(value)
return decorated
ensure(isinstance(_object, int), "not of type int") | Validates a given input is of type int..
Example usage::
data = {'a' : 21}
schema = ('a', integer)
You can also use this as a decorator, as a way to check for the
input before it even hits a validator you may be writing.
.. note::
If the argument is a callable, the decorating... | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/validators/types.py#L129-L153 | [
"def ensure(assertion, message=None):\n \"\"\"\n Checks an assertion argument for truth-ness. Will return ``True`` or\n explicitly raise ``AssertionError``. This is to deal with environments\n using ``python -O` or ``PYTHONOPTIMIZE=``.\n\n :param assertion: some value to evaluate for truth-ness\n ... | """
Basic type validators
"""
from functools import wraps
from notario._compat import basestring
from notario.exceptions import Invalid
from notario.utils import is_callable, forced_leaf_validator, ensure
def string(_object):
"""
Validates a given input is of type string.
Example usage::
data = ... |
alfredodeza/notario | notario/validators/iterables.py | BasicIterableValidator.safe_type | python | def safe_type(self, data, tree):
if not isinstance(data, list):
name = self.__class__.__name__
msg = "did not pass validation against callable: %s" % name
reason = 'expected a list but got %s' % safe_repr(data)
raise Invalid(self.schema, tree, reason=reason, pair=... | Make sure that the incoming data complies with the class type we
are expecting it to be. In this case, classes that inherit from this
base class expect data to be of type ``list``. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/validators/iterables.py#L22-L32 | [
"def safe_repr(obj):\n \"\"\"\n Try to get ``__name__`` first, ``__class__.__name__`` second\n and finally, if we can't get anything acceptable, fallback\n to user a ``repr()`` call.\n \"\"\"\n name = getattr(obj, '__name__', getattr(obj.__class__, '__name__'))\n if name == 'ndict':\n na... | class BasicIterableValidator(object):
"""
Base class for iterable validators, can be sub-classed
for other type of iterable validators but should not be
used directly.
"""
__validator_leaf__ = True
def __init__(self, schema):
self.schema = schema
|
alfredodeza/notario | notario/utils.py | safe_repr | python | def safe_repr(obj):
name = getattr(obj, '__name__', getattr(obj.__class__, '__name__'))
if name == 'ndict':
name = 'dict'
return name or repr(obj) | Try to get ``__name__`` first, ``__class__.__name__`` second
and finally, if we can't get anything acceptable, fallback
to user a ``repr()`` call. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/utils.py#L10-L19 | null | import warnings
def is_callable(data):
if hasattr(data, '__call__'):
return True
return False
# Backwards compatibility
def optional(validator):
from notario import decorators
msg = "import optional from notario.decorators, not from utils"
warnings.warn(msg, DeprecationWarning, stacklev... |
alfredodeza/notario | notario/utils.py | re_sort | python | def re_sort(data):
keys = sorted(data.keys())
new_data = {}
for number, key in enumerate(keys):
new_data[number] = data[key]
return new_data | A data with keys that are not enumerated sequentially will be
re sorted and sequentially ordered.
For example::
>>> data = {16: ('1', 'b'), 3: ('1', 'a')}
>>> re_sort(data)
>>> {0: ('1', 'a'), 1: ('1', 'b')} | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/utils.py#L39-L54 | null | import warnings
def is_callable(data):
if hasattr(data, '__call__'):
return True
return False
def safe_repr(obj):
"""
Try to get ``__name__`` first, ``__class__.__name__`` second
and finally, if we can't get anything acceptable, fallback
to user a ``repr()`` call.
"""
name = ... |
alfredodeza/notario | notario/utils.py | sift | python | def sift(data, required_items=None):
required_items = required_items or []
new_data = {}
for k, v in data.items():
if v[0] in required_items:
new_data[k] = v
continue
for required_item in required_items:
key = getattr(required_item, '_object', False)
... | Receive a ``data`` object that will be in the form
of a normalized structure (e.g. ``{0: {'a': 0}}``) and
filter out keys that match the ``required_items``. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/utils.py#L57-L75 | [
"def re_sort(data):\n \"\"\"\n A data with keys that are not enumerated sequentially will be\n re sorted and sequentially ordered.\n\n For example::\n\n >>> data = {16: ('1', 'b'), 3: ('1', 'a')}\n >>> re_sort(data)\n >>> {0: ('1', 'a'), 1: ('1', 'b')}\n \"\"\"\n keys = sorted... | import warnings
def is_callable(data):
if hasattr(data, '__call__'):
return True
return False
def safe_repr(obj):
"""
Try to get ``__name__`` first, ``__class__.__name__`` second
and finally, if we can't get anything acceptable, fallback
to user a ``repr()`` call.
"""
name = ... |
alfredodeza/notario | notario/utils.py | data_item | python | def data_item(data):
if isinstance(data, ndict):
# OK, we have something that looks like {0: ('a', 'b')}
# or something that is a regular dictionary
# so try to return 'a' regardless of the length
for item in data:
return repr(data[item][0])
elif isinstance(data, dict... | When trying to return a meaningful error about an unexpected data item
we cannot just `repr(data)` as that could show a gigantic data struture.
This utility should try to get the key of the first item or the single item
in the data structure. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/utils.py#L95-L114 | null | import warnings
def is_callable(data):
if hasattr(data, '__call__'):
return True
return False
def safe_repr(obj):
"""
Try to get ``__name__`` first, ``__class__.__name__`` second
and finally, if we can't get anything acceptable, fallback
to user a ``repr()`` call.
"""
name = ... |
alfredodeza/notario | notario/utils.py | ensure | python | def ensure(assertion, message=None):
message = message or assertion
if not assertion:
raise AssertionError(message)
return True | Checks an assertion argument for truth-ness. Will return ``True`` or
explicitly raise ``AssertionError``. This is to deal with environments
using ``python -O` or ``PYTHONOPTIMIZE=``.
:param assertion: some value to evaluate for truth-ness
:param message: optional message used for raising AssertionError | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/utils.py#L144-L158 | null | import warnings
def is_callable(data):
if hasattr(data, '__call__'):
return True
return False
def safe_repr(obj):
"""
Try to get ``__name__`` first, ``__class__.__name__`` second
and finally, if we can't get anything acceptable, fallback
to user a ``repr()`` call.
"""
name = ... |
alfredodeza/notario | notario/decorators.py | not_empty | python | def not_empty(_object):
if is_callable(_object):
_validator = _object
@wraps(_validator)
@instance_of()
def decorated(value):
ensure(value, "%s is empty" % safe_repr(value))
return _validator(value)
return decorated
try:
ensure(len(_object... | Validates the given input (has to be a valid data structure) is empty.
Input *has* to be one of: `list`, `dict`, or `string`.
It is specially useful when most of the validators being created are
dealing with data structures that should not be empty. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/decorators.py#L72-L92 | [
"def ensure(assertion, message=None):\n \"\"\"\n Checks an assertion argument for truth-ness. Will return ``True`` or\n explicitly raise ``AssertionError``. This is to deal with environments\n using ``python -O` or ``PYTHONOPTIMIZE=``.\n\n :param assertion: some value to evaluate for truth-ness\n ... | from functools import wraps
from notario.utils import is_callable, safe_repr, ensure
class instance_of(object):
"""
When trying to make sure the value is coming from any number of valid
objects, you will want to use this decorator as it will make sure that
before executing the validator it will comply... |
alfredodeza/notario | notario/decorators.py | optional | python | def optional(_object):
if is_callable(_object):
validator = _object
@wraps(validator)
def decorated(value):
if value:
return validator(value)
return
return decorated
else:
def optional(*args):
return _object
op... | This decorator has a double functionality, it can wrap validators and make
them optional or it can wrap keys and make that entry optional.
**Optional Validator:**
Allows to have validators work only when there is a value that contains
some data, otherwise it will just not pass the information to the ac... | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/decorators.py#L95-L156 | [
"def is_callable(data):\n if hasattr(data, '__call__'):\n return True\n return False\n"
] | from functools import wraps
from notario.utils import is_callable, safe_repr, ensure
class instance_of(object):
"""
When trying to make sure the value is coming from any number of valid
objects, you will want to use this decorator as it will make sure that
before executing the validator it will comply... |
alfredodeza/notario | notario/regex.py | chain | python | def chain(*regexes, **kwargs):
prepend_negation = kwargs.get('prepend_negation', True)
return Linker(regexes, prepend_negation=prepend_negation) | A helper function to interact with the regular expression engine
that compiles and applies partial matches to a string.
It expects key value tuples as arguments (any number of them) where the
first pair is the regex to compile and the latter is the message to display
when the regular expression does no... | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/regex.py#L57-L94 | null | import re
class Linker(list):
"""
This list-like object will receive key/value pairs as regexes with
accompanying failure error messages and upon a call, it will apply them
sequentially so that a user can understand at what point in the regex the
failure happened with a given value.
.. note::... |
alfredodeza/notario | notario/engine.py | validate | python | def validate(data, schema, defined_keys=False):
if isinstance(data, dict):
validator = Validator(data, schema, defined_keys=defined_keys)
validator.validate()
else:
raise TypeError('expected data to be of type dict, but got: %s' % type(data)) | Main entry point for the validation engine.
:param data: The incoming data, as a dictionary object.
:param schema: The schema from which data will be validated against | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/engine.py#L343-L354 | [
"def validate(self):\n if self.data == {} and self.schema:\n msg = 'has no data to validate against schema'\n reason = 'an empty dictionary object was provided'\n raise Invalid(None, {}, msg=msg, reason=reason, pair='value')\n self.traverser(self.data, self.schema, [])\n"
] | import sys
from notario.exceptions import Invalid, SchemaError
from notario.utils import (is_callable, sift, is_empty, re_sort, is_not_empty,
data_item, safe_repr, ensure)
from notario.normal import Data, Schema
from notario.validators import cherry_pick
class Validator(object):
def __... |
alfredodeza/notario | notario/engine.py | Validator.traverser | python | def traverser(self, data, schema, tree):
if hasattr(schema, '__validator_leaf__'):
return schema(data, tree)
if hasattr(schema, 'must_validate'): # cherry picking?
if not len(schema.must_validate):
reason = "must_validate attribute must not be empty"
... | Traverses the dictionary, recursing onto itself if
it sees appropriate key/value pairs that indicate that
there is a need for more validation in a branch below us. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/engine.py#L24-L118 | [
"def sift(data, required_items=None):\n \"\"\"\n Receive a ``data`` object that will be in the form\n of a normalized structure (e.g. ``{0: {'a': 0}}``) and\n filter out keys that match the ``required_items``.\n \"\"\"\n required_items = required_items or []\n new_data = {}\n for k, v in dat... | class Validator(object):
def __init__(self, data, schema, defined_keys=None):
if defined_keys:
schema = cherry_pick(schema)
self.data = Data(data, schema).normalized()
self.schema = Schema(data, schema).normalized()
def validate(self):
if self.data == {} and self.sc... |
alfredodeza/notario | notario/engine.py | Validator.key_leaf | python | def key_leaf(self, data, schema, tree):
key, value = data
schema_key, schema_value = schema
enforce(key, schema_key, tree, 'key') | The deepest validation we can make in any given circumstance for a key.
Does not recurse, it will just receive both values and the tree,
passing them on to the :fun:`enforce` function. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/engine.py#L121-L129 | [
"def enforce(data_item, schema_item, tree, pair):\n schema_is_optional = hasattr(schema_item, 'is_optional')\n if is_callable(schema_item) and not schema_is_optional:\n try:\n schema_item(data_item)\n except AssertionError:\n e = sys.exc_info()[1]\n if pair == 'v... | class Validator(object):
def __init__(self, data, schema, defined_keys=None):
if defined_keys:
schema = cherry_pick(schema)
self.data = Data(data, schema).normalized()
self.schema = Schema(data, schema).normalized()
def validate(self):
if self.data == {} and self.sc... |
alfredodeza/notario | notario/engine.py | Validator.value_leaf | python | def value_leaf(self, data, schema, tree):
key, value = data
schema_key, schema_value = schema
if hasattr(schema_value, '__validator_leaf__'):
return schema_value(value, tree)
enforce(value, schema_value, tree, 'value') | The deepest validation we can make in any given circumstance for
a value. Does not recurse, it will just receive both values and the
tree, passing them on to the :fun:`enforce` function. | train | https://github.com/alfredodeza/notario/blob/d5dc2edfcb75d9291ced3f2551f368c35dd31475/notario/engine.py#L131-L142 | [
"def enforce(data_item, schema_item, tree, pair):\n schema_is_optional = hasattr(schema_item, 'is_optional')\n if is_callable(schema_item) and not schema_is_optional:\n try:\n schema_item(data_item)\n except AssertionError:\n e = sys.exc_info()[1]\n if pair == 'v... | class Validator(object):
def __init__(self, data, schema, defined_keys=None):
if defined_keys:
schema = cherry_pick(schema)
self.data = Data(data, schema).normalized()
self.schema = Schema(data, schema).normalized()
def validate(self):
if self.data == {} and self.sc... |
meyersj/geotweet | geotweet/twitter/stream_steps.py | GeoFilterStep.validate_geotweet | python | def validate_geotweet(self, record):
if record and self._validate('user', record) \
and self._validate('coordinates', record):
return True
return False | check that stream record is actual tweet with coordinates | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/twitter/stream_steps.py#L53-L58 | [
"def _validate(self, key, record):\n if key in record and record[key]:\n return True\n return False\n"
] | class GeoFilterStep(ProcessStep):
"""
Process output from Twitter Streaming API
For each record output from the API will be called as argument to process.
That function will validate and convert tweet to desired format.
"""
def _validate(self, key, record):
if key in record and record[... |
meyersj/geotweet | geotweet/mapreduce/utils/lookup.py | SpatialLookup.get_object | python | def get_object(self, point, buffer_size=0, multiple=False):
# first search bounding boxes
# idx.intersection method modifies input if it is a list
try:
tmp = tuple(point)
except TypeError:
return None
# point must be in the form (minx, miny, maxx, maxy) or... | lookup object based on point as [longitude, latitude] | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L83-L101 | null | class SpatialLookup(FileReader):
""" Create a indexed spatial lookup of a geojson file """
idx = None
data_store = {}
def __init__(self, src=None):
if src:
if not self.is_valid_src(src):
error = "Arg src=< {0} > is invalid."
error += " Must be existi... |
meyersj/geotweet | geotweet/mapreduce/utils/lookup.py | SpatialLookup._build_from_geojson | python | def _build_from_geojson(self, src):
geojson = json.loads(self.read(src))
idx = index.Index()
data_store = {}
for i, feature in enumerate(geojson['features']):
feature = self._build_obj(feature)
idx.insert(i, feature['geometry'].bounds)
data_store[i] = ... | Build a RTree index to disk using bounding box of each feature | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L107-L116 | null | class SpatialLookup(FileReader):
""" Create a indexed spatial lookup of a geojson file """
idx = None
data_store = {}
def __init__(self, src=None):
if src:
if not self.is_valid_src(src):
error = "Arg src=< {0} > is invalid."
error += " Must be existi... |
meyersj/geotweet | geotweet/mapreduce/utils/lookup.py | CachedLookup.get | python | def get(self, point, buffer_size=0, multiple=False):
lon, lat = point
geohash = Geohash.encode(lat, lon, precision=self.precision)
key = (geohash, buffer_size, multiple)
if key in self.geohash_cache:
# cache hit on geohash
self.hit += 1
#print self.hit... | lookup state and county based on geohash of coordinates from tweet | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/lookup.py#L139-L157 | [
"def project(lonlat):\n return transform(proj4326, proj102005, *lonlat)\n"
] | class CachedLookup(SpatialLookup):
""" Cache results of spatial lookups """
geohash_cache = {}
def __init__(self, precision=7, *args, **kwargs):
super(CachedLookup, self).__init__(*args, **kwargs)
self.precision = precision
self.hit = 0
self.miss = 0
|
meyersj/geotweet | geotweet/mapreduce/metro_wordcount.py | MRMetroMongoWordCount.mapper_init | python | def mapper_init(self):
self.lookup = CachedMetroLookup(precision=GEOHASH_PRECISION)
self.extractor = WordExtractor() | build local spatial index of US metro areas | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L96-L99 | null | class MRMetroMongoWordCount(MRJob):
"""
Map Reduce job that counts word occurences for each US Metro Area
Requires a running MongoDB instance with us_metro_areas.geojson loaded
Mapper Init:
1. Build local Rtree spatial index of US metro areas
- geojson file downloaded from S3 buck... |
meyersj/geotweet | geotweet/mapreduce/metro_wordcount.py | MRMetroMongoWordCount.reducer_init_output | python | def reducer_init_output(self):
try:
self.mongo = MongoGeo(db=DB, collection=COLLECTION, timeout=MONGO_TIMEOUT)
except ServerSelectionTimeoutError:
# failed to connect to running MongoDB instance
self.mongo = None | establish connection to MongoDB | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/metro_wordcount.py#L124-L130 | null | class MRMetroMongoWordCount(MRJob):
"""
Map Reduce job that counts word occurences for each US Metro Area
Requires a running MongoDB instance with us_metro_areas.geojson loaded
Mapper Init:
1. Build local Rtree spatial index of US metro areas
- geojson file downloaded from S3 buck... |
meyersj/geotweet | geotweet/osm.py | OSMRunner.run | python | def run(self):
states = open(self.states, 'r').read().splitlines()
for state in states:
url = self.build_url(state)
log = "Downloading State < {0} > from < {1} >"
logging.info(log.format(state, url))
tmp = self.download(self.output, url, self.overwrite)
... | For each state in states file build url and download file | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L37-L45 | [
"def download(self, output_dir, url, overwrite):\n \"\"\" Dowload file to /tmp \"\"\"\n tmp = self.url2tmp(output_dir, url)\n if os.path.isfile(tmp) and not overwrite:\n logging.info(\"File {0} already exists. Skipping download.\".format(tmp))\n return tmp\n f = open(tmp, 'wb')\n loggin... | class OSMRunner(object):
"""
Downloads OSM extracts from GeoFabrik in pbf format
"""
def __init__(self, args):
self.states = args.states
if not args.states:
self.states = DEFAULT_STATES
self.output = args.output
self.overwrite = False
self.s3 = S3Load... |
meyersj/geotweet | geotweet/osm.py | OSMRunner.download | python | def download(self, output_dir, url, overwrite):
tmp = self.url2tmp(output_dir, url)
if os.path.isfile(tmp) and not overwrite:
logging.info("File {0} already exists. Skipping download.".format(tmp))
return tmp
f = open(tmp, 'wb')
logging.info("Downloading {0}".form... | Dowload file to /tmp | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L47-L65 | [
"def url2tmp(self, root, url):\n \"\"\" convert url path to filename \"\"\"\n filename = url.rsplit('/', 1)[-1]\n return os.path.join(root, filename)\n"
] | class OSMRunner(object):
"""
Downloads OSM extracts from GeoFabrik in pbf format
"""
def __init__(self, args):
self.states = args.states
if not args.states:
self.states = DEFAULT_STATES
self.output = args.output
self.overwrite = False
self.s3 = S3Load... |
meyersj/geotweet | geotweet/osm.py | OSMRunner.extract | python | def extract(self, pbf, output):
logging.info("Extracting POI nodes from {0} to {1}".format(pbf, output))
with open(output, 'w') as f:
# define callback for each node that is processed
def nodes_callback(nodes):
for node in nodes:
node_id, tags,... | extract POI nodes from osm pbf extract | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L67-L81 | null | class OSMRunner(object):
"""
Downloads OSM extracts from GeoFabrik in pbf format
"""
def __init__(self, args):
self.states = args.states
if not args.states:
self.states = DEFAULT_STATES
self.output = args.output
self.overwrite = False
self.s3 = S3Load... |
meyersj/geotweet | geotweet/osm.py | OSMRunner.url2tmp | python | def url2tmp(self, root, url):
filename = url.rsplit('/', 1)[-1]
return os.path.join(root, filename) | convert url path to filename | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/osm.py#L86-L89 | null | class OSMRunner(object):
"""
Downloads OSM extracts from GeoFabrik in pbf format
"""
def __init__(self, args):
self.states = args.states
if not args.states:
self.states = DEFAULT_STATES
self.output = args.output
self.overwrite = False
self.s3 = S3Load... |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.mapper_metro | python | def mapper_metro(self, _, data):
# OSM POI record
if 'tags' in data:
type_tag = 1
lonlat = data['coordinates']
payload = data['tags']
# Tweet with coordinates from Streaming API
elif 'user_id' in data:
type_tag = 2
# only allow ... | map each osm POI and geotweets based on spatial lookup of metro area | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L81-L108 | null | class POINearbyTweetsMRJob(MRJob):
""" Count common OSM points-of-interest around Tweets with coordinates """
INPUT_PROTOCOL = JSONValueProtocol
INTERNAL_PROTOCOL = JSONProtocol
OUTPUT_PROTOCOL = RawValueProtocol
SORT_VALUES = True
def steps(self):
return [
# 1. lookup metr... |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.reducer_metro | python | def reducer_metro(self, metro, values):
lookup = CachedLookup(precision=POI_GEOHASH_PRECISION)
for i, value in enumerate(values):
type_tag, lonlat, data = value
if type_tag == 1:
# OSM POI node, construct geojson and add to Rtree index
lookup.inser... | Output tags of POI locations nearby tweet locations
Values will be sorted coming into reducer.
First element in each value tuple will be either 1 (osm POI) or 2 (geotweet).
Build a spatial index with POI records.
For each tweet lookup nearby POI, and emit tag values for predefined tags. | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L110-L142 | [
"def project(lonlat):\n return transform(proj4326, proj102005, *lonlat)\n"
] | class POINearbyTweetsMRJob(MRJob):
""" Count common OSM points-of-interest around Tweets with coordinates """
INPUT_PROTOCOL = JSONValueProtocol
INTERNAL_PROTOCOL = JSONProtocol
OUTPUT_PROTOCOL = RawValueProtocol
SORT_VALUES = True
def steps(self):
return [
# 1. lookup metr... |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.reducer_count | python | def reducer_count(self, key, values):
total = sum(values)
metro, poi = key
# group data by metro areas for final output
yield metro, (total, poi) | count occurences for each (metro, POI) record | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L144-L149 | null | class POINearbyTweetsMRJob(MRJob):
""" Count common OSM points-of-interest around Tweets with coordinates """
INPUT_PROTOCOL = JSONValueProtocol
INTERNAL_PROTOCOL = JSONProtocol
OUTPUT_PROTOCOL = RawValueProtocol
SORT_VALUES = True
def steps(self):
return [
# 1. lookup metr... |
meyersj/geotweet | geotweet/mapreduce/poi_nearby_tweets.py | POINearbyTweetsMRJob.reducer_output | python | def reducer_output(self, metro, values):
records = []
# build up list of data for each metro area and submit as one network
# call instead of individually
for value in values:
total, poi = value
records.append(dict(
metro_area=metro,
... | store each record in MongoDB and output tab delimited lines | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/poi_nearby_tweets.py#L159-L175 | null | class POINearbyTweetsMRJob(MRJob):
""" Count common OSM points-of-interest around Tweets with coordinates """
INPUT_PROTOCOL = JSONValueProtocol
INTERNAL_PROTOCOL = JSONProtocol
OUTPUT_PROTOCOL = RawValueProtocol
SORT_VALUES = True
def steps(self):
return [
# 1. lookup metr... |
meyersj/geotweet | geotweet/mapreduce/utils/words.py | WordExtractor.run | python | def run(self, line):
words = []
for word in self.clean_unicode(line.lower()).split():
if word.startswith('http'):
continue
cleaned = self.clean_punctuation(word)
if len(cleaned) > 1 and cleaned not in self.stopwords:
words.append(cleane... | Extract words from tweet
1. Remove non-ascii characters
2. Split line into individual words
3. Clean up puncuation characters | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/words.py#L47-L63 | null | class WordExtractor(FileReader):
"""
Extract words from a tweet.
If a provided `src` keyword param references a local file or remote resource
containing list of stop words, the will be download and used to exclude
extracted words
"""
def __init__(self, src=STOPWORDS_LIST):
self.sub... |
meyersj/geotweet | geotweet/mapreduce/utils/reader.py | FileReader.read | python | def read(self, src):
geojson = None
if not self.is_valid_src(src):
error = "File < {0} > does not exists or does start with 'http'."
raise ValueError(error.format(src))
if not self.is_url(src):
return open(src, 'r').read().decode('latin-1').encode('utf-8')
... | Download GeoJSON file of US counties from url (S3 bucket) | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/utils/reader.py#L32-L51 | [
"def is_valid_src(self, src):\n return os.path.isfile(src) or self.is_url(src)\n"
] | class FileReader(object):
""" Read file from the local file system or remote url and cache """
def is_url(self, src):
return src.startswith('http')
def is_valid_src(self, src):
return os.path.isfile(src) or self.is_url(src)
def get_location(self, src):
digest = self.digest(src... |
meyersj/geotweet | geotweet/mapreduce/state_county_wordcount.py | StateCountyWordCountJob.mapper_init | python | def mapper_init(self):
self.counties = CachedCountyLookup(precision=GEOHASH_PRECISION)
self.extractor = WordExtractor() | Download counties geojson from S3 and build spatial index and cache | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/mapreduce/state_county_wordcount.py#L60-L63 | null | class StateCountyWordCountJob(MRJob):
"""
Count word occurences for US tweets by entire county, by State and County
A geojson file of US counties is downloaded from an S3 bucket. A RTree index
is built using the bounding box of each county, and is used for determining
State and County for each twee... |
meyersj/geotweet | geotweet/geomongo/__init__.py | GeoMongo.run | python | def run(self):
logging.info("Starting GeoJSON MongoDB loading process.")
mongo = dict(uri=self.mongo, db=self.db, collection=self.collection)
self.load(self.source, **mongo)
logging.info("Finished loading {0} into MongoDB".format(self.source)) | Top level runner to load State and County GeoJSON files into Mongo DB | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/geomongo/__init__.py#L19-L24 | [
"def load(self, geojson, uri=None, db=None, collection=None):\n \"\"\" Load geojson file into mongodb instance \"\"\"\n logging.info(\"Mongo URI: {0}\".format(uri))\n logging.info(\"Mongo DB: {0}\".format(db))\n logging.info(\"Mongo Collection: {0}\".format(collection))\n logging.info(\"Geojson File ... | class GeoMongo(object):
def __init__(self, args):
self.source = args.file
self.mongo = args.mongo
self.db = args.db
self.collection = args.collection
def load(self, geojson, uri=None, db=None, collection=None):
""" Load geojson file into mongodb instance """
lo... |
meyersj/geotweet | geotweet/geomongo/__init__.py | GeoMongo.load | python | def load(self, geojson, uri=None, db=None, collection=None):
logging.info("Mongo URI: {0}".format(uri))
logging.info("Mongo DB: {0}".format(db))
logging.info("Mongo Collection: {0}".format(collection))
logging.info("Geojson File to be loaded: {0}".format(geojson))
mongo = MongoGe... | Load geojson file into mongodb instance | train | https://github.com/meyersj/geotweet/blob/1a6b55f98adf34d1b91f172d9187d599616412d9/geotweet/geomongo/__init__.py#L26-L33 | null | class GeoMongo(object):
def __init__(self, args):
self.source = args.file
self.mongo = args.mongo
self.db = args.db
self.collection = args.collection
def run(self):
""" Top level runner to load State and County GeoJSON files into Mongo DB """
logging.info("Star... |
elkiwy/paynter | paynter/paynter.py | Paynter.drawLine | python | def drawLine(self, x1, y1, x2, y2, silent=False):
start = time.time()
#Downsample the coordinates
x1 = int(x1/config.DOWNSAMPLING)
x2 = int(x2/config.DOWNSAMPLING)
y1 = int(y1/config.DOWNSAMPLING)
y2 = int(y2/config.DOWNSAMPLING)
if not silent :
print('drawing line from: '+str((x1,y1))+' to: '+str((x2... | Draws a line on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: Starting X coordinate.
:param y1: Starting Y coordinate.
:param x2: End X coordinate.
:param y2: End Y coordinate.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L65-L123 | [
"def getActiveLayer(self):\n\t\"\"\"\n\tReturns the currently active :py:class:`Layer`.\n\n\t:rtype: A :py:class:`Layer` object.\n\t\"\"\"\n\treturn self.layers[self.activeLayer]\n"
] | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.drawPoint | python | def drawPoint(self, x, y, silent=True):
start = time.time()
#Downsample the coordinates
x = int(x/config.DOWNSAMPLING)
y = int(y/config.DOWNSAMPLING)
#Apply the dab with or without source caching
if self.brush.usesSourceCaching:
applyMirroredDab_jit(self.mirrorMode, self.image.getActiveLayer().data, in... | Draws a point on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: Point X coordinate.
:param y1: Point Y coordinate.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L127-L147 | null | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.drawPath | python | def drawPath(self, pointList):
self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1])
i = 1
while i<len(pointList)-1:
self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1])
i+=1 | Draws a series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`.
No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param pointList: A ... | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L153-L166 | [
"def drawLine(self, x1, y1, x2, y2, silent=False):\n\t\"\"\"\n\tDraws a line on the current :py:class:`Layer` with the current :py:class:`Brush`.\n\tCoordinates are relative to the original layer size WITHOUT downsampling applied.\n\n\t:param x1: Starting X coordinate.\n\t:param y1: Starting Y coordinate.\n\t:param... | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.drawClosedPath | python | def drawClosedPath(self, pointList):
self.drawLine(pointList[0][0], pointList[0][1], pointList[1][0], pointList[1][1])
i = 1
while i<len(pointList)-1:
self.drawLine(pointList[i][0], pointList[i][1], pointList[i+1][0], pointList[i+1][1])
i+=1
self.drawLine(pointList[-1][0], pointList[-1][1], pointList[0][0... | Draws a closed series of lines on the current :py:class:`Layer` with the current :py:class:`Brush`.
No interpolation is applied to these point and :py:meth:`drawLine` will be used to connect all the points lineraly.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param pointL... | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L169-L183 | [
"def drawLine(self, x1, y1, x2, y2, silent=False):\n\t\"\"\"\n\tDraws a line on the current :py:class:`Layer` with the current :py:class:`Brush`.\n\tCoordinates are relative to the original layer size WITHOUT downsampling applied.\n\n\t:param x1: Starting X coordinate.\n\t:param y1: Starting Y coordinate.\n\t:param... | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.drawRect | python | def drawRect(self, x1, y1, x2, y2, angle=0):
vertices = [[x1,y1],[x2,y1],[x2,y2],[x1,y2],]
rotatedVertices = rotateMatrix(vertices, (x1+x2)*0.5, (y1+y2)*0.5, angle)
self.drawClosedPath(rotatedVertices) | Draws a rectangle on the current :py:class:`Layer` with the current :py:class:`Brush`.
Coordinates are relative to the original layer size WITHOUT downsampling applied.
:param x1: The X of the top-left corner of the rectangle.
:param y1: The Y of the top-left corner of the rectangle.
:param x2: The X of the ... | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L186-L200 | [
"def rotateMatrix(pointList, cx, cy, angle):\t\n\trotatedPoints = []\n\t#For each point in the list\n\tfor point in pointList:\n\t\t#Grab the coords and get dir and len\n\t\toldX = point[0]\n\t\toldY = point[1]\n\t\tdirection = math.degrees(math.atan2(cy-oldY, cx-oldX))\n\t\tlength = math.sqrt((cx - oldX)**2 + (cy ... | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.fillLayerWithColor | python | def fillLayerWithColor(self, color):
layer = self.image.getActiveLayer().data
colorRGBA = color.get_0_255()
layer[:,:,0] = colorRGBA[0]
layer[:,:,1] = colorRGBA[1]
layer[:,:,2] = colorRGBA[2]
layer[:,:,3] = colorRGBA[3] | Fills the current :py:class:`Layer` with the current :py:class:`Color`.
:param color: The :py:class:`Color` to apply to the layer.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L203-L215 | [
"def getActiveLayer(self):\n\t\"\"\"\n\tReturns the currently active :py:class:`Layer`.\n\n\t:rtype: A :py:class:`Layer` object.\n\t\"\"\"\n\treturn self.layers[self.activeLayer]\n"
] | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.addBorder | python | def addBorder(self, width, color=None):
width = int(width/config.DOWNSAMPLING)
if color==None:
color = self.color
layer = self.image.getActiveLayer().data
colorRGBA = color.get_0_255()
print('adding border'+str(colorRGBA)+str(width)+str(layer.shape))
layer[0:width,:,0] = colorRGBA[0]
layer[0:width,:,1]... | Add a border to the current :py:class:`Layer`.
:param width: The width of the border.
:param color: The :py:class:`Color` of the border, current :py:class:`Color` is the default value.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L218-L250 | [
"def getActiveLayer(self):\n\t\"\"\"\n\tReturns the currently active :py:class:`Layer`.\n\n\t:rtype: A :py:class:`Layer` object.\n\t\"\"\"\n\treturn self.layers[self.activeLayer]\n"
] | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.setColor | python | def setColor(self, color):
self.color = color
if self.brush and self.brush.doesUseSourceCaching():
self.brush.cacheBrush(color) | Sets the current :py:class:`Color` to use.
:param color: The :py:class:`Color` to use.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L259-L268 | null | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.setColorAlpha | python | def setColorAlpha(self, fixed=None, proportional=None):
if fixed!=None:
self.color.set_alpha(fixed)
elif proportional!=None:
self.color.set_alpha(self.color.get_alpha()*proportional) | Change the alpha of the current :py:class:`Color`.
:param fixed: Set the absolute 0-1 value of the alpha.
:param proportional: Set the relative value of the alpha (Es: If the current alpha is 0.8, a proportional value of 0.5 will set the final value to 0.4).
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L271-L282 | null | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.swapColors | python | def swapColors(self):
rgba = self.color.get_0_255()
self.color = self.secondColor
self.secondColor = Color(rgba, '0-255') | Swaps the current :py:class:`Color` with the secondary :py:class:`Color`.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L303-L311 | null | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.setBrush | python | def setBrush(self, b, resize=0, proportional=None):
if proportional!=None:
resize = int(self.brush.brushSize*0.5)
b.resizeBrush(resize) #If resize=0 it reset to its default size
self.brush = b
if self.brush and self.brush.doesUseSourceCaching():
self.brush.cacheBrush(self.color) | Sets the size of the current :py:class:`Brush`.
:param brush: The :py:class:`Brush` object to use as a brush.
:param resize: An optional absolute value to resize the brush before using it.
:param proportional: An optional relative float 0-1 value to resize the brush before using it.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L314-L328 | [
"def doesUseSourceCaching(self):\n\treturn self.usesSourceCaching\n",
"def cacheBrush(self, color):\n\tself.coloredBrushSource = self.brushTip[:,:] * color.get_0_1()\n",
"def resizeBrush(self, newSize):\n\t#Check if I want to reset back to original\n\tif newSize==0:\n\t\tnewSize = self.originalSize\n\n\t#Don't ... | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.setMirrorMode | python | def setMirrorMode(self, mirror):
assert (mirror=='' or mirror=='h' or mirror=='v' or mirror=='hv'or mirror=='vh'), 'setMirrorMode: wrong mirror mode, got '+str(mirror)+' expected one of ["","h","v","hv"]'
#Round up all the coordinates and convert them to int
if mirror=='': mirror = 0
elif mirror=='h': m... | Sets the mirror mode to use in the next operation.
:param mirror: A string object with one of these values : '', 'h', 'v', 'hv'. "h" stands for horizontal mirroring, while "v" stands for vertical mirroring. "hv" sets both at the same time.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L331-L346 | null | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.renderImage | python | def renderImage(self, output='', show=True):
#Merge all the layers to apply blending modes
resultLayer = self.image.mergeAllLayers()
#Show and save the results
img = PIL.Image.fromarray(resultLayer.data, 'RGBA')
if show:
img.show()
if output!='':
img.save(output, 'PNG') | Renders the :py:class:`Image` and outputs the final PNG file.
:param output: A string with the output file path, can be empty if you don't want to save the final image.
:param show: A boolean telling the system to display the final image after the rendering is done.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L349-L367 | [
"def mergeAllLayers(self):\n\t\"\"\"\n\tMerge all the layers together.\n\n\t:rtype: The result :py:class:`Layer` object. \n\t\"\"\"\n\tstart = time.time()\n\twhile(len(self.layers)>1):\n\t\tself.mergeBottomLayers()\n\tprint('merge time:'+str(time.time()-start))\n\treturn self.layers[0]\n"
] | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/paynter.py | Paynter.setActiveLayerEffect | python | def setActiveLayerEffect(self, effect):
self.image.layers[self.image.activeLayer].effect = effect | Changes the effect of the current active :py:class:`Layer`.
:param output: A string with the one of the blend modes listed in :py:meth:`newLayer`.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/paynter.py#L380-L387 | null | class Paynter:
"""
This class is the main object of the library and the one that will draw everything you ask.
To create this class you can use the default constructor.
.. code-block:: python
from paynter import *
P = Paynter()
"""
brush = 0
layer = 0
color = Color(0, 0, 0, 1)
secondColor = Color(1,1,1,... |
elkiwy/paynter | paynter/layer.py | Layer.showLayer | python | def showLayer(self, title='', debugText=''):
img = PIL.Image.fromarray(self.data, 'RGBA')
if debugText!='':
draw = PIL.ImageDraw.Draw(img)
font = PIL.ImageFont.truetype("DejaVuSansMono.ttf", 24)
draw.text((0, 0),debugText,(255,255,255),font=font)
img.show(title=title) | Shows the single layer.
:param title: A string with the title of the window where to render the image.
:param debugText: A string with some text to render over the image.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/layer.py#L65-L78 | null | class Layer:
"""
The :py:class:`Layer` class contains a 3D array of N.uint8 and a string with the blend mode of the layer.
An Image starts with one layer inside, but you can create more of them as follows:
.. code-block:: python
from paynter import *
#Inside the paynter there is already an Image with a blan... |
elkiwy/paynter | paynter/color.py | getColors_Triad | python | def getColors_Triad(hue=None, sat = 1, val = 1, spread = 60):
palette = list()
if hue==None:
leadHue = randFloat(0, 1)
else:
leadHue = hue
palette.append(Color(0,0,0,1).set_HSV(leadHue, sat, val))
palette.append(Color(0,0,0,1).set_HSV((leadHue + 0.5 + spread/360) % 1, sat, val))
palette.append(Color(0,0,0,1).... | Create a palette with one main color and two opposite color evenly spread apart from the main one.
:param hue: A 0-1 float with the starting hue value.
:param sat: A 0-1 float with the palette saturation.
:param val: A 0-1 float with the palette value.
:param val: An int with the spread in degrees from the opposi... | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/color.py#L71-L89 | [
"def randFloat(a,b):\n\treturn random.uniform(a,b)\n",
"def set_HSV(self, h, s, v):\n\t\"\"\"\n\tOverwrite the current color with this set of HSV values.\n\tThis keeps the current alpha value.\n\n\t:param h: A 0-1 float with the Hue.\n\t:param s: A 0-1 float with the Saturation.\n\t:param v: A 0-1 float with the ... | """
The Color class is another fundamental class in the Paynter library.
This module will mange the creation, modification, and storing of colors and palettes.
The color class is mainly used internally by the :py:class:`Paynter` class, but the user will still have to create the palette and sets the active colors manua... |
elkiwy/paynter | paynter/image.py | Image.newLayer | python | def newLayer(self, effect=''):
self.layers.append(Layer(effect = effect))
self.activeLayer = len(self.layers)-1 | Creates a new :py:class:`Layer` and set that as the active.
:param effect: A string with the blend mode for that layer that will be used when during the rendering process. The accepted values are: :code:`'soft_light','lighten','screen','dodge','addition','darken','multiply','hard_light','difference','subtract','gr... | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/image.py#L54-L62 | null | class Image:
"""
The :py:class:`Image` class is structured as an array of :py:class:`Layer`.
An Image class is created when you create a :py:class:`Paynter`, so you can access this class as follows:
.. code-block:: python
from paynter import *
paynter = Paynter()
image = paynter.image
"""
layers = []
a... |
elkiwy/paynter | paynter/image.py | Image.duplicateActiveLayer | python | def duplicateActiveLayer(self):
activeLayer = self.layers[self.activeLayer]
newLayer = Layer(data=activeLayer.data, effect=activeLayer.effect)
self.layers.append(newLayer)
self.activeLayer = len(self.layers)-1 | Duplicates the current active :py:class:`Layer`.
:rtype: Nothing. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/image.py#L65-L74 | null | class Image:
"""
The :py:class:`Image` class is structured as an array of :py:class:`Layer`.
An Image class is created when you create a :py:class:`Paynter`, so you can access this class as follows:
.. code-block:: python
from paynter import *
paynter = Paynter()
image = paynter.image
"""
layers = []
a... |
elkiwy/paynter | paynter/image.py | Image.mergeAllLayers | python | def mergeAllLayers(self):
start = time.time()
while(len(self.layers)>1):
self.mergeBottomLayers()
print('merge time:'+str(time.time()-start))
return self.layers[0] | Merge all the layers together.
:rtype: The result :py:class:`Layer` object. | train | https://github.com/elkiwy/paynter/blob/f73cb5bb010a6b32ee41640a50396ed0bae8d496/paynter/image.py#L77-L87 | [
"def mergeBottomLayers(self):\n\t#Debug show the two layer being merged\n\tprint('merging layers with:'+str(self.layers[1].effect))\n\t#Normal paste on top\n\tif self.layers[1].effect=='':\n\t\tbaseImage = PIL.Image.fromarray(self.layers[0].data, 'RGBA')\n\t\toverImage = PIL.Image.fromarray(self.layers[1].data, 'RG... | class Image:
"""
The :py:class:`Image` class is structured as an array of :py:class:`Layer`.
An Image class is created when you create a :py:class:`Paynter`, so you can access this class as follows:
.. code-block:: python
from paynter import *
paynter = Paynter()
image = paynter.image
"""
layers = []
a... |
thiezn/iperf3-python | iperf3/iperf3.py | more_data | python | def more_data(pipe_out):
r, _, _ = select.select([pipe_out], [], [], 0)
return bool(r) | Check if there is more data left on the pipe
:param pipe_out: The os pipe_out
:rtype: bool | train | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L40-L47 | null | # -*- coding: utf-8 -*-
"""
Python wrapper for the iperf3 libiperf.so.0 library. The module consists of two
classes, :class:`Client` and :class:`Server`, that inherit from the base class
:class:`IPerf3`. They provide a nice (if i say so myself) and pythonic way to
interact with the iperf3 utility.
At the moment the mo... |
thiezn/iperf3-python | iperf3/iperf3.py | read_pipe | python | def read_pipe(pipe_out):
out = b''
while more_data(pipe_out):
out += os.read(pipe_out, 1024)
return out.decode('utf-8') | Read data on a pipe
Used to capture stdout data produced by libiperf
:param pipe_out: The os pipe_out
:rtype: unicode string | train | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L50-L62 | [
"def more_data(pipe_out):\n \"\"\"Check if there is more data left on the pipe\n\n :param pipe_out: The os pipe_out\n :rtype: bool\n \"\"\"\n r, _, _ = select.select([pipe_out], [], [], 0)\n return bool(r)\n"
] | # -*- coding: utf-8 -*-
"""
Python wrapper for the iperf3 libiperf.so.0 library. The module consists of two
classes, :class:`Client` and :class:`Server`, that inherit from the base class
:class:`IPerf3`. They provide a nice (if i say so myself) and pythonic way to
interact with the iperf3 utility.
At the moment the mo... |
thiezn/iperf3-python | iperf3/iperf3.py | IPerf3.role | python | def role(self):
try:
self._role = c_char(
self.lib.iperf_get_test_role(self._test)
).value.decode('utf-8')
except TypeError:
self._role = c_char(
chr(self.lib.iperf_get_test_role(self._test))
).value.decode('utf-8')
... | The iperf3 instance role
valid roles are 'c'=client and 's'=server
:rtype: 'c' or 's' | train | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L246-L261 | null | class IPerf3(object):
"""The base class used by both the iperf3 :class:`Server` and :class:`Client`
.. note:: You should not use this class directly
"""
def __init__(self,
role,
verbose=True,
lib_name=None):
"""Initialise the iperf shared libra... |
thiezn/iperf3-python | iperf3/iperf3.py | IPerf3.bind_address | python | def bind_address(self):
result = c_char_p(
self.lib.iperf_get_test_bind_address(self._test)
).value
if result:
self._bind_address = result.decode('utf-8')
else:
self._bind_address = '*'
return self._bind_address | The bind address the iperf3 instance will listen on
use * to listen on all available IPs
:rtype: string | train | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L275-L289 | null | class IPerf3(object):
"""The base class used by both the iperf3 :class:`Server` and :class:`Client`
.. note:: You should not use this class directly
"""
def __init__(self,
role,
verbose=True,
lib_name=None):
"""Initialise the iperf shared libra... |
thiezn/iperf3-python | iperf3/iperf3.py | IPerf3.port | python | def port(self):
self._port = self.lib.iperf_get_test_server_port(self._test)
return self._port | The port the iperf3 server is listening on | train | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L300-L303 | null | class IPerf3(object):
"""The base class used by both the iperf3 :class:`Server` and :class:`Client`
.. note:: You should not use this class directly
"""
def __init__(self,
role,
verbose=True,
lib_name=None):
"""Initialise the iperf shared libra... |
thiezn/iperf3-python | iperf3/iperf3.py | IPerf3.json_output | python | def json_output(self):
enabled = self.lib.iperf_get_test_json_output(self._test)
if enabled:
self._json_output = True
else:
self._json_output = False
return self._json_output | Toggles json output of libiperf
Turning this off will output the iperf3 instance results to
stdout/stderr
:rtype: bool | train | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L311-L326 | null | class IPerf3(object):
"""The base class used by both the iperf3 :class:`Server` and :class:`Client`
.. note:: You should not use this class directly
"""
def __init__(self,
role,
verbose=True,
lib_name=None):
"""Initialise the iperf shared libra... |
thiezn/iperf3-python | iperf3/iperf3.py | IPerf3.verbose | python | def verbose(self):
enabled = self.lib.iperf_get_verbose(self._test)
if enabled:
self._verbose = True
else:
self._verbose = False
return self._verbose | Toggles verbose output for the iperf3 instance
:rtype: bool | train | https://github.com/thiezn/iperf3-python/blob/094a6e043f44fb154988348603661b1473c23a50/iperf3/iperf3.py#L338-L350 | null | class IPerf3(object):
"""The base class used by both the iperf3 :class:`Server` and :class:`Client`
.. note:: You should not use this class directly
"""
def __init__(self,
role,
verbose=True,
lib_name=None):
"""Initialise the iperf shared libra... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.