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
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.getEndpointSubscriptions
python
def getEndpointSubscriptions(self,ep): ''' Get list of all subscriptions on a given endpoint ``ep`` :param str ep: name of endpoint :return: successful ``.status_code`` / ``.is_done``. Check the ``.error`` :rtype: asyncResult ''' result = asyncResult() result.endpoint = ep data = self._getURL("/sub...
Get list of all subscriptions on a given endpoint ``ep`` :param str ep: name of endpoint :return: successful ``.status_code`` / ``.is_done``. Check the ``.error`` :rtype: asyncResult
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L394-L414
[ "def _getURL(self, url,query={},versioned=True):\n\tif versioned:\n\t\treturn r.get(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n\telse:\n\t\treturn r.get(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n" ]
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.getResourceSubscription
python
def getResourceSubscription(self,ep,res): ''' Get list of all subscriptions for a resource ``res`` on an endpoint ``ep`` :param str ep: name of endpoint :param str res: name of resource :return: successful ``.status_code`` / ``.is_done``. Check the ``.error`` :rtype: asyncResult ''' result = asyncRes...
Get list of all subscriptions for a resource ``res`` on an endpoint ``ep`` :param str ep: name of endpoint :param str res: name of resource :return: successful ``.status_code`` / ``.is_done``. Check the ``.error`` :rtype: asyncResult
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L418-L440
[ "def _getURL(self, url,query={},versioned=True):\n\tif versioned:\n\t\treturn r.get(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n\telse:\n\t\treturn r.get(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n" ]
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.putPreSubscription
python
def putPreSubscription(self,JSONdata): ''' Set pre-subscription rules for all endpoints / resources on the domain. This can be useful for all current and future endpoints/resources. :param json JSONdata: data to use as pre-subscription data. Wildcards are permitted :return: successful ``.status_code`` / ``...
Set pre-subscription rules for all endpoints / resources on the domain. This can be useful for all current and future endpoints/resources. :param json JSONdata: data to use as pre-subscription data. Wildcards are permitted :return: successful ``.status_code`` / ``.is_done``. Check the ``.error`` :rtype: asyn...
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L442-L467
[ "def _putURL(self, url,payload=None,versioned=True):\n\tif self._isJSON(payload):\n\t\tself.log.debug(\"PUT payload is json\")\n\t\tif versioned:\n\t\t\treturn r.put(self.address+self.apiVersion+url,json=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\t\telse:\n\t\t\treturn r.put(self.address+url,jso...
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.getPreSubscription
python
def getPreSubscription(self): ''' Get the current pre-subscription data from connector :return: JSON that represents the pre-subscription data in the ``.result`` field :rtype: asyncResult ''' result = asyncResult() data = self._getURL("/subscriptions") if data.status_code == 200: #immediate success ...
Get the current pre-subscription data from connector :return: JSON that represents the pre-subscription data in the ``.result`` field :rtype: asyncResult
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L469-L487
[ "def _getURL(self, url,query={},versioned=True):\n\tif versioned:\n\t\treturn r.get(self.address+self.apiVersion+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n\telse:\n\t\treturn r.get(self.address+url,headers={\"Authorization\":\"Bearer \"+self.bearer},params=query)\n" ]
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.putCallback
python
def putCallback(self,url,headers=""): ''' Set the callback URL. To be used in place of LongPolling when deploying a webapp. **note**: make sure you set up a callback URL in your web app :param str url: complete url, including port, where the callback url is located :param str headers: Optional - Headers...
Set the callback URL. To be used in place of LongPolling when deploying a webapp. **note**: make sure you set up a callback URL in your web app :param str url: complete url, including port, where the callback url is located :param str headers: Optional - Headers to have Connector send back with all calls ...
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L489-L513
[ "def _putURL(self, url,payload=None,versioned=True):\n\tif self._isJSON(payload):\n\t\tself.log.debug(\"PUT payload is json\")\n\t\tif versioned:\n\t\t\treturn r.put(self.address+self.apiVersion+url,json=payload,headers={\"Authorization\":\"Bearer \"+self.bearer})\n\t\telse:\n\t\t\treturn r.put(self.address+url,jso...
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.setHandler
python
def setHandler(self,handler,cbfn): ''' Register a handler for a particular notification type. These are the types of notifications that are acceptable. | 'async-responses' | 'registrations-expired' | 'de-registrations' | 'reg-updates' | 'registrations' | 'notifications' :param str handler: name...
Register a handler for a particular notification type. These are the types of notifications that are acceptable. | 'async-responses' | 'registrations-expired' | 'de-registrations' | 'reg-updates' | 'registrations' | 'notifications' :param str handler: name of the notification type :param fnptr cb...
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L554-L583
null
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.startLongPolling
python
def startLongPolling(self, noWait=False): ''' Start LongPolling Connector for notifications. :param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond :return: Thread of constantly running LongPoll. To be used to kill the thred if necessary. :rtype: pythonThre...
Start LongPolling Connector for notifications. :param bool noWait: Optional - use the cached values in connector, do not wait for the device to respond :return: Thread of constantly running LongPoll. To be used to kill the thred if necessary. :rtype: pythonThread
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L587-L608
null
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.stopLongPolling
python
def stopLongPolling(self): ''' Stop LongPolling thread :return: none ''' if(self.longPollThread.isAlive()): self._stopLongPolling.set() self.log.debug("set stop longpolling flag") else: self.log.warn("LongPolling thread already stopped") return
Stop LongPolling thread :return: none
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L611-L622
null
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.handler
python
def handler(self,data): ''' Function to handle notification data as part of Callback URL handler. :param str data: data posted to Callback URL by connector. :return: nothing ''' if isinstance(data,r.models.Response): self.log.debug("data is request object = %s", str(data.content)) data = data.con...
Function to handle notification data as part of Callback URL handler. :param str data: data posted to Callback URL by connector. :return: nothing
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L648-L685
null
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
ARMmbed/mbed-connector-api-python
mbed_connector_api/mbed_connector_api.py
connector.debug
python
def debug(self,onOff,level='DEBUG'): ''' Enable / Disable debugging :param bool onOff: turn debugging on / off :return: none ''' if onOff: if level == 'DEBUG': self.log.setLevel(logging.DEBUG) self._ch.setLevel(logging.DEBUG) self.log.debug("Debugging level DEBUG enabled") elif level =...
Enable / Disable debugging :param bool onOff: turn debugging on / off :return: none
train
https://github.com/ARMmbed/mbed-connector-api-python/blob/a5024a01dc67cc192c8bf7a70b251fcf0a3f279b/mbed_connector_api/mbed_connector_api.py#L688-L715
null
class connector: """ Interface class to use the connector.mbed.com REST API. This class will by default handle asyncronous events. All function return :class:'.asyncResult' objects """ # Return connector version number and recent rest API version number it supports def getConnectorVersion(self): """ GET th...
makinacorpus/django-tracking-fields
tracking_fields/admin.py
TrackingEventAdmin.changelist_view
python
def changelist_view(self, request, extra_context=None): extra_context = extra_context or {} if 'object' in request.GET.keys(): value = request.GET['object'].split(':') content_type = get_object_or_404( ContentType, id=value[0], ) ...
Get object currently tracked and add a button to get back to it
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/admin.py#L118-L134
null
class TrackingEventAdmin(admin.ModelAdmin): date_hierarchy = 'date' list_display = ('date', 'action', 'object', 'object_repr') list_filter = ('action', TrackerEventUserFilter, TrackerEventListFilter,) search_fields = ('object_repr', 'user_repr',) readonly_fields = ( 'date', 'action', 'object...
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_track_class_related_field
python
def _track_class_related_field(cls, field): # field = field on current model # related_field = field on related model (field, related_field) = field.split('__', 1) field_obj = cls._meta.get_field(field) related_cls = field_obj.remote_field.model related_name = field_obj.remote_field.get_accessor...
Track a field on a related model
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L35-L71
null
from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.urls import reverse from django.db.models import ManyToManyField from django.db.models.signals import ( post_init, post_save, pre_delete, m2m_changed ) from tracking_fields.tracking import ( tracking...
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_track_class_field
python
def _track_class_field(cls, field): if '__' in field: _track_class_related_field(cls, field) return # Will raise FieldDoesNotExist if there is an error cls._meta.get_field(field) # Detect m2m fields changes if isinstance(cls._meta.get_field(field), ManyToManyField): m2m_chang...
Track a field on the current model
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L74-L87
[ "def _track_class_related_field(cls, field):\n \"\"\" Track a field on a related model \"\"\"\n # field = field on current model\n # related_field = field on related model\n (field, related_field) = field.split('__', 1)\n field_obj = cls._meta.get_field(field)\n related_cls = field_obj.remote_fiel...
from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.urls import reverse from django.db.models import ManyToManyField from django.db.models.signals import ( post_init, post_save, pre_delete, m2m_changed ) from tracking_fields.tracking import ( tracking...
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_track_class
python
def _track_class(cls, fields): # Small tests to ensure everything is all right assert not getattr(cls, '_is_tracked', False) for field in fields: _track_class_field(cls, field) _add_signals_to_cls(cls) # Mark the class as tracked cls._is_tracked = True # Do not directly track rela...
Track fields on the specified model
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L90-L107
[ "def _add_signals_to_cls(cls):\n # Use repr(cls) to be sure to bound the callback\n # only once for each class\n post_init.connect(\n tracking_init,\n sender=cls,\n dispatch_uid=repr(cls),\n )\n post_save.connect(\n tracking_save,\n sender=cls,\n dispatch_uid...
from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.urls import reverse from django.db.models import ManyToManyField from django.db.models.signals import ( post_init, post_save, pre_delete, m2m_changed ) from tracking_fields.tracking import ( tracking...
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
_add_get_tracking_url
python
def _add_get_tracking_url(cls): def get_tracking_url(self): """ return url to tracking view in admin panel """ url = reverse('admin:tracking_fields_trackingevent_changelist') object_id = '{0}%3A{1}'.format( ContentType.objects.get_for_model(self).pk, self.pk )...
Add a method to get the tracking url of an object.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L110-L121
null
from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.urls import reverse from django.db.models import ManyToManyField from django.db.models.signals import ( post_init, post_save, pre_delete, m2m_changed ) from tracking_fields.tracking import ( tracking...
makinacorpus/django-tracking-fields
tracking_fields/decorators.py
track
python
def track(*fields): def inner(cls): _track_class(cls, fields) _add_get_tracking_url(cls) return cls return inner
Decorator used to track changes on Model's fields. :Example: >>> @track('name') ... class Human(models.Model): ... name = models.CharField(max_length=30)
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/decorators.py#L124-L137
null
from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.urls import reverse from django.db.models import ManyToManyField from django.db.models.signals import ( post_init, post_save, pre_delete, m2m_changed ) from tracking_fields.tracking import ( tracking...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_set_original_fields
python
def _set_original_fields(instance): original_fields = {} def _set_original_field(instance, field): if instance.pk is None: original_fields[field] = None else: if isinstance(instance._meta.get_field(field), ForeignKey): # Only get the PK, we don't want to ...
Save fields value, only for non-m2m fields.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L29-L54
[ "def _set_original_field(instance, field):\n if instance.pk is None:\n original_fields[field] = None\n else:\n if isinstance(instance._meta.get_field(field), ForeignKey):\n # Only get the PK, we don't want to get the object\n # (which would make an additional request)\n ...
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_has_changed
python
def _has_changed(instance): for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): try: if field in getattr(instance, '_tracked_fields', []): if isinstance(inst...
Check if some tracked fields have changed
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L57-L75
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_has_changed_related
python
def _has_changed_related(instance): tracked_related_fields = getattr( instance, '_tracked_related_fields', {} ).keys() for field, value in instance._original_fields.items(): if field != 'pk' and \ not isinstance(instance._meta.get_field(field), ManyToManyField): ...
Check if some related tracked fields have changed
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L78-L97
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_event
python
def _create_event(instance, action): user = None user_repr = repr(user) if CUSER: user = CuserMiddleware.get_user() user_repr = repr(user) if user is not None and user.is_anonymous: user = None return TrackingEvent.objects.create( action=action, object...
Create a new event, getting the use if django-cuser is available.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L100-L117
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_tracked_field
python
def _create_tracked_field(event, instance, field, fieldname=None): fieldname = fieldname or field if isinstance(instance._meta.get_field(field), ForeignKey): # We only have the pk, we need to get the actual object model = instance._meta.get_field(field).remote_field.model pk = instance._...
Create a TrackedFieldModification for the instance. :param event: The TrackingEvent on which to add TrackingField :param instance: The instance on which the field is :param field: The field name to track :param fieldname: The displayed name for the field. Default to field.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L145-L170
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_create_tracking_event
python
def _create_create_tracking_event(instance): event = _create_event(instance, CREATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): _create_tracked_field(event, instance, field)
Create a TrackingEvent and TrackedFieldModification for a CREATE event.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L173-L180
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_update_tracking_event
python
def _create_update_tracking_event(instance): event = _create_event(instance, UPDATE) for field in instance._tracked_fields: if not isinstance(instance._meta.get_field(field), ManyToManyField): try: if isinstance(instance._meta.get_field(field), ForeignKey): ...
Create a TrackingEvent and TrackedFieldModification for an UPDATE event.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L183-L200
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_update_tracking_related_event
python
def _create_update_tracking_related_event(instance): events = {} # Create a dict mapping related model field to modified fields for field, related_fields in instance._tracked_related_fields.items(): if not isinstance(instance._meta.get_field(field), ManyToManyField): if isinstance(instan...
Create a TrackingEvent and TrackedFieldModification for an UPDATE event for each related model.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L203-L239
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_get_m2m_field
python
def _get_m2m_field(model, sender): for field in getattr(model, '_tracked_fields', []): if isinstance(model._meta.get_field(field), ManyToManyField): if getattr(model, field).through == sender: return field for field in getattr(model, '_tracked_related_fields', {}).keys(): ...
Get the field name from a model and a sender from m2m_changed signal.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L249-L260
null
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
_create_tracked_event_m2m
python
def _create_tracked_event_m2m(model, instance, sender, objects, action): field = _get_m2m_field(model, sender) if field in getattr(model, '_tracked_related_fields', {}).keys(): # In case of a m2m tracked on a related model related_fields = model._tracked_related_fields[field] for related...
Create the ``TrackedEvent`` and it's related ``TrackedFieldModification`` for a m2m modification. The first thing needed is to get the m2m field on the object being tracked. The current related objects are then taken (``old_value``). The new value is calculated in function of ``action`` (``new_value``)....
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L283-L320
[ "def _create_event(instance, action):\n \"\"\"\n Create a new event, getting the use if django-cuser is available.\n \"\"\"\n user = None\n user_repr = repr(user)\n if CUSER:\n user = CuserMiddleware.get_user()\n user_repr = repr(user)\n if user is not None and user.is_anonymo...
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
tracking_save
python
def tracking_save(sender, instance, raw, using, update_fields, **kwargs): if _has_changed(instance): if instance._original_fields['pk'] is None: # Create _create_create_tracking_event(instance) else: # Update _create_update_tracking_event(instance) ...
Post save, detect creation or changes and log them. We need post_save to have the object for a create.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L332-L349
[ "def _has_changed(instance):\n \"\"\"\n Check if some tracked fields have changed\n \"\"\"\n for field, value in instance._original_fields.items():\n if field != 'pk' and \\\n not isinstance(instance._meta.get_field(field), ManyToManyField):\n try:\n if field i...
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
makinacorpus/django-tracking-fields
tracking_fields/tracking.py
tracking_m2m
python
def tracking_m2m( sender, instance, action, reverse, model, pk_set, using, **kwargs ): action_event = { 'pre_clear': 'CLEAR', 'pre_add': 'ADD', 'pre_remove': 'REMOVE', } if (action not in action_event.keys()): return if reverse: if action == 'pre_clear': ...
m2m_changed callback. The idea is to get the model and the instance of the object being tracked, and the different objects being added/removed. It is then send to the ``_create_tracked_field_m2m`` method to extract the proper attribute for the TrackedFieldModification.
train
https://github.com/makinacorpus/django-tracking-fields/blob/463313d0f9c0f8107a0413f4d418d1a8c2311981/tracking_fields/tracking.py#L359-L400
[ "def _get_m2m_field(model, sender):\n \"\"\"\n Get the field name from a model and a sender from m2m_changed signal.\n \"\"\"\n for field in getattr(model, '_tracked_fields', []):\n if isinstance(model._meta.get_field(field), ManyToManyField):\n if getattr(model, field).through == send...
from __future__ import unicode_literals import datetime import json import logging from django.core.exceptions import ObjectDoesNotExist from django.db.models import Model, ManyToManyField from django.db.models.fields.files import FieldFile from django.db.models.fields.related import ForeignKey from django.utils impo...
Grk0/python-libconf
libconf.py
decode_escapes
python
def decode_escapes(s): '''Unescape libconfig string literals''' def decode_match(match): return codecs.decode(match.group(0), 'unicode-escape') return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
Unescape libconfig string literals
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L50-L55
null
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
load
python
def load(f, filename=None, includedir=''): '''Load the contents of ``f`` (a file-like object) to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> with open('test/example.cfg') as f: ... config = libconf.load...
Load the contents of ``f`` (a file-like object) to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> with open('test/example.cfg') as f: ... config = libconf.load(f) >>> config['window']['title'] ...
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L476-L498
[ "def from_file(cls, f, filename=None, includedir='', seenfiles=None):\n '''Create a token stream by reading an input file\n\n Read tokens from `f`. If an include directive ('@include \"file.cfg\"')\n is found, read its contents as well.\n\n The `filename` argument is used for error messages and to detec...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
loads
python
def loads(string, filename=None, includedir=''): '''Load the contents of ``string`` to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> config = libconf.loads('window: { title: "libconfig example"; };') >>> conf...
Load the contents of ``string`` to a Python object The returned object is a subclass of ``dict`` that exposes string keys as attributes as well. Example: >>> config = libconf.loads('window: { title: "libconfig example"; };') >>> config['window']['title'] 'libconfig example' ...
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L501-L521
[ "def load(f, filename=None, includedir=''):\n '''Load the contents of ``f`` (a file-like object) to a Python object\n\n The returned object is a subclass of ``dict`` that exposes string keys as\n attributes as well.\n\n Example:\n\n >>> with open('test/example.cfg') as f:\n ... config ...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
dump_string
python
def dump_string(s): '''Stringize ``s``, adding double quotes and escaping as necessary Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and ``\t``. Escape all remaining unprintable characters in ``\xFF``-style. The returned string will be surrounded by double quotes. ''' s ...
Stringize ``s``, adding double quotes and escaping as necessary Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and ``\t``. Escape all remaining unprintable characters in ``\xFF``-style. The returned string will be surrounded by double quotes.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L555-L572
null
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
get_dump_type
python
def get_dump_type(value): '''Get the libconfig datatype of a value Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array), ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool), ``'f'`` (float), or ``'s'`` (string). Produces the proper type for LibconfList, LibconfArray, LibconfInt64...
Get the libconfig datatype of a value Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array), ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool), ``'f'`` (float), or ``'s'`` (string). Produces the proper type for LibconfList, LibconfArray, LibconfInt64 instances.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L575-L606
[ "def isint(i):\n return isinstance(i, (int, long))\n", "def isint(i):\n return isinstance(i, int)\n", "def is_long_int(i):\n '''Return True if argument should be dumped as int64 type\n\n Either because the argument is an instance of LibconfInt64, or\n because it exceeds the 32bit integer value ra...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
get_array_value_dtype
python
def get_array_value_dtype(lst): '''Return array value type, raise ConfigSerializeError for invalid arrays Libconfig arrays must only contain scalar values and all elements must be of the same libconfig data type. Raises ConfigSerializeError if these invariants are not met. Returns the value type o...
Return array value type, raise ConfigSerializeError for invalid arrays Libconfig arrays must only contain scalar values and all elements must be of the same libconfig data type. Raises ConfigSerializeError if these invariants are not met. Returns the value type of the array. If an array contains both ...
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L609-L646
[ "def get_dump_type(value):\n '''Get the libconfig datatype of a value\n\n Return values: ``'d'`` (dict), ``'l'`` (list), ``'a'`` (array),\n ``'i'`` (integer), ``'i64'`` (long integer), ``'b'`` (bool),\n ``'f'`` (float), or ``'s'`` (string).\n\n Produces the proper type for LibconfList, LibconfArray, ...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
dump_value
python
def dump_value(key, value, f, indent=0): '''Save a value of any libconfig type This function serializes takes ``key`` and ``value`` and serializes them into ``f``. If ``key`` is ``None``, a list-style output is produced. Otherwise, output has ``key = value`` format. ''' spaces = ' ' * indent ...
Save a value of any libconfig type This function serializes takes ``key`` and ``value`` and serializes them into ``f``. If ``key`` is ``None``, a list-style output is produced. Otherwise, output has ``key = value`` format.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L649-L692
[ "def dump_int(i):\n '''Stringize ``i``, append 'L' suffix if necessary'''\n return str(i) + ('L' if is_long_int(i) else '')\n", "def dump_string(s):\n '''Stringize ``s``, adding double quotes and escaping as necessary\n\n Backslash escape backslashes, double quotes, ``\\f``, ``\\n``, ``\\r``, and\n ...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
dump_collection
python
def dump_collection(cfg, f, indent=0): '''Save a collection of attributes''' for i, value in enumerate(cfg): dump_value(None, value, f, indent) if i < len(cfg) - 1: f.write(u',\n')
Save a collection of attributes
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L695-L701
[ "def dump_value(key, value, f, indent=0):\n '''Save a value of any libconfig type\n\n This function serializes takes ``key`` and ``value`` and serializes them\n into ``f``. If ``key`` is ``None``, a list-style output is produced.\n Otherwise, output has ``key = value`` format.\n '''\n\n spaces = '...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
dump_dict
python
def dump_dict(cfg, f, indent=0): '''Save a dictionary of attributes''' for key in cfg: if not isstr(key): raise ConfigSerializeError("Dict keys must be strings: %r" % (key,)) dump_value(key, cfg[key], f, indent) f.write(u';\n')
Save a dictionary of attributes
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L704-L712
[ "def isstr(s):\n return isinstance(s, basestring)\n", "def isstr(s):\n return isinstance(s, str)\n", "def dump_value(key, value, f, indent=0):\n '''Save a value of any libconfig type\n\n This function serializes takes ``key`` and ``value`` and serializes them\n into ``f``. If ``key`` is ``None``,...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
dumps
python
def dumps(cfg): '''Serialize ``cfg`` into a libconfig-formatted ``str`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). Returns the formatted string. ''' str_file = io.StringIO() dump(cfg, st...
Serialize ``cfg`` into a libconfig-formatted ``str`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). Returns the formatted string.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L715-L726
[ "def dump(cfg, f):\n '''Serialize ``cfg`` as a libconfig-formatted stream into ``f``\n\n ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values\n (numbers, strings, booleans, possibly nested dicts, lists, and tuples).\n\n ``f`` must be a ``file``-like object with a ``write()`` method....
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
dump
python
def dump(cfg, f): '''Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method. ''' ...
Serialize ``cfg`` as a libconfig-formatted stream into ``f`` ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values (numbers, strings, booleans, possibly nested dicts, lists, and tuples). ``f`` must be a ``file``-like object with a ``write()`` method.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L729-L743
[ "def dump_dict(cfg, f, indent=0):\n '''Save a dictionary of attributes'''\n\n for key in cfg:\n if not isstr(key):\n raise ConfigSerializeError(\"Dict keys must be strings: %r\" %\n (key,))\n dump_value(key, cfg[key], f, indent)\n f.write(u...
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
main
python
def main(): '''Open the libconfig file specified by sys.argv[1] and pretty-print it''' global output if len(sys.argv[1:]) == 1: with io.open(sys.argv[1], 'r', encoding='utf-8') as f: output = load(f) else: output = load(sys.stdin) dump(output, sys.stdout)
Open the libconfig file specified by sys.argv[1] and pretty-print it
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L749-L758
[ "def dump(cfg, f):\n '''Serialize ``cfg`` as a libconfig-formatted stream into ``f``\n\n ``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values\n (numbers, strings, booleans, possibly nested dicts, lists, and tuples).\n\n ``f`` must be a ``file``-like object with a ``write()`` method....
#!/usr/bin/python from __future__ import absolute_import, division, print_function import sys import os import codecs import collections import io import re # Define an isstr() and isint() that work on both Python2 and Python3. # See http://stackoverflow.com/questions/11301138 try: basestring # attempt to evalu...
Grk0/python-libconf
libconf.py
Tokenizer.tokenize
python
def tokenize(self, string): '''Yield tokens from the input string or throw ConfigParseError''' pos = 0 while pos < len(string): m = SKIP_RE.match(string, pos=pos) if m: skip_lines = m.group(0).split('\n') if len(skip_lines) > 1: ...
Yield tokens from the input string or throw ConfigParseError
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L178-L206
null
class Tokenizer: '''Tokenize an input string Typical usage: tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();""")) The filename argument to the constructor is used only in error messages, no data is loaded from the file. The input data is received as argument to the tokenize ...
Grk0/python-libconf
libconf.py
TokenStream.from_file
python
def from_file(cls, f, filename=None, includedir='', seenfiles=None): '''Create a token stream by reading an input file Read tokens from `f`. If an include directive ('@include "file.cfg"') is found, read its contents as well. The `filename` argument is used for error messages and to de...
Create a token stream by reading an input file Read tokens from `f`. If an include directive ('@include "file.cfg"') is found, read its contents as well. The `filename` argument is used for error messages and to detect circular imports. ``includedir`` sets the lookup directory for incl...
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L224-L273
[ "def decode_escapes(s):\n '''Unescape libconfig string literals'''\n def decode_match(match):\n return codecs.decode(match.group(0), 'unicode-escape')\n\n return ESCAPE_SEQUENCE_RE.sub(decode_match, s)\n", "def tokenize(self, string):\n '''Yield tokens from the input string or throw ConfigParse...
class TokenStream: '''Offer a parsing-oriented view on tokens Provide several methods that are useful to parsers, like ``accept()``, ``expect()``, ... The ``from_file()`` method is the preferred way to read input files, as it handles include directives, which the ``Tokenizer`` class does not do. ...
Grk0/python-libconf
libconf.py
TokenStream.peek
python
def peek(self): '''Return (but do not consume) the next token At the end of input, ``None`` is returned. ''' if self.position >= len(self.tokens): return None return self.tokens[self.position]
Return (but do not consume) the next token At the end of input, ``None`` is returned.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L275-L284
null
class TokenStream: '''Offer a parsing-oriented view on tokens Provide several methods that are useful to parsers, like ``accept()``, ``expect()``, ... The ``from_file()`` method is the preferred way to read input files, as it handles include directives, which the ``Tokenizer`` class does not do. ...
Grk0/python-libconf
libconf.py
TokenStream.accept
python
def accept(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, return None. ''' ...
Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, return None.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L286-L304
[ "def peek(self):\n '''Return (but do not consume) the next token\n\n At the end of input, ``None`` is returned.\n '''\n\n if self.position >= len(self.tokens):\n return None\n\n return self.tokens[self.position]\n" ]
class TokenStream: '''Offer a parsing-oriented view on tokens Provide several methods that are useful to parsers, like ``accept()``, ``expect()``, ... The ``from_file()`` method is the preferred way to read input files, as it handles include directives, which the ``Tokenizer`` class does not do. ...
Grk0/python-libconf
libconf.py
TokenStream.expect
python
def expect(self, *args): '''Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError. ...
Consume and return the next token if it has the correct type Multiple token types (as strings, e.g. 'integer64') can be given as arguments. If the next token is one of them, consume and return it. If the token type doesn't match, raise a ConfigParseError.
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L306-L319
[ "def accept(self, *args):\n '''Consume and return the next token if it has the correct type\n\n Multiple token types (as strings, e.g. 'integer64') can be given\n as arguments. If the next token is one of them, consume and return it.\n\n If the token type doesn't match, return None.\n '''\n\n toke...
class TokenStream: '''Offer a parsing-oriented view on tokens Provide several methods that are useful to parsers, like ``accept()``, ``expect()``, ... The ``from_file()`` method is the preferred way to read input files, as it handles include directives, which the ``Tokenizer`` class does not do. ...
Grk0/python-libconf
libconf.py
TokenStream.error
python
def error(self, msg): '''Raise a ConfigParseError at the current input position''' if self.finished(): raise ConfigParseError("Unexpected end of input; %s" % (msg,)) else: t = self.peek() raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
Raise a ConfigParseError at the current input position
train
https://github.com/Grk0/python-libconf/blob/9c4cf5f56d56ebbc1fe0e1596807218b7d5d5da4/libconf.py#L321-L327
[ "def finished(self):\n '''Return ``True`` if the end of the token stream is reached.'''\n return self.position >= len(self.tokens)\n" ]
class TokenStream: '''Offer a parsing-oriented view on tokens Provide several methods that are useful to parsers, like ``accept()``, ``expect()``, ... The ``from_file()`` method is the preferred way to read input files, as it handles include directives, which the ``Tokenizer`` class does not do. ...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup._get_valididty
python
def _get_valididty(self): """ Determines whether this AD Group is valid. :returns: True and "" if this group is valid or False and a string description with the reason why it isn't valid otherwise. """ try: self.ldap_connection.search(search_base...
Determines whether this AD Group is valid. :returns: True and "" if this group is valid or False and a string description with the reason why it isn't valid otherwise.
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L270-L294
null
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.get_attribute
python
def get_attribute(self, attribute_name, no_cache=False): """ Gets the passed attribute of this group. :param attribute_name: The name of the attribute to get. :type attribute_name: str :param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instea...
Gets the passed attribute of this group. :param attribute_name: The name of the attribute to get. :type attribute_name: str :param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of from the cache. Default Fals...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L296-L322
[ "def get_attributes(self, no_cache=False):\n \"\"\"\n Returns a dictionary of this group's attributes. This method caches the attributes after\n the first search unless no_cache is specified.\n\n :param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of\n ...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.get_attributes
python
def get_attributes(self, no_cache=False): """ Returns a dictionary of this group's attributes. This method caches the attributes after the first search unless no_cache is specified. :param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of ...
Returns a dictionary of this group's attributes. This method caches the attributes after the first search unless no_cache is specified. :param no_cache (optional): Set to True to pull attributes directly from an LDAP search instead of from the cache. Default Fals...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L324-L353
null
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup._get_user_dn
python
def _get_user_dn(self, user_lookup_attribute_value): """ Searches for a user and retrieves his distinguished name. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if th...
Searches for a user and retrieves his distinguished name. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the account doesn't exist in the active directory.
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L355-L381
[ "def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n" ]
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup._get_group_dn
python
def _get_group_dn(self, group_lookup_attribute_value): """ Searches for a group and retrieves its distinguished name. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** i...
Searches for a group and retrieves its distinguished name. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the group doesn't exist in the active directory.
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L383-L409
[ "def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n" ]
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup._get_group_members
python
def _get_group_members(self, page_size=500): """ Searches for a group and retrieve its members. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be...
Searches for a group and retrieve its members. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the server's ...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L411-L431
[ "def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n" ]
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.get_member_info
python
def get_member_info(self, page_size=500): """ Retrieves member information from the AD group object. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size ...
Retrieves member information from the AD group object. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the s...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L433-L462
[ "def _get_group_members(self, page_size=500):\n \"\"\" Searches for a group and retrieve its members.\n\n :param page_size (optional): Many servers have a limit on the number of results that can be returned.\n Paged searches circumvent that limit. Adjust the page_size to be bel...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.get_tree_members
python
def get_tree_members(self): """ Retrieves all members from this node of the tree down.""" members = [] queue = deque() queue.appendleft(self) visited = set() while len(queue): node = queue.popleft() if node not in visited: ...
Retrieves all members from this node of the tree down.
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L464-L480
null
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.add_member
python
def add_member(self, user_lookup_attribute_value): """ Attempts to add a member to the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provided accoun...
Attempts to add a member to the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory. ...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L512-L528
[ "def _get_user_dn(self, user_lookup_attribute_value):\n \"\"\" Searches for a user and retrieves his distinguished name.\n\n :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE\n :type user_lookup_attribute_value: str\n\n :raises: **AccountDoesNotExist** if the accoun...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.remove_member
python
def remove_member(self, user_lookup_attribute_value): """ Attempts to remove a member from the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provide...
Attempts to remove a member from the AD group. :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE. :type user_lookup_attribute_value: str :raises: **AccountDoesNotExist** if the provided account doesn't exist in the active directory. ...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L530-L545
[ "def _get_user_dn(self, user_lookup_attribute_value):\n \"\"\" Searches for a user and retrieves his distinguished name.\n\n :param user_lookup_attribute_value: The value for the LDAP_GROUPS_USER_LOOKUP_ATTRIBUTE\n :type user_lookup_attribute_value: str\n\n :raises: **AccountDoesNotExist** if the accoun...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.add_child
python
def add_child(self, group_lookup_attribute_value): """ Attempts to add a child to the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provided group ...
Attempts to add a child to the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory. ...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L547-L563
[ "def _get_group_dn(self, group_lookup_attribute_value):\n \"\"\" Searches for a group and retrieves its distinguished name.\n\n :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE\n :type group_lookup_attribute_value: str\n\n :raises: **GroupDoesNotExist** if the gr...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.remove_child
python
def remove_child(self, group_lookup_attribute_value): """ Attempts to remove a child from the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provide...
Attempts to remove a child from the AD group. :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE. :type group_lookup_attribute_value: str :raises: **GroupDoesNotExist** if the provided group doesn't exist in the active directory. ...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L565-L581
[ "def _get_group_dn(self, group_lookup_attribute_value):\n \"\"\" Searches for a group and retrieves its distinguished name.\n\n :param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE\n :type group_lookup_attribute_value: str\n\n :raises: **GroupDoesNotExist** if the gr...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.get_descendants
python
def get_descendants(self, page_size=500): """ Returns a list of all descendants of this group. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be ...
Returns a list of all descendants of this group. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the server'...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L587-L612
null
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.get_children
python
def get_children(self, page_size=500): """ Returns a list of this group's children. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the ...
Returns a list of this group's children. :param page_size (optional): Many servers have a limit on the number of results that can be returned. Paged searches circumvent that limit. Adjust the page_size to be below the server's size l...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L614-L666
[ "def get_attribute(self, attribute_name, no_cache=False):\n \"\"\" Gets the passed attribute of this group.\n\n :param attribute_name: The name of the attribute to get.\n :type attribute_name: str\n :param no_cache (optional): Set to True to pull the attribute directly from an LDAP search instead of\n ...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.child
python
def child(self, group_name, page_size=500): """ Returns the child ad group that matches the provided group_name or none if the child does not exist. :param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU=' :type group_name: str :param page_size (...
Returns the child ad group that matches the provided group_name or none if the child does not exist. :param group_name: The name of the child group. NOTE: A name does not contain 'CN=' or 'OU=' :type group_name: str :param page_size (optional): Many servers have a limit on the number of res...
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L668-L714
[ "def escape_query(query):\n \"\"\"Escapes certain filter characters from an LDAP query.\"\"\"\n\n return query.replace(\"\\\\\", r\"\\5C\").replace(\"*\", r\"\\2A\").replace(\"(\", r\"\\28\").replace(\")\", r\"\\29\")\n", "def get_attribute(self, attribute_name, no_cache=False):\n \"\"\" Gets the passed ...
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.parent
python
def parent(self): """ Returns this group's parent (up to the DC)""" # Don't go above the DC if ''.join(self.group_dn.split("DC")[0].split()) == '': return self else: parent_dn = self.group_dn.split(",", 1).pop() return ADGroup( ...
Returns this group's parent (up to the DC)
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L716-L729
null
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/groups.py
ADGroup.ancestor
python
def ancestor(self, generation): """ Returns an ancestor of this group given a generation (up to the DC). :param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ... :type generation: int """ # Don't go below the current g...
Returns an ancestor of this group given a generation (up to the DC). :param generation: Determines how far up the path to go. Example: 0 = self, 1 = parent, 2 = grandparent ... :type generation: int
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/groups.py#L731-L756
null
class ADGroup: """ An Active Directory group. This methods in this class can add members to, remove members from, and view members of an Active Directory group, as well as traverse the Active Directory tree. """ def __init__(self, group_dn, server_uri=None, base_dn=None, user_lookup_attr=None...
kavdev/ldap-groups
ldap_groups/utils.py
escape_query
python
def escape_query(query): return query.replace("\\", r"\5C").replace("*", r"\2A").replace("(", r"\28").replace(")", r"\29")
Escapes certain filter characters from an LDAP query.
train
https://github.com/kavdev/ldap-groups/blob/0dd3a7d9eafa3903127364839b12a4b3dd3ca521/ldap_groups/utils.py#L23-L26
null
""" .. module:: ldap_groups.utils :synopsis: LDAP Groups Utilities. ldap-groups is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later ver...
inveniosoftware-contrib/json-merger
json_merger/utils.py
dedupe_list
python
def dedupe_list(l): result = [] for el in l: if el not in result: result.append(el) return result
Remove duplicates from a list preserving the order. We might be tempted to use the list(set(l)) idiom, but it doesn't preserve the order, which hinders testability and does not work for lists with unhashable elements.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/utils.py#L107-L120
null
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/config.py
DictMergerOps.keep_longest
python
def keep_longest(head, update, down_path): if update is None: return 'f' if head is None: return 's' return 'f' if len(head) >= len(update) else 's'
Keep longest field among `head` and `update`.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/config.py#L40-L48
null
class DictMergerOps(object): """Possible strategies for merging two base values. Attributes: FALLBACK_KEEP_HEAD: In case of conflict keep the `head` value. FALLBACK_KEEP_UPDATE: In case of conflict keep the `update` value. """ allowed_ops = [ 'FALLBACK_KEEP_HEAD', 'FALL...
inveniosoftware-contrib/json-merger
json_merger/graph_builder.py
toposort
python
def toposort(graph, pick_first='head'): in_deg = {} for node, next_nodes in six.iteritems(graph): for next_node in [next_nodes.head_node, next_nodes.update_node]: if next_node is None: continue in_deg[next_node] = in_deg.get(next_node, 0) + 1 stk = [FIRST] ...
Toplogically sorts a list match graph. Tries to perform a topological sort using as tiebreaker the pick_first argument. If the graph contains cycles, raise ValueError.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/graph_builder.py#L231-L266
[ "def _get_traversal(next_nodes, pick_first):\n if pick_first == 'head':\n return [next_nodes.update_node, next_nodes.head_node]\n else:\n return [next_nodes.head_node, next_nodes.update_node]\n" ]
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/graph_builder.py
sort_cyclic_graph_best_effort
python
def sort_cyclic_graph_best_effort(graph, pick_first='head'): ordered = [] visited = set() # Go first on the pick_first chain then go back again on the others # that were not visited. Given the way the graph is built both chains # will always contain all the elements. if pick_first == 'head': ...
Fallback for cases in which the graph has cycles.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/graph_builder.py#L269-L293
null
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/dict_merger.py
patch_to_conflict_set
python
def patch_to_conflict_set(patch): patch_type, patched_key, value = patch if isinstance(patched_key, list): key_path = tuple(patched_key) else: key_path = tuple(k for k in patched_key.split('.') if k) conflicts = set() if patch_type == REMOVE: conflict_type = ConflictType.REM...
Translates a dictdiffer conflict into a json_merger one.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/dict_merger.py#L54-L76
null
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/dict_merger.py
SkipListsMerger.merge
python
def merge(self): if isinstance(self.head, dict) and isinstance(self.update, dict): if not isinstance(self.root, dict): self.root = {} self._merge_dicts() else: self._merge_base_values() if self.conflict_set: raise MergeError('Dictd...
Perform merge of head and update starting from root.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/dict_merger.py#L236-L246
[ "def _merge_base_values(self):\n if self.head == self.update:\n self.merged_root = self.head\n elif self.head == NOTHING:\n self.merged_root = self.update\n elif self.update == NOTHING:\n self.merged_root = self.head\n elif self.head == self.root:\n self.merged_root = self.up...
class SkipListsMerger(object): """3-way Merger that ignores list fields.""" def __init__(self, root, head, update, default_op, data_lists=None, custom_ops={}, key_path=None): self.root = copy.deepcopy(root) self.head = copy.deepcopy(head) self.update = copy.deepcopy(upd...
inveniosoftware-contrib/json-merger
json_merger/contrib/inspirehep/match.py
distance_function_match
python
def distance_function_match(l1, l2, thresh, dist_fn, norm_funcs=[]): common = [] # We will keep track of the global index in the source list as we # will successively reduce their sizes. l1 = list(enumerate(l1)) l2 = list(enumerate(l2)) # Use the distance function and threshold on hints given b...
Returns pairs of matching indices from l1 and l2.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L30-L76
[ "def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh):\n \"\"\"Matches elements in l1 and l2 using normalization functions.\n\n Splits the elements in each list into buckets given by the normalization\n function. If the same normalization value points to a bucket from the\n first list and a bucket ...
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/contrib/inspirehep/match.py
_match_by_norm_func
python
def _match_by_norm_func(l1, l2, norm_fn, dist_fn, thresh): common = [] l1_only_idx = set(range(len(l1))) l2_only_idx = set(range(len(l2))) buckets_l1 = _group_by_fn(enumerate(l1), lambda x: norm_fn(x[1])) buckets_l2 = _group_by_fn(enumerate(l2), lambda x: norm_fn(x[1])) for normed, l1_element...
Matches elements in l1 and l2 using normalization functions. Splits the elements in each list into buckets given by the normalization function. If the same normalization value points to a bucket from the first list and a bucket from the second list, both with a single element we consider the elements i...
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L79-L138
[ "def _group_by_fn(iterable, fn):\n buckets = {}\n for elem in iterable:\n key = fn(elem)\n if key not in buckets:\n buckets[key] = []\n buckets[key].append(elem)\n return buckets\n" ]
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/contrib/inspirehep/match.py
_match_munkres
python
def _match_munkres(l1, l2, dist_matrix, thresh): equal_dist_matches = set() m = Munkres() indices = m.compute(dist_matrix) for l1_idx, l2_idx in indices: dst = dist_matrix[l1_idx][l2_idx] if dst > thresh: continue for eq_l2_idx, eq_val in enumerate(dist_matrix[l1_idx...
Matches two lists using the Munkres algorithm. Returns pairs of matching indices from the two lists by minimizing the sum of the distance between the linked elements and taking only the elements which have the distance between them less (or equal) than the threshold.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/match.py#L141-L163
null
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/conflict.py
Conflict.with_prefix
python
def with_prefix(self, root_path): return Conflict(self.conflict_type, root_path + self.path, self.body)
Returns a new conflict with a prepended prefix as a path.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/conflict.py#L95-L97
null
class Conflict(tuple): """Immutable and Hashable representation of a conflict. Attributes: conflict_type: A :class:`json_merger.conflict.ConflictType` member. path: A tuple containing the path to the conflictual field. body: Optional value representing the body of the conflict. N...
inveniosoftware-contrib/json-merger
json_merger/conflict.py
Conflict.to_json
python
def to_json(self): # map ConflictType to json-patch operator path = self.path if self.conflict_type in ('REORDER', 'SET_FIELD'): op = 'replace' elif self.conflict_type in ('MANUAL_MERGE', 'ADD_BACK_TO_HEAD'): op = 'add' path += ('-',) elif self...
Deserializes conflict to a JSON object. It returns list of: `json-patch <https://tools.ietf.org/html/rfc6902>`_ format. - REORDER, SET_FIELD become "op": "replace" - MANUAL_MERGE, ADD_BACK_TO_HEAD become "op": "add" - Path becomes `json-pointer <https://tools.ietf.org/html/...
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/conflict.py#L99-L139
[ "def force_list(data):\n if not isinstance(data, (list, tuple, set)):\n return [data]\n elif isinstance(data, (tuple, set)):\n return list(data)\n return data\n" ]
class Conflict(tuple): """Immutable and Hashable representation of a conflict. Attributes: conflict_type: A :class:`json_merger.conflict.ConflictType` member. path: A tuple containing the path to the conflictual field. body: Optional value representing the body of the conflict. N...
inveniosoftware-contrib/json-merger
json_merger/merger.py
Merger.merge
python
def merge(self): self.merged_root = self._recursive_merge(self.root, self.head, self.update) if self.conflicts: raise MergeError('Conflicts Occurred in Merge Process', self.conflicts)
Populates result members. Performs the merge algorithm using the specified config and fills in the members that provide stats about the merging procedure. Attributes: merged_root: The result of the merge. aligned_root, aligned_head, aligned_update: Copies of root, head...
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/merger.py#L135-L224
[ "def _recursive_merge(self, root, head, update, key_path=()):\n dotted_key_path = get_dotted_key_path(key_path, filter_int_keys=True)\n\n if (isinstance(head, list) and isinstance(update, list) and\n dotted_key_path not in self.data_lists):\n # In this case we are merging two lists of object...
class Merger(object): """Class that merges two JSON objects that share a common ancestor. This class treats by default all lists as being lists of entities and offers support for matching their elements by their content, by specifing per-field comparator classes. """ def __init__(self, root, h...
inveniosoftware-contrib/json-merger
json_merger/stats.py
ListMatchStats.move_to_result
python
def move_to_result(self, lst_idx): self.in_result_idx.add(lst_idx) if lst_idx in self.not_in_result_root_match_idx: self.not_in_result_root_match_idx.remove(lst_idx)
Moves element from lst available at lst_idx.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/stats.py#L72-L77
null
class ListMatchStats(object): """Class for holding list entity matching stats.""" def __init__(self, lst, root): """ Args: lst: The list of elements that needs to be matched. root: The ancestor of the list of elements that needs to be matched. ...
inveniosoftware-contrib/json-merger
json_merger/stats.py
ListMatchStats.add_root_match
python
def add_root_match(self, lst_idx, root_idx): self.root_matches[lst_idx] = root_idx if lst_idx in self.in_result_idx: return self.not_in_result_root_match_idx.add(lst_idx)
Adds a match for the elements avaialble at lst_idx and root_idx.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/stats.py#L79-L85
null
class ListMatchStats(object): """Class for holding list entity matching stats.""" def __init__(self, lst, root): """ Args: lst: The list of elements that needs to be matched. root: The ancestor of the list of elements that needs to be matched. ...
inveniosoftware-contrib/json-merger
json_merger/contrib/inspirehep/author_util.py
token_distance
python
def token_distance(t1, t2, initial_match_penalization): if isinstance(t1, NameInitial) or isinstance(t2, NameInitial): if t1.token == t2.token: return 0 if t1 == t2: return initial_match_penalization return 1.0 return _normalized_edit_dist(t1.token, t2.token)
Calculates the edit distance between two tokens.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/author_util.py#L60-L68
null
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/contrib/inspirehep/author_util.py
simple_tokenize
python
def simple_tokenize(name): last_names, first_names = name.split(',') last_names = _RE_NAME_TOKEN_SEPARATOR.split(last_names) first_names = _RE_NAME_TOKEN_SEPARATOR.split(first_names) first_names = [NameToken(n) if len(n) > 1 else NameInitial(n) for n in first_names if n] last_nam...
Simple tokenizer function to be used with the normalizers.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/contrib/inspirehep/author_util.py#L71-L82
null
# -*- coding: utf-8 -*- # # This file is part of Inspirehep. # Copyright (C) 2016 CERN. # # Inspirehep is free software; you can redistribute it # and/or modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of the # License, or (at your option) any...
inveniosoftware-contrib/json-merger
json_merger/comparator.py
BaseComparator.process_lists
python
def process_lists(self): for l1_idx, obj1 in enumerate(self.l1): for l2_idx, obj2 in enumerate(self.l2): if self.equal(obj1, obj2): self.matches.add((l1_idx, l2_idx))
Do any preprocessing of the lists.
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L45-L50
[ "def equal(self, obj1, obj2):\n \"\"\"Implementation of object equality.\"\"\"\n raise NotImplementedError()\n" ]
class BaseComparator(object): """Abstract base class for Entity Comparison.""" def __init__(self, l1, l2): """ Args: l1: First list of entities. l2: Second list of entities. """ self.l1 = l1 self.l2 = l2 self.matches = set() self.p...
inveniosoftware-contrib/json-merger
json_merger/comparator.py
BaseComparator.get_matches
python
def get_matches(self, src, src_idx): if src not in ('l1', 'l2'): raise ValueError('Must have one of "l1" or "l2" as src') if src == 'l1': target_list = self.l2 else: target_list = self.l1 comparator = { 'l1': lambda s_idx, t_idx: (s_idx, t_...
Get elements equal to the idx'th in src from the other list. e.g. get_matches(self, 'l1', 0) will return all elements from self.l2 matching with self.l1[0]
train
https://github.com/inveniosoftware-contrib/json-merger/blob/adc6d372da018427e1db7b92424d3471e01a4118/json_merger/comparator.py#L56-L74
null
class BaseComparator(object): """Abstract base class for Entity Comparison.""" def __init__(self, l1, l2): """ Args: l1: First list of entities. l2: Second list of entities. """ self.l1 = l1 self.l2 = l2 self.matches = set() self.p...
heronotears/lazyxml
lazyxml/parser.py
Parser.set_options
python
def set_options(self, **kw): r"""Set Parser options. .. seealso:: ``kw`` argument have the same meaning as in :func:`lazyxml.loads` """ for k, v in kw.iteritems(): if k in self.__options: self.__options[k] = v
r"""Set Parser options. .. seealso:: ``kw`` argument have the same meaning as in :func:`lazyxml.loads`
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L39-L47
null
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/parser.py
Parser.xml2object
python
def xml2object(self, content): r"""Convert xml content to python object. :param content: xml content :rtype: dict .. versionadded:: 1.2 """ content = self.xml_filter(content) element = ET.fromstring(content) tree = self.parse(element) if self.__options['...
r"""Convert xml content to python object. :param content: xml content :rtype: dict .. versionadded:: 1.2
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L64-L80
[ "def xml_filter(self, content):\n r\"\"\"Filter and preprocess xml content\n\n :param content: xml content\n :rtype: str\n \"\"\"\n content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip()\n\n if not self.__options['encoding']:\n encoding = self.guess_...
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/parser.py
Parser.xml_filter
python
def xml_filter(self, content): r"""Filter and preprocess xml content :param content: xml content :rtype: str """ content = utils.strip_whitespace(content, True) if self.__options['strip'] else content.strip() if not self.__options['encoding']: encoding = sel...
r"""Filter and preprocess xml content :param content: xml content :rtype: str
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L82-L100
[ "def strip_whitespace(s, strict=False):\n s = s.replace('\\r', '').replace('\\n', '').replace('\\t', '').replace('\\x0B', '')\n return s.strip() if strict else s\n", "def html_entity_decode(s):\n return HTML_ENTITY_PATTERN.sub(html_entity_decode_char, s)\n", "def set_options(self, **kw):\n r\"\"\"Se...
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/parser.py
Parser.guess_xml_encoding
python
def guess_xml_encoding(self, content): r"""Guess encoding from xml header declaration. :param content: xml content :rtype: str or None """ matchobj = self.__regex['xml_encoding'].match(content) return matchobj and matchobj.group(1).lower()
r"""Guess encoding from xml header declaration. :param content: xml content :rtype: str or None
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L102-L109
null
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/parser.py
Parser.parse
python
def parse(self, element): r"""Parse xml element. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict """ values = {} for child in element: node = self.get_node(child) subs = self.parse(child) value = subs o...
r"""Parse xml element. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L119-L136
[ "def parse(self, element):\n r\"\"\"Parse xml element.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n \"\"\"\n values = {}\n for child in element:\n node = self.get_node(child)\n subs = self.parse(child)\n value = subs or node['value']...
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/parser.py
Parser.parse_full
python
def parse_full(self, element): r"""Parse xml element include the node attributes. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict .. versionadded:: 1.2.1 """ values = collections.defaultdict(dict) for child in element: ...
r"""Parse xml element include the node attributes. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict .. versionadded:: 1.2.1
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L138-L158
[ "def parse_full(self, element):\n r\"\"\"Parse xml element include the node attributes.\n\n :param element: an :class:`~xml.etree.ElementTree.Element` instance\n :rtype: dict\n\n .. versionadded:: 1.2.1\n \"\"\"\n values = collections.defaultdict(dict)\n for child in element:\n node = se...
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/parser.py
Parser.get_node
python
def get_node(self, element): r"""Get node info. Parse element and get the element tag info. Include tag name, value, attribute, namespace. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict """ ns, tag = self.split_namespace(element.tag) ...
r"""Get node info. Parse element and get the element tag info. Include tag name, value, attribute, namespace. :param element: an :class:`~xml.etree.ElementTree.Element` instance :rtype: dict
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L160-L169
[ "def split_namespace(self, tag):\n r\"\"\"Split tag namespace.\n\n :param tag: tag name\n :return: a pair of (namespace, tag)\n :rtype: tuple\n \"\"\"\n matchobj = self.__regex['xml_ns'].search(tag)\n return matchobj.groups() if matchobj else ('', tag)\n" ]
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/parser.py
Parser.split_namespace
python
def split_namespace(self, tag): r"""Split tag namespace. :param tag: tag name :return: a pair of (namespace, tag) :rtype: tuple """ matchobj = self.__regex['xml_ns'].search(tag) return matchobj.groups() if matchobj else ('', tag)
r"""Split tag namespace. :param tag: tag name :return: a pair of (namespace, tag) :rtype: tuple
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/parser.py#L171-L179
null
class Parser(object): r"""XML Parser """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__regex = { 'xml_ns': re.compile(r'\{(.*?)\}(.*)'), # XML命名空间正则匹配对象 'xml_header': re.compile(r'<\?xml.*?\?>', re.I|re.S), # XML头部声明正则匹配对象 ...
heronotears/lazyxml
lazyxml/builder.py
Builder.object2xml
python
def object2xml(self, data): r"""Convert python object to xml string. :param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``. :rtype: str or unicode .. versionadded:: 1.2 """ if not self.__options['enco...
r"""Convert python object to xml string. :param data: data for build xml. If don't provide the ``root`` option, type of ``data`` must be dict and ``len(data) == 1``. :rtype: str or unicode .. versionadded:: 1.2
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L60-L85
[ "def set_options(self, **kw):\n r\"\"\"Set Builder options.\n\n .. seealso::\n ``kw`` argument have the same meaning as in :func:`lazyxml.dumps`\n \"\"\"\n for k, v in kw.iteritems():\n if k in self.__options:\n self.__options[k] = v\n", "def build_xml_header(self):\n r\"\"...
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
lazyxml/builder.py
Builder.build_tree
python
def build_tree(self, data, tagname, attrs=None, depth=0): r"""Build xml tree. :param data: data for build xml. :param tagname: element tag name. :param attrs: element attributes. Default:``None``. :type attrs: dict or None :param depth: element depth of the hierarchy. De...
r"""Build xml tree. :param data: data for build xml. :param tagname: element tag name. :param attrs: element attributes. Default:``None``. :type attrs: dict or None :param depth: element depth of the hierarchy. Default:``0``. :type depth: int
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L94-L128
null
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
lazyxml/builder.py
Builder.check_structure
python
def check_structure(self, keys): r"""Check structure availability by ``attrkey`` and ``valuekey`` option. """ return set(keys) <= set([self.__options['attrkey'], self.__options['valuekey']])
r"""Check structure availability by ``attrkey`` and ``valuekey`` option.
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L130-L133
null
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
lazyxml/builder.py
Builder.pickdata
python
def pickdata(self, data): r"""Pick data from ``attrkey`` and ``valuekey`` option. :return: a pair of (attrs, values) :rtype: tuple """ attrs = data.get(self.__options['attrkey']) or {} values = data.get(self.__options['valuekey']) or '' return (attrs, values)
r"""Pick data from ``attrkey`` and ``valuekey`` option. :return: a pair of (attrs, values) :rtype: tuple
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L135-L143
null
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
lazyxml/builder.py
Builder.safedata
python
def safedata(self, data, cdata=True): r"""Convert xml special chars to entities. :param data: the data will be converted safe. :param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data. :type cdata: bool :rtype: str """ ...
r"""Convert xml special chars to entities. :param data: the data will be converted safe. :param cdata: whether to use cdata. Default:``True``. If not, use :func:`cgi.escape` to convert data. :type cdata: bool :rtype: str
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L145-L154
null
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
lazyxml/builder.py
Builder.build_tag
python
def build_tag(self, tag, text='', attrs=None): r"""Build tag full info include the attributes. :param tag: tag name. :param text: tag text. :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str """ return '%s%s%s' % (self.t...
r"""Build tag full info include the attributes. :param tag: tag name. :param text: tag text. :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L156-L165
[ "def tag_start(self, tag, attrs=None):\n r\"\"\"Build started tag info.\n\n :param tag: tag name\n :param attrs: tag attributes. Default:``None``.\n :type attrs: dict or None\n :rtype: str\n \"\"\"\n return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag\n", "def tag_end(...
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
lazyxml/builder.py
Builder.build_attr
python
def build_attr(self, attrs): r"""Build tag attributes. :param attrs: tag attributes :type attrs: dict :rtype: str """ attrs = sorted(attrs.iteritems(), key=lambda x: x[0]) return ' '.join(map(lambda x: '%s="%s"' % x, attrs))
r"""Build tag attributes. :param attrs: tag attributes :type attrs: dict :rtype: str
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L167-L175
null
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
lazyxml/builder.py
Builder.tag_start
python
def tag_start(self, tag, attrs=None): r"""Build started tag info. :param tag: tag name :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str """ return '<%s %s>' % (tag, self.build_attr(attrs)) if attrs else '<%s>' % tag
r"""Build started tag info. :param tag: tag name :param attrs: tag attributes. Default:``None``. :type attrs: dict or None :rtype: str
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/builder.py#L177-L185
[ "def build_attr(self, attrs):\n r\"\"\"Build tag attributes.\n\n :param attrs: tag attributes\n :type attrs: dict\n :rtype: str\n \"\"\"\n attrs = sorted(attrs.iteritems(), key=lambda x: x[0])\n return ' '.join(map(lambda x: '%s=\"%s\"' % x, attrs))\n" ]
class Builder(object): r"""XML Builder """ def __init__(self, **kw): self.__encoding = 'utf-8' # 内部默认编码: utf-8 self.__options = { 'encoding': None, # XML编码 'header_declare': True, # 是否声明XML头部 'version': '1.0', ...
heronotears/lazyxml
demo/dump.py
main
python
def main(): data = {'demo':{'foo': '<foo>', 'bar': ['1', '2']}} # xml写入文件 提供文件名 lazyxml.dump(data, 'xml/dump.xml') # xml写入文件 提供文件句柄 with open('xml/dump-fp.xml', 'w') as fp: lazyxml.dump(data, fp) # xml写入文件 提供类文件对象 from cStringIO import StringIO buffer = StringIO() lazyxml....
<root a1="1" a2="2"> <test1 a="1" b="2" c="3"> <normal index="5" required="false"> <bar><![CDATA[1]]></bar> <bar><![CDATA[2]]></bar> <foo><![CDATA[<foo-1>]]></foo> </normal> <repeat1 index="1" required="false"> <...
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/demo/dump.py#L54-L142
[ "def dump(obj, fp, **kw):\n r\"\"\"Dump python object to file.\n\n >>> import lazyxml\n >>> data = {'demo': {'foo': 1, 'bar': 2}}\n >>> lazyxml.dump(data, 'dump.xml')\n >>> with open('dump-fp.xml', 'w') as fp:\n >>> lazyxml.dump(data, fp)\n\n >>> from cStringIO import StringIO\n >>> data...
#!/usr/bin/env python # -*- coding: utf-8 -*- import compat import lazyxml ATTRKEY = '{{attrs}}' VALUEKEY = '{{values}}' ATTRDATA = { 'root': { ATTRKEY: {'a1': 1, 'a2': 2}, VALUEKEY: { 'test1': { ATTRKEY: {'b': 2, 'a': 1, 'c': 3}, VALUEKEY: { ...
heronotears/lazyxml
lazyxml/__init__.py
dump
python
def dump(obj, fp, **kw): r"""Dump python object to file. >>> import lazyxml >>> data = {'demo': {'foo': 1, 'bar': 2}} >>> lazyxml.dump(data, 'dump.xml') >>> with open('dump-fp.xml', 'w') as fp: >>> lazyxml.dump(data, fp) >>> from cStringIO import StringIO >>> data = {'demo': {'foo'...
r"""Dump python object to file. >>> import lazyxml >>> data = {'demo': {'foo': 1, 'bar': 2}} >>> lazyxml.dump(data, 'dump.xml') >>> with open('dump-fp.xml', 'w') as fp: >>> lazyxml.dump(data, fp) >>> from cStringIO import StringIO >>> data = {'demo': {'foo': 1, 'bar': 2}} >>> buffe...
train
https://github.com/heronotears/lazyxml/blob/e3f1ebd3f34cfa03d022ddec90e17d60c1c81953/lazyxml/__init__.py#L149-L180
[ "def dumps(obj, **kw):\n r\"\"\"Dump python object to xml.\n\n >>> import lazyxml\n\n >>> data = {'demo':{'foo': '<foo>', 'bar': ['1', '2']}}\n\n >>> lazyxml.dumps(data)\n '<?xml version=\"1.0\" encoding=\"utf-8\"?><demo><foo><![CDATA[<foo>]]></foo><bar><![CDATA[1]]></bar><bar><![CDATA[2]]></bar></de...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @package lazyxml # @copyright Copyright (c) 2012, Zonglong Fan. # @license MIT r"""A simple xml parse and build lib. """ from __future__ import with_statement, absolute_import from . import builder from . import parser __author__ = 'Zonglong Fan <lazyboy.fan@gmail...