repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
Kentzo/Power
power/common.py
PowerManagementBase.add_observer
def add_observer(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class """ if not isinstance(observer, PowerManagementObserver): raise TypeError("observer MUST conform to power.PowerManagementObserver") self._weak_observers.append(weakref.ref(observer))
python
def add_observer(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class """ if not isinstance(observer, PowerManagementObserver): raise TypeError("observer MUST conform to power.PowerManagementObserver") self._weak_observers.append(weakref.ref(observer))
[ "def", "add_observer", "(", "self", ",", "observer", ")", ":", "if", "not", "isinstance", "(", "observer", ",", "PowerManagementObserver", ")", ":", "raise", "TypeError", "(", "\"observer MUST conform to power.PowerManagementObserver\"", ")", "self", ".", "_weak_observers", ".", "append", "(", "weakref", ".", "ref", "(", "observer", ")", ")" ]
Adds weak ref to an observer. @param observer: Instance of class registered with PowerManagementObserver @raise TypeError: If observer is not registered with PowerManagementObserver abstract class
[ "Adds", "weak", "ref", "to", "an", "observer", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/common.py#L115-L124
Kentzo/Power
power/common.py
PowerManagementBase.remove_all_observers
def remove_all_observers(self): """ Removes all registered observers. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: self.remove_observer(observer)
python
def remove_all_observers(self): """ Removes all registered observers. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: self.remove_observer(observer)
[ "def", "remove_all_observers", "(", "self", ")", ":", "for", "weak_observer", "in", "self", ".", "_weak_observers", ":", "observer", "=", "weak_observer", "(", ")", "if", "observer", ":", "self", ".", "remove_observer", "(", "observer", ")" ]
Removes all registered observers.
[ "Removes", "all", "registered", "observers", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/common.py#L135-L142
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.startThread
def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None) self._thread.start()
python
def startThread(self): """Spawns new NSThread to handle notifications.""" if self._thread is not None: return self._thread = NSThread.alloc().initWithTarget_selector_object_(self, 'runPowerNotificationsThread', None) self._thread.start()
[ "def", "startThread", "(", "self", ")", ":", "if", "self", ".", "_thread", "is", "not", "None", ":", "return", "self", ".", "_thread", "=", "NSThread", ".", "alloc", "(", ")", ".", "initWithTarget_selector_object_", "(", "self", ",", "'runPowerNotificationsThread'", ",", "None", ")", "self", ".", "_thread", ".", "start", "(", ")" ]
Spawns new NSThread to handle notifications.
[ "Spawns", "new", "NSThread", "to", "handle", "notifications", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L177-L182
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.stopThread
def stopThread(self): """Stops spawned NSThread.""" if self._thread is not None: self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES) self._thread = None
python
def stopThread(self): """Stops spawned NSThread.""" if self._thread is not None: self.performSelector_onThread_withObject_waitUntilDone_('stopPowerNotificationsThread', self._thread, None, objc.YES) self._thread = None
[ "def", "stopThread", "(", "self", ")", ":", "if", "self", ".", "_thread", "is", "not", "None", ":", "self", ".", "performSelector_onThread_withObject_waitUntilDone_", "(", "'stopPowerNotificationsThread'", ",", "self", ".", "_thread", ",", "None", ",", "objc", ".", "YES", ")", "self", ".", "_thread", "=", "None" ]
Stops spawned NSThread.
[ "Stops", "spawned", "NSThread", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L184-L188
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.runPowerNotificationsThread
def runPowerNotificationsThread(self): """Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" pool = NSAutoreleasePool.alloc().init() @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_source_notification(context): with self._lock: for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_source_notification, None) CFRunLoopAddSource(NSRunLoop.currentRunLoop().getCFRunLoop(), self._source, kCFRunLoopDefaultMode) while not NSThread.currentThread().isCancelled(): NSRunLoop.currentRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.distantFuture()) del pool
python
def runPowerNotificationsThread(self): """Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.""" pool = NSAutoreleasePool.alloc().init() @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_source_notification(context): with self._lock: for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_source_notification, None) CFRunLoopAddSource(NSRunLoop.currentRunLoop().getCFRunLoop(), self._source, kCFRunLoopDefaultMode) while not NSThread.currentThread().isCancelled(): NSRunLoop.currentRunLoop().runMode_beforeDate_(NSDefaultRunLoopMode, NSDate.distantFuture()) del pool
[ "def", "runPowerNotificationsThread", "(", "self", ")", ":", "pool", "=", "NSAutoreleasePool", ".", "alloc", "(", ")", ".", "init", "(", ")", "@", "objc", ".", "callbackFor", "(", "IOPSNotificationCreateRunLoopSource", ")", "def", "on_power_source_notification", "(", "context", ")", ":", "with", "self", ".", "_lock", ":", "for", "weak_observer", "in", "self", ".", "_weak_observers", ":", "observer", "=", "weak_observer", "(", ")", "if", "observer", ":", "observer", ".", "on_power_source_notification", "(", ")", "self", ".", "_source", "=", "IOPSNotificationCreateRunLoopSource", "(", "on_power_source_notification", ",", "None", ")", "CFRunLoopAddSource", "(", "NSRunLoop", ".", "currentRunLoop", "(", ")", ".", "getCFRunLoop", "(", ")", ",", "self", ".", "_source", ",", "kCFRunLoopDefaultMode", ")", "while", "not", "NSThread", ".", "currentThread", "(", ")", ".", "isCancelled", "(", ")", ":", "NSRunLoop", ".", "currentRunLoop", "(", ")", ".", "runMode_beforeDate_", "(", "NSDefaultRunLoopMode", ",", "NSDate", ".", "distantFuture", "(", ")", ")", "del", "pool" ]
Main method of the spawned NSThread. Registers run loop source and runs current NSRunLoop.
[ "Main", "method", "of", "the", "spawned", "NSThread", ".", "Registers", "run", "loop", "source", "and", "runs", "current", "NSRunLoop", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L190-L206
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.stopPowerNotificationsThread
def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThread.currentThread().cancel()
python
def stopPowerNotificationsThread(self): """Removes the only source from NSRunLoop and cancels thread.""" assert NSThread.currentThread() == self._thread CFRunLoopSourceInvalidate(self._source) self._source = None NSThread.currentThread().cancel()
[ "def", "stopPowerNotificationsThread", "(", "self", ")", ":", "assert", "NSThread", ".", "currentThread", "(", ")", "==", "self", ".", "_thread", "CFRunLoopSourceInvalidate", "(", "self", ".", "_source", ")", "self", ".", "_source", "=", "None", "NSThread", ".", "currentThread", "(", ")", ".", "cancel", "(", ")" ]
Removes the only source from NSRunLoop and cancels thread.
[ "Removes", "the", "only", "source", "from", "NSRunLoop", "and", "cancels", "thread", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L209-L215
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.addObserver
def addObserver(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() """ with self._lock: self._weak_observers.append(weakref.ref(observer)) if len(self._weak_observers) == 1: self.startThread()
python
def addObserver(self, observer): """ Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification() """ with self._lock: self._weak_observers.append(weakref.ref(observer)) if len(self._weak_observers) == 1: self.startThread()
[ "def", "addObserver", "(", "self", ",", "observer", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_weak_observers", ".", "append", "(", "weakref", ".", "ref", "(", "observer", ")", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "1", ":", "self", ".", "startThread", "(", ")" ]
Adds weak ref to an observer. @param observer: Instance of class that implements on_power_source_notification()
[ "Adds", "weak", "ref", "to", "an", "observer", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L217-L226
Kentzo/Power
power/darwin.py
PowerSourcesNotificationsObserver.removeObserver
def removeObserver(self, observer): """ Removes an observer. @param observer: Previously added observer """ with self._lock: self._weak_observers.remove(weakref.ref(observer)) if len(self._weak_observers) == 0: self.stopThread()
python
def removeObserver(self, observer): """ Removes an observer. @param observer: Previously added observer """ with self._lock: self._weak_observers.remove(weakref.ref(observer)) if len(self._weak_observers) == 0: self.stopThread()
[ "def", "removeObserver", "(", "self", ",", "observer", ")", ":", "with", "self", ".", "_lock", ":", "self", ".", "_weak_observers", ".", "remove", "(", "weakref", ".", "ref", "(", "observer", ")", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "0", ":", "self", ".", "stopThread", "(", ")" ]
Removes an observer. @param observer: Previously added observer
[ "Removes", "an", "observer", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L228-L237
Kentzo/Power
power/darwin.py
PowerManagement.on_power_source_notification
def on_power_source_notification(self): """ Called in response to IOPSNotificationCreateRunLoopSource() event. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_sources_change(self) observer.on_time_remaining_change(self)
python
def on_power_source_notification(self): """ Called in response to IOPSNotificationCreateRunLoopSource() event. """ for weak_observer in self._weak_observers: observer = weak_observer() if observer: observer.on_power_sources_change(self) observer.on_time_remaining_change(self)
[ "def", "on_power_source_notification", "(", "self", ")", ":", "for", "weak_observer", "in", "self", ".", "_weak_observers", ":", "observer", "=", "weak_observer", "(", ")", "if", "observer", ":", "observer", ".", "on_power_sources_change", "(", "self", ")", "observer", ".", "on_time_remaining_change", "(", "self", ")" ]
Called in response to IOPSNotificationCreateRunLoopSource() event.
[ "Called", "in", "response", "to", "IOPSNotificationCreateRunLoopSource", "()", "event", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L250-L258
Kentzo/Power
power/darwin.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate. """ if IOPSGetTimeRemainingEstimate is not None: # Mac OS X 10.7+ estimate = float(IOPSGetTimeRemainingEstimate()) if estimate == -1.0: return common.TIME_REMAINING_UNKNOWN elif estimate == -2.0: return common.TIME_REMAINING_UNLIMITED else: return estimate / 60.0 else: # Mac OS X 10.6 warnings.warn("IOPSGetTimeRemainingEstimate is not preset", RuntimeWarning) blob = IOPSCopyPowerSourcesInfo() type = IOPSGetProvidingPowerSourceType(blob) if type == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED else: estimate = 0.0 for source in IOPSCopyPowerSourcesList(blob): description = IOPSGetPowerSourceDescription(blob, source) if kIOPSIsPresentKey in description and description[kIOPSIsPresentKey] and kIOPSTimeToEmptyKey in description and description[kIOPSTimeToEmptyKey] > 0.0: estimate += float(description[kIOPSTimeToEmptyKey]) if estimate > 0.0: return float(estimate) else: return common.TIME_REMAINING_UNKNOWN
python
def get_time_remaining_estimate(self): """ In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate. """ if IOPSGetTimeRemainingEstimate is not None: # Mac OS X 10.7+ estimate = float(IOPSGetTimeRemainingEstimate()) if estimate == -1.0: return common.TIME_REMAINING_UNKNOWN elif estimate == -2.0: return common.TIME_REMAINING_UNLIMITED else: return estimate / 60.0 else: # Mac OS X 10.6 warnings.warn("IOPSGetTimeRemainingEstimate is not preset", RuntimeWarning) blob = IOPSCopyPowerSourcesInfo() type = IOPSGetProvidingPowerSourceType(blob) if type == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED else: estimate = 0.0 for source in IOPSCopyPowerSourcesList(blob): description = IOPSGetPowerSourceDescription(blob, source) if kIOPSIsPresentKey in description and description[kIOPSIsPresentKey] and kIOPSTimeToEmptyKey in description and description[kIOPSTimeToEmptyKey] > 0.0: estimate += float(description[kIOPSTimeToEmptyKey]) if estimate > 0.0: return float(estimate) else: return common.TIME_REMAINING_UNKNOWN
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "if", "IOPSGetTimeRemainingEstimate", "is", "not", "None", ":", "# Mac OS X 10.7+", "estimate", "=", "float", "(", "IOPSGetTimeRemainingEstimate", "(", ")", ")", "if", "estimate", "==", "-", "1.0", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "elif", "estimate", "==", "-", "2.0", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "else", ":", "return", "estimate", "/", "60.0", "else", ":", "# Mac OS X 10.6", "warnings", ".", "warn", "(", "\"IOPSGetTimeRemainingEstimate is not preset\"", ",", "RuntimeWarning", ")", "blob", "=", "IOPSCopyPowerSourcesInfo", "(", ")", "type", "=", "IOPSGetProvidingPowerSourceType", "(", "blob", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "else", ":", "estimate", "=", "0.0", "for", "source", "in", "IOPSCopyPowerSourcesList", "(", "blob", ")", ":", "description", "=", "IOPSGetPowerSourceDescription", "(", "blob", ",", "source", ")", "if", "kIOPSIsPresentKey", "in", "description", "and", "description", "[", "kIOPSIsPresentKey", "]", "and", "kIOPSTimeToEmptyKey", "in", "description", "and", "description", "[", "kIOPSTimeToEmptyKey", "]", ">", "0.0", ":", "estimate", "+=", "float", "(", "description", "[", "kIOPSTimeToEmptyKey", "]", ")", "if", "estimate", ">", "0.0", ":", "return", "float", "(", "estimate", ")", "else", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN" ]
In Mac OS X 10.7+ Uses IOPSGetTimeRemainingEstimate to get time remaining estimate. In Mac OS X 10.6 IOPSGetTimeRemainingEstimate is not available. If providing power source type is AC, returns TIME_REMAINING_UNLIMITED. Otherwise looks through all power sources returned by IOPSGetProvidingPowerSourceType and returns total estimate.
[ "In", "Mac", "OS", "X", "10", ".", "7", "+", "Uses", "IOPSGetTimeRemainingEstimate", "to", "get", "time", "remaining", "estimate", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L276-L310
Kentzo/Power
power/darwin.py
PowerManagement.add_observer
def add_observer(self, observer): """ Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ super(PowerManagement, self).add_observer(observer) if len(self._weak_observers) == 1: if not self._cf_run_loop: PowerManagement.notifications_observer.addObserver(self) else: @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_sources_change(context): self.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_sources_change, None) CFRunLoopAddSource(self._cf_run_loop, self._source, kCFRunLoopDefaultMode)
python
def add_observer(self, observer): """ Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__ """ super(PowerManagement, self).add_observer(observer) if len(self._weak_observers) == 1: if not self._cf_run_loop: PowerManagement.notifications_observer.addObserver(self) else: @objc.callbackFor(IOPSNotificationCreateRunLoopSource) def on_power_sources_change(context): self.on_power_source_notification() self._source = IOPSNotificationCreateRunLoopSource(on_power_sources_change, None) CFRunLoopAddSource(self._cf_run_loop, self._source, kCFRunLoopDefaultMode)
[ "def", "add_observer", "(", "self", ",", "observer", ")", ":", "super", "(", "PowerManagement", ",", "self", ")", ".", "add_observer", "(", "observer", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "1", ":", "if", "not", "self", ".", "_cf_run_loop", ":", "PowerManagement", ".", "notifications_observer", ".", "addObserver", "(", "self", ")", "else", ":", "@", "objc", ".", "callbackFor", "(", "IOPSNotificationCreateRunLoopSource", ")", "def", "on_power_sources_change", "(", "context", ")", ":", "self", ".", "on_power_source_notification", "(", ")", "self", ".", "_source", "=", "IOPSNotificationCreateRunLoopSource", "(", "on_power_sources_change", ",", "None", ")", "CFRunLoopAddSource", "(", "self", ".", "_cf_run_loop", ",", "self", ".", "_source", ",", "kCFRunLoopDefaultMode", ")" ]
Spawns thread or adds IOPSNotificationCreateRunLoopSource directly to provided cf_run_loop @see: __init__
[ "Spawns", "thread", "or", "adds", "IOPSNotificationCreateRunLoopSource", "directly", "to", "provided", "cf_run_loop" ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L312-L327
Kentzo/Power
power/darwin.py
PowerManagement.remove_observer
def remove_observer(self, observer): """ Stops thread and invalidates source. """ super(PowerManagement, self).remove_observer(observer) if len(self._weak_observers) == 0: if not self._cf_run_loop: PowerManagement.notifications_observer.removeObserver(self) else: CFRunLoopSourceInvalidate(self._source) self._source = None
python
def remove_observer(self, observer): """ Stops thread and invalidates source. """ super(PowerManagement, self).remove_observer(observer) if len(self._weak_observers) == 0: if not self._cf_run_loop: PowerManagement.notifications_observer.removeObserver(self) else: CFRunLoopSourceInvalidate(self._source) self._source = None
[ "def", "remove_observer", "(", "self", ",", "observer", ")", ":", "super", "(", "PowerManagement", ",", "self", ")", ".", "remove_observer", "(", "observer", ")", "if", "len", "(", "self", ".", "_weak_observers", ")", "==", "0", ":", "if", "not", "self", ".", "_cf_run_loop", ":", "PowerManagement", ".", "notifications_observer", ".", "removeObserver", "(", "self", ")", "else", ":", "CFRunLoopSourceInvalidate", "(", "self", ".", "_source", ")", "self", ".", "_source", "=", "None" ]
Stops thread and invalidates source.
[ "Stops", "thread", "and", "invalidates", "source", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/darwin.py#L329-L339
Kentzo/Power
power/win32.py
PowerManagement.get_providing_power_source_type
def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() return POWER_TYPE_MAP[power_status.ACLineStatus]
python
def get_providing_power_source_type(self): """ Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() return POWER_TYPE_MAP[power_status.ACLineStatus]
[ "def", "get_providing_power_source_type", "(", "self", ")", ":", "power_status", "=", "SYSTEM_POWER_STATUS", "(", ")", "if", "not", "GetSystemPowerStatus", "(", "pointer", "(", "power_status", ")", ")", ":", "raise", "WinError", "(", ")", "return", "POWER_TYPE_MAP", "[", "power_status", ".", "ACLineStatus", "]" ]
Returns GetSystemPowerStatus().ACLineStatus @raise: WindowsError if any underlying error occures.
[ "Returns", "GetSystemPowerStatus", "()", ".", "ACLineStatus" ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/win32.py#L45-L54
Kentzo/Power
power/win32.py
PowerManagement.get_low_battery_warning_level
def get_low_battery_warning_level(self): """ Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.LOW_BATTERY_WARNING_NONE else: if power_status.BatteryLifeTime != -1 and power_status.BatteryLifeTime <= 600: return common.LOW_BATTERY_WARNING_FINAL elif power_status.BatteryLifePercent <= 22: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE
python
def get_low_battery_warning_level(self): """ Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures. """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.LOW_BATTERY_WARNING_NONE else: if power_status.BatteryLifeTime != -1 and power_status.BatteryLifeTime <= 600: return common.LOW_BATTERY_WARNING_FINAL elif power_status.BatteryLifePercent <= 22: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE
[ "def", "get_low_battery_warning_level", "(", "self", ")", ":", "power_status", "=", "SYSTEM_POWER_STATUS", "(", ")", "if", "not", "GetSystemPowerStatus", "(", "pointer", "(", "power_status", ")", ")", ":", "raise", "WinError", "(", ")", "if", "POWER_TYPE_MAP", "[", "power_status", ".", "ACLineStatus", "]", "==", "common", ".", "POWER_TYPE_AC", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE", "else", ":", "if", "power_status", ".", "BatteryLifeTime", "!=", "-", "1", "and", "power_status", ".", "BatteryLifeTime", "<=", "600", ":", "return", "common", ".", "LOW_BATTERY_WARNING_FINAL", "elif", "power_status", ".", "BatteryLifePercent", "<=", "22", ":", "return", "common", ".", "LOW_BATTERY_WARNING_EARLY", "else", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE" ]
Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures.
[ "Returns", "warning", "according", "to", "GetSystemPowerStatus", "()", ".", "BatteryLifeTime", "/", "BatteryLifePercent" ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/win32.py#L56-L74
Kentzo/Power
power/win32.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED elif power_status.BatteryLifeTime == -1: return common.TIME_REMAINING_UNKNOWN else: return float(power_status.BatteryLifeTime) / 60.0
python
def get_time_remaining_estimate(self): """ Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime """ power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.TIME_REMAINING_UNLIMITED elif power_status.BatteryLifeTime == -1: return common.TIME_REMAINING_UNKNOWN else: return float(power_status.BatteryLifeTime) / 60.0
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "power_status", "=", "SYSTEM_POWER_STATUS", "(", ")", "if", "not", "GetSystemPowerStatus", "(", "pointer", "(", "power_status", ")", ")", ":", "raise", "WinError", "(", ")", "if", "POWER_TYPE_MAP", "[", "power_status", ".", "ACLineStatus", "]", "==", "common", ".", "POWER_TYPE_AC", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "elif", "power_status", ".", "BatteryLifeTime", "==", "-", "1", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "else", ":", "return", "float", "(", "power_status", ".", "BatteryLifeTime", ")", "/", "60.0" ]
Returns time remaining estimate according to GetSystemPowerStatus().BatteryLifeTime
[ "Returns", "time", "remaining", "estimate", "according", "to", "GetSystemPowerStatus", "()", ".", "BatteryLifeTime" ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/win32.py#L76-L89
Kentzo/Power
power/freebsd.py
PowerManagement.power_source_type
def power_source_type(): """ FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported """ try: supply=int(subprocess.check_output(["sysctl","-n","hw.acpi.acline"])) except: return common.POWER_TYPE_AC if supply == 1: return common.POWER_TYPE_AC elif supply == 0: return common.POWER_TYPE_BATTERY else: raise RuntimeError("Unknown power source type!")
python
def power_source_type(): """ FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported """ try: supply=int(subprocess.check_output(["sysctl","-n","hw.acpi.acline"])) except: return common.POWER_TYPE_AC if supply == 1: return common.POWER_TYPE_AC elif supply == 0: return common.POWER_TYPE_BATTERY else: raise RuntimeError("Unknown power source type!")
[ "def", "power_source_type", "(", ")", ":", "try", ":", "supply", "=", "int", "(", "subprocess", ".", "check_output", "(", "[", "\"sysctl\"", ",", "\"-n\"", ",", "\"hw.acpi.acline\"", "]", ")", ")", "except", ":", "return", "common", ".", "POWER_TYPE_AC", "if", "supply", "==", "1", ":", "return", "common", ".", "POWER_TYPE_AC", "elif", "supply", "==", "0", ":", "return", "common", ".", "POWER_TYPE_BATTERY", "else", ":", "raise", "RuntimeError", "(", "\"Unknown power source type!\"", ")" ]
FreeBSD use sysctl hw.acpi.acline to tell if Mains (1) is used or Battery (0). Beware, that on a Desktop machines this hw.acpi.acline oid may not exist. @return: One of common.POWER_TYPE_* @raise: Runtime error if type of power source is not supported
[ "FreeBSD", "use", "sysctl", "hw", ".", "acpi", ".", "acline", "to", "tell", "if", "Mains", "(", "1", ")", "is", "used", "or", "Battery", "(", "0", ")", ".", "Beware", "that", "on", "a", "Desktop", "machines", "this", "hw", ".", "acpi", ".", "acline", "oid", "may", "not", "exist", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L13-L30
Kentzo/Power
power/freebsd.py
PowerManagement.get_battery_state
def get_battery_state(): """ TODO @return: Tuple (energy_full, energy_now, power_now) """ energy_now = float(100.0) power_now = float(100.0) energy_full = float(100.0) return energy_full, energy_now, power_now
python
def get_battery_state(): """ TODO @return: Tuple (energy_full, energy_now, power_now) """ energy_now = float(100.0) power_now = float(100.0) energy_full = float(100.0) return energy_full, energy_now, power_now
[ "def", "get_battery_state", "(", ")", ":", "energy_now", "=", "float", "(", "100.0", ")", "power_now", "=", "float", "(", "100.0", ")", "energy_full", "=", "float", "(", "100.0", ")", "return", "energy_full", ",", "energy_now", ",", "power_now" ]
TODO @return: Tuple (energy_full, energy_now, power_now)
[ "TODO" ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L64-L72
Kentzo/Power
power/freebsd.py
PowerManagement.get_providing_power_source_type
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") return common.POWER_TYPE_AC
python
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") return common.POWER_TYPE_AC
[ "def", "get_providing_power_source_type", "(", "self", ")", ":", "type", "=", "self", ".", "power_source_type", "(", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", ")", ":", "return", "common", ".", "POWER_TYPE_AC", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", ")", "and", "self", ".", "is_battery_discharging", "(", ")", ":", "return", "common", ".", "POWER_TYPE_BATTERY", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "return", "common", ".", "POWER_TYPE_AC" ]
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned.
[ "Looks", "through", "all", "power", "supplies", "in", "POWER_SUPPLY_PATH", ".", "If", "there", "is", "an", "AC", "adapter", "online", "returns", "POWER_TYPE_AC", ".", "If", "there", "is", "a", "discharging", "battery", "returns", "POWER_TYPE_BATTERY", ".", "Since", "the", "order", "of", "supplies", "is", "arbitrary", "whatever", "found", "first", "is", "returned", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L75-L91
Kentzo/Power
power/freebsd.py
PowerManagement.get_low_battery_warning_level
def get_low_battery_warning_level(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """ all_energy_full = [] all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.LOW_BATTERY_WARNING_NONE elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_full.append(energy_full) all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) try: total_percentage = sum(all_energy_full) / sum(all_energy_now) total_time = sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) if total_time <= 10.0: return common.LOW_BATTERY_WARNING_FINAL elif total_percentage <= 22.0: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE except ZeroDivisionError as e: warnings.warn("Unable to calculate low battery level: {0}".format(e), category=RuntimeWarning) return common.LOW_BATTERY_WARNING_NONE
python
def get_low_battery_warning_level(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries. """ all_energy_full = [] all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(): return common.LOW_BATTERY_WARNING_NONE elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_full.append(energy_full) all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) try: total_percentage = sum(all_energy_full) / sum(all_energy_now) total_time = sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) if total_time <= 10.0: return common.LOW_BATTERY_WARNING_FINAL elif total_percentage <= 22.0: return common.LOW_BATTERY_WARNING_EARLY else: return common.LOW_BATTERY_WARNING_NONE except ZeroDivisionError as e: warnings.warn("Unable to calculate low battery level: {0}".format(e), category=RuntimeWarning) return common.LOW_BATTERY_WARNING_NONE
[ "def", "get_low_battery_warning_level", "(", "self", ")", ":", "all_energy_full", "=", "[", "]", "all_energy_now", "=", "[", "]", "all_power_now", "=", "[", "]", "try", ":", "type", "=", "self", ".", "power_source_type", "(", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", ")", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", ")", "and", "self", ".", "is_battery_discharging", "(", ")", ":", "energy_full", ",", "energy_now", ",", "power_now", "=", "self", ".", "get_battery_state", "(", ")", "all_energy_full", ".", "append", "(", "energy_full", ")", "all_energy_now", ".", "append", "(", "energy_now", ")", "all_power_now", ".", "append", "(", "power_now", ")", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read system power information!\"", ",", "category", "=", "RuntimeWarning", ")", "try", ":", "total_percentage", "=", "sum", "(", "all_energy_full", ")", "/", "sum", "(", "all_energy_now", ")", "total_time", "=", "sum", "(", "[", "energy_now", "/", "power_now", "*", "60.0", "for", "energy_now", ",", "power_now", "in", "zip", "(", "all_energy_now", ",", "all_power_now", ")", "]", ")", "if", "total_time", "<=", "10.0", ":", "return", "common", ".", "LOW_BATTERY_WARNING_FINAL", "elif", "total_percentage", "<=", "22.0", ":", "return", "common", ".", "LOW_BATTERY_WARNING_EARLY", "else", ":", "return", "common", ".", "LOW_BATTERY_WARNING_NONE", "except", "ZeroDivisionError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to calculate low battery level: {0}\"", ".", "format", "(", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "LOW_BATTERY_WARNING_NONE" ]
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC returns LOW_BATTERY_WARNING_NONE. Otherwise determines total percentage and time remaining across all attached batteries.
[ "Looks", "through", "all", "power", "supplies", "in", "POWER_SUPPLY_PATH", ".", "If", "there", "is", "an", "AC", "adapter", "online", "returns", "POWER_TYPE_AC", "returns", "LOW_BATTERY_WARNING_NONE", ".", "Otherwise", "determines", "total", "percentage", "and", "time", "remaining", "across", "all", "attached", "batteries", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L94-L130
Kentzo/Power
power/freebsd.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
python
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_power_now = [] try: type = self.power_source_type() if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present() and self.is_battery_discharging(): energy_full, energy_now, power_now = self.get_battery_state() all_energy_now.append(energy_now) all_power_now.append(power_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read system power information!", category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)]) except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "all_energy_now", "=", "[", "]", "all_power_now", "=", "[", "]", "try", ":", "type", "=", "self", ".", "power_source_type", "(", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", "supply_path", ")", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", ")", "and", "self", ".", "is_battery_discharging", "(", ")", ":", "energy_full", ",", "energy_now", ",", "power_now", "=", "self", ".", "get_battery_state", "(", ")", "all_energy_now", ".", "append", "(", "energy_now", ")", "all_power_now", ".", "append", "(", "power_now", ")", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read system power information!\"", ",", "category", "=", "RuntimeWarning", ")", "if", "len", "(", "all_energy_now", ")", ">", "0", ":", "try", ":", "return", "sum", "(", "[", "energy_now", "/", "power_now", "*", "60.0", "for", "energy_now", ",", "power_now", "in", "zip", "(", "all_energy_now", ",", "all_power_now", ")", "]", ")", "except", "ZeroDivisionError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to calculate time remaining estimate: {0}\"", ".", "format", "(", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "else", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN" ]
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online.
[ "Looks", "through", "all", "power", "sources", "and", "returns", "total", "time", "remaining", "estimate", "or", "TIME_REMAINING_UNLIMITED", "if", "ac", "power", "supply", "is", "online", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/freebsd.py#L133-L162
Kentzo/Power
power/linux.py
PowerManagement.get_providing_power_source_type
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) return common.POWER_TYPE_AC
python
def get_providing_power_source_type(self): """ Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned. """ for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.POWER_TYPE_AC elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): return common.POWER_TYPE_BATTERY else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) return common.POWER_TYPE_AC
[ "def", "get_providing_power_source_type", "(", "self", ")", ":", "for", "supply", "in", "os", ".", "listdir", "(", "POWER_SUPPLY_PATH", ")", ":", "supply_path", "=", "os", ".", "path", ".", "join", "(", "POWER_SUPPLY_PATH", ",", "supply", ")", "try", ":", "type", "=", "self", ".", "power_source_type", "(", "supply_path", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", "supply_path", ")", ":", "return", "common", ".", "POWER_TYPE_AC", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", "supply_path", ")", "and", "self", ".", "is_battery_discharging", "(", "supply_path", ")", ":", "return", "common", ".", "POWER_TYPE_BATTERY", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read properties of {0}: {1}\"", ".", "format", "(", "supply_path", ",", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "POWER_TYPE_AC" ]
Looks through all power supplies in POWER_SUPPLY_PATH. If there is an AC adapter online returns POWER_TYPE_AC. If there is a discharging battery, returns POWER_TYPE_BATTERY. Since the order of supplies is arbitrary, whatever found first is returned.
[ "Looks", "through", "all", "power", "supplies", "in", "POWER_SUPPLY_PATH", ".", "If", "there", "is", "an", "AC", "adapter", "online", "returns", "POWER_TYPE_AC", ".", "If", "there", "is", "a", "discharging", "battery", "returns", "POWER_TYPE_BATTERY", ".", "Since", "the", "order", "of", "supplies", "is", "arbitrary", "whatever", "found", "first", "is", "returned", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/linux.py#L88-L110
Kentzo/Power
power/linux.py
PowerManagement.get_time_remaining_estimate
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_energy_not_discharging = [] all_power_now = [] for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): energy_full, energy_now, power_now = self.get_battery_state(supply_path) all_energy_now.append(energy_now) all_power_now.append(power_now) elif self.is_battery_present(supply_path) and not self.is_battery_discharging(supply_path): energy_now = self.get_battery_state(supply_path)[1] all_energy_not_discharging.append(energy_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)])\ + sum(all_energy_not_discharging) / (sum(all_power_now) / len(all_power_now)) * 60.0 except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
python
def get_time_remaining_estimate(self): """ Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online. """ all_energy_now = [] all_energy_not_discharging = [] all_power_now = [] for supply in os.listdir(POWER_SUPPLY_PATH): supply_path = os.path.join(POWER_SUPPLY_PATH, supply) try: type = self.power_source_type(supply_path) if type == common.POWER_TYPE_AC: if self.is_ac_online(supply_path): return common.TIME_REMAINING_UNLIMITED elif type == common.POWER_TYPE_BATTERY: if self.is_battery_present(supply_path) and self.is_battery_discharging(supply_path): energy_full, energy_now, power_now = self.get_battery_state(supply_path) all_energy_now.append(energy_now) all_power_now.append(power_now) elif self.is_battery_present(supply_path) and not self.is_battery_discharging(supply_path): energy_now = self.get_battery_state(supply_path)[1] all_energy_not_discharging.append(energy_now) else: warnings.warn("UPS is not supported.") except (RuntimeError, IOError) as e: warnings.warn("Unable to read properties of {0}: {1}".format(supply_path, e), category=RuntimeWarning) if len(all_energy_now) > 0: try: return sum([energy_now / power_now * 60.0 for energy_now, power_now in zip(all_energy_now, all_power_now)])\ + sum(all_energy_not_discharging) / (sum(all_power_now) / len(all_power_now)) * 60.0 except ZeroDivisionError as e: warnings.warn("Unable to calculate time remaining estimate: {0}".format(e), category=RuntimeWarning) return common.TIME_REMAINING_UNKNOWN else: return common.TIME_REMAINING_UNKNOWN
[ "def", "get_time_remaining_estimate", "(", "self", ")", ":", "all_energy_now", "=", "[", "]", "all_energy_not_discharging", "=", "[", "]", "all_power_now", "=", "[", "]", "for", "supply", "in", "os", ".", "listdir", "(", "POWER_SUPPLY_PATH", ")", ":", "supply_path", "=", "os", ".", "path", ".", "join", "(", "POWER_SUPPLY_PATH", ",", "supply", ")", "try", ":", "type", "=", "self", ".", "power_source_type", "(", "supply_path", ")", "if", "type", "==", "common", ".", "POWER_TYPE_AC", ":", "if", "self", ".", "is_ac_online", "(", "supply_path", ")", ":", "return", "common", ".", "TIME_REMAINING_UNLIMITED", "elif", "type", "==", "common", ".", "POWER_TYPE_BATTERY", ":", "if", "self", ".", "is_battery_present", "(", "supply_path", ")", "and", "self", ".", "is_battery_discharging", "(", "supply_path", ")", ":", "energy_full", ",", "energy_now", ",", "power_now", "=", "self", ".", "get_battery_state", "(", "supply_path", ")", "all_energy_now", ".", "append", "(", "energy_now", ")", "all_power_now", ".", "append", "(", "power_now", ")", "elif", "self", ".", "is_battery_present", "(", "supply_path", ")", "and", "not", "self", ".", "is_battery_discharging", "(", "supply_path", ")", ":", "energy_now", "=", "self", ".", "get_battery_state", "(", "supply_path", ")", "[", "1", "]", "all_energy_not_discharging", ".", "append", "(", "energy_now", ")", "else", ":", "warnings", ".", "warn", "(", "\"UPS is not supported.\"", ")", "except", "(", "RuntimeError", ",", "IOError", ")", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to read properties of {0}: {1}\"", ".", "format", "(", "supply_path", ",", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "if", "len", "(", "all_energy_now", ")", ">", "0", ":", "try", ":", "return", "sum", "(", "[", "energy_now", "/", "power_now", "*", "60.0", "for", "energy_now", ",", "power_now", "in", "zip", "(", "all_energy_now", ",", "all_power_now", ")", "]", ")", "+", "sum", "(", "all_energy_not_discharging", ")", "/", "(", "sum", "(", "all_power_now", ")", "/", "len", "(", "all_power_now", ")", ")", "*", "60.0", "except", "ZeroDivisionError", "as", "e", ":", "warnings", ".", "warn", "(", "\"Unable to calculate time remaining estimate: {0}\"", ".", "format", "(", "e", ")", ",", "category", "=", "RuntimeWarning", ")", "return", "common", ".", "TIME_REMAINING_UNKNOWN", "else", ":", "return", "common", ".", "TIME_REMAINING_UNKNOWN" ]
Looks through all power sources and returns total time remaining estimate or TIME_REMAINING_UNLIMITED if ac power supply is online.
[ "Looks", "through", "all", "power", "sources", "and", "returns", "total", "time", "remaining", "estimate", "or", "TIME_REMAINING_UNLIMITED", "if", "ac", "power", "supply", "is", "online", "." ]
train
https://github.com/Kentzo/Power/blob/2c99b156546225e448f7030681af3df5cd345e4b/power/linux.py#L152-L188
pilliq/scratchpy
scratch/scratch.py
Scratch._pack
def _pack(self, msg): """ Packages msg according to Scratch message specification (encodes and appends length prefix to msg). Credit to chalkmarrow from the scratch.mit.edu forums for the prefix encoding code. """ n = len(msg) a = array.array('c') a.append(chr((n >> 24) & 0xFF)) a.append(chr((n >> 16) & 0xFF)) a.append(chr((n >> 8) & 0xFF)) a.append(chr(n & 0xFF)) return a.tostring() + msg
python
def _pack(self, msg): """ Packages msg according to Scratch message specification (encodes and appends length prefix to msg). Credit to chalkmarrow from the scratch.mit.edu forums for the prefix encoding code. """ n = len(msg) a = array.array('c') a.append(chr((n >> 24) & 0xFF)) a.append(chr((n >> 16) & 0xFF)) a.append(chr((n >> 8) & 0xFF)) a.append(chr(n & 0xFF)) return a.tostring() + msg
[ "def", "_pack", "(", "self", ",", "msg", ")", ":", "n", "=", "len", "(", "msg", ")", "a", "=", "array", ".", "array", "(", "'c'", ")", "a", ".", "append", "(", "chr", "(", "(", "n", ">>", "24", ")", "&", "0xFF", ")", ")", "a", ".", "append", "(", "chr", "(", "(", "n", ">>", "16", ")", "&", "0xFF", ")", ")", "a", ".", "append", "(", "chr", "(", "(", "n", ">>", "8", ")", "&", "0xFF", ")", ")", "a", ".", "append", "(", "chr", "(", "n", "&", "0xFF", ")", ")", "return", "a", ".", "tostring", "(", ")", "+", "msg" ]
Packages msg according to Scratch message specification (encodes and appends length prefix to msg). Credit to chalkmarrow from the scratch.mit.edu forums for the prefix encoding code.
[ "Packages", "msg", "according", "to", "Scratch", "message", "specification", "(", "encodes", "and", "appends", "length", "prefix", "to", "msg", ")", ".", "Credit", "to", "chalkmarrow", "from", "the", "scratch", ".", "mit", ".", "edu", "forums", "for", "the", "prefix", "encoding", "code", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L27-L39
pilliq/scratchpy
scratch/scratch.py
Scratch._get_type
def _get_type(self, s): """ Converts a string from Scratch to its proper type in Python. Expects a string with its delimiting quotes in place. Returns either a string, int or float. """ # TODO: what if the number is bigger than an int or float? if s.startswith('"') and s.endswith('"'): return s[1:-1] elif s.find('.') != -1: return float(s) else: return int(s)
python
def _get_type(self, s): """ Converts a string from Scratch to its proper type in Python. Expects a string with its delimiting quotes in place. Returns either a string, int or float. """ # TODO: what if the number is bigger than an int or float? if s.startswith('"') and s.endswith('"'): return s[1:-1] elif s.find('.') != -1: return float(s) else: return int(s)
[ "def", "_get_type", "(", "self", ",", "s", ")", ":", "# TODO: what if the number is bigger than an int or float?", "if", "s", ".", "startswith", "(", "'\"'", ")", "and", "s", ".", "endswith", "(", "'\"'", ")", ":", "return", "s", "[", "1", ":", "-", "1", "]", "elif", "s", ".", "find", "(", "'.'", ")", "!=", "-", "1", ":", "return", "float", "(", "s", ")", "else", ":", "return", "int", "(", "s", ")" ]
Converts a string from Scratch to its proper type in Python. Expects a string with its delimiting quotes in place. Returns either a string, int or float.
[ "Converts", "a", "string", "from", "Scratch", "to", "its", "proper", "type", "in", "Python", ".", "Expects", "a", "string", "with", "its", "delimiting", "quotes", "in", "place", ".", "Returns", "either", "a", "string", "int", "or", "float", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L47-L59
pilliq/scratchpy
scratch/scratch.py
Scratch._escape
def _escape(self, msg): """ Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string. """ escaped = '' for c in msg: escaped += c if c == '"': escaped += '"' return escaped
python
def _escape(self, msg): """ Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string. """ escaped = '' for c in msg: escaped += c if c == '"': escaped += '"' return escaped
[ "def", "_escape", "(", "self", ",", "msg", ")", ":", "escaped", "=", "''", "for", "c", "in", "msg", ":", "escaped", "+=", "c", "if", "c", "==", "'\"'", ":", "escaped", "+=", "'\"'", "return", "escaped" ]
Escapes double quotes by adding another double quote as per the Scratch protocol. Expects a string without its delimiting quotes. Returns a new escaped string.
[ "Escapes", "double", "quotes", "by", "adding", "another", "double", "quote", "as", "per", "the", "Scratch", "protocol", ".", "Expects", "a", "string", "without", "its", "delimiting", "quotes", ".", "Returns", "a", "new", "escaped", "string", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L61-L72
pilliq/scratchpy
scratch/scratch.py
Scratch._unescape
def _unescape(self, msg): """ Removes double quotes that were used to escape double quotes. Expects a string without its delimiting quotes, or a number. Returns a new unescaped string. """ if isinstance(msg, (int, float, long)): return msg unescaped = '' i = 0 while i < len(msg): unescaped += msg[i] if msg[i] == '"': i+=1 i+=1 return unescaped
python
def _unescape(self, msg): """ Removes double quotes that were used to escape double quotes. Expects a string without its delimiting quotes, or a number. Returns a new unescaped string. """ if isinstance(msg, (int, float, long)): return msg unescaped = '' i = 0 while i < len(msg): unescaped += msg[i] if msg[i] == '"': i+=1 i+=1 return unescaped
[ "def", "_unescape", "(", "self", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "(", "int", ",", "float", ",", "long", ")", ")", ":", "return", "msg", "unescaped", "=", "''", "i", "=", "0", "while", "i", "<", "len", "(", "msg", ")", ":", "unescaped", "+=", "msg", "[", "i", "]", "if", "msg", "[", "i", "]", "==", "'\"'", ":", "i", "+=", "1", "i", "+=", "1", "return", "unescaped" ]
Removes double quotes that were used to escape double quotes. Expects a string without its delimiting quotes, or a number. Returns a new unescaped string.
[ "Removes", "double", "quotes", "that", "were", "used", "to", "escape", "double", "quotes", ".", "Expects", "a", "string", "without", "its", "delimiting", "quotes", "or", "a", "number", ".", "Returns", "a", "new", "unescaped", "string", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L74-L90
pilliq/scratchpy
scratch/scratch.py
Scratch._is_msg
def _is_msg(self, msg): """ Returns True if message is a proper Scratch message, else return False. """ if not msg or len(msg) < self.prefix_len: return False length = self._extract_len(msg[:self.prefix_len]) msg_type = msg[self.prefix_len:].split(' ', 1)[0] if length == len(msg[self.prefix_len:]) and msg_type in self.msg_types: return True return False
python
def _is_msg(self, msg): """ Returns True if message is a proper Scratch message, else return False. """ if not msg or len(msg) < self.prefix_len: return False length = self._extract_len(msg[:self.prefix_len]) msg_type = msg[self.prefix_len:].split(' ', 1)[0] if length == len(msg[self.prefix_len:]) and msg_type in self.msg_types: return True return False
[ "def", "_is_msg", "(", "self", ",", "msg", ")", ":", "if", "not", "msg", "or", "len", "(", "msg", ")", "<", "self", ".", "prefix_len", ":", "return", "False", "length", "=", "self", ".", "_extract_len", "(", "msg", "[", ":", "self", ".", "prefix_len", "]", ")", "msg_type", "=", "msg", "[", "self", ".", "prefix_len", ":", "]", ".", "split", "(", "' '", ",", "1", ")", "[", "0", "]", "if", "length", "==", "len", "(", "msg", "[", "self", ".", "prefix_len", ":", "]", ")", "and", "msg_type", "in", "self", ".", "msg_types", ":", "return", "True", "return", "False" ]
Returns True if message is a proper Scratch message, else return False.
[ "Returns", "True", "if", "message", "is", "a", "proper", "Scratch", "message", "else", "return", "False", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L92-L102
pilliq/scratchpy
scratch/scratch.py
Scratch._parse_broadcast
def _parse_broadcast(self, msg): """ Given a broacast message, returns the message that was broadcast. """ # get message, remove surrounding quotes, and unescape return self._unescape(self._get_type(msg[self.broadcast_prefix_len:]))
python
def _parse_broadcast(self, msg): """ Given a broacast message, returns the message that was broadcast. """ # get message, remove surrounding quotes, and unescape return self._unescape(self._get_type(msg[self.broadcast_prefix_len:]))
[ "def", "_parse_broadcast", "(", "self", ",", "msg", ")", ":", "# get message, remove surrounding quotes, and unescape", "return", "self", ".", "_unescape", "(", "self", ".", "_get_type", "(", "msg", "[", "self", ".", "broadcast_prefix_len", ":", "]", ")", ")" ]
Given a broacast message, returns the message that was broadcast.
[ "Given", "a", "broacast", "message", "returns", "the", "message", "that", "was", "broadcast", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L104-L109
pilliq/scratchpy
scratch/scratch.py
Scratch._parse_sensorupdate
def _parse_sensorupdate(self, msg): """ Given a sensor-update message, returns the sensors/variables that were updated as a dict that maps sensors/variables to their updated values. """ update = msg[self.sensorupdate_prefix_len:] parsed = [] # each element is either a sensor (key) or a sensor value curr_seg = '' # current segment (i.e. key or value) being formed numq = 0 # number of double quotes in current segment for seg in update.split(' ')[:-1]: # last char in update is a space numq += seg.count('"') curr_seg += seg # even number of quotes means we've finished parsing a segment if numq % 2 == 0: parsed.append(curr_seg) curr_seg = '' numq = 0 else: # segment has a space inside, so add back it in curr_seg += ' ' unescaped = [self._unescape(self._get_type(x)) for x in parsed] # combine into a dict using iterators (both elements in the list # inputted to izip have a reference to the same iterator). even # elements are keys, odd are values return dict(itertools.izip(*[iter(unescaped)]*2))
python
def _parse_sensorupdate(self, msg): """ Given a sensor-update message, returns the sensors/variables that were updated as a dict that maps sensors/variables to their updated values. """ update = msg[self.sensorupdate_prefix_len:] parsed = [] # each element is either a sensor (key) or a sensor value curr_seg = '' # current segment (i.e. key or value) being formed numq = 0 # number of double quotes in current segment for seg in update.split(' ')[:-1]: # last char in update is a space numq += seg.count('"') curr_seg += seg # even number of quotes means we've finished parsing a segment if numq % 2 == 0: parsed.append(curr_seg) curr_seg = '' numq = 0 else: # segment has a space inside, so add back it in curr_seg += ' ' unescaped = [self._unescape(self._get_type(x)) for x in parsed] # combine into a dict using iterators (both elements in the list # inputted to izip have a reference to the same iterator). even # elements are keys, odd are values return dict(itertools.izip(*[iter(unescaped)]*2))
[ "def", "_parse_sensorupdate", "(", "self", ",", "msg", ")", ":", "update", "=", "msg", "[", "self", ".", "sensorupdate_prefix_len", ":", "]", "parsed", "=", "[", "]", "# each element is either a sensor (key) or a sensor value", "curr_seg", "=", "''", "# current segment (i.e. key or value) being formed", "numq", "=", "0", "# number of double quotes in current segment", "for", "seg", "in", "update", ".", "split", "(", "' '", ")", "[", ":", "-", "1", "]", ":", "# last char in update is a space", "numq", "+=", "seg", ".", "count", "(", "'\"'", ")", "curr_seg", "+=", "seg", "# even number of quotes means we've finished parsing a segment", "if", "numq", "%", "2", "==", "0", ":", "parsed", ".", "append", "(", "curr_seg", ")", "curr_seg", "=", "''", "numq", "=", "0", "else", ":", "# segment has a space inside, so add back it in", "curr_seg", "+=", "' '", "unescaped", "=", "[", "self", ".", "_unescape", "(", "self", ".", "_get_type", "(", "x", ")", ")", "for", "x", "in", "parsed", "]", "# combine into a dict using iterators (both elements in the list", "# inputted to izip have a reference to the same iterator). even ", "# elements are keys, odd are values", "return", "dict", "(", "itertools", ".", "izip", "(", "*", "[", "iter", "(", "unescaped", ")", "]", "*", "2", ")", ")" ]
Given a sensor-update message, returns the sensors/variables that were updated as a dict that maps sensors/variables to their updated values.
[ "Given", "a", "sensor", "-", "update", "message", "returns", "the", "sensors", "/", "variables", "that", "were", "updated", "as", "a", "dict", "that", "maps", "sensors", "/", "variables", "to", "their", "updated", "values", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L111-L134
pilliq/scratchpy
scratch/scratch.py
Scratch._parse
def _parse(self, msg): """ Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' message is a dict whose keys are variables, and values are updated variable values. Returns None if msg is not a message. """ if not self._is_msg(msg): return None msg_type = msg[self.prefix_len:].split(' ')[0] if msg_type == 'broadcast': return ('broadcast', self._parse_broadcast(msg)) else: return ('sensor-update', self._parse_sensorupdate(msg))
python
def _parse(self, msg): """ Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' message is a dict whose keys are variables, and values are updated variable values. Returns None if msg is not a message. """ if not self._is_msg(msg): return None msg_type = msg[self.prefix_len:].split(' ')[0] if msg_type == 'broadcast': return ('broadcast', self._parse_broadcast(msg)) else: return ('sensor-update', self._parse_sensorupdate(msg))
[ "def", "_parse", "(", "self", ",", "msg", ")", ":", "if", "not", "self", ".", "_is_msg", "(", "msg", ")", ":", "return", "None", "msg_type", "=", "msg", "[", "self", ".", "prefix_len", ":", "]", ".", "split", "(", "' '", ")", "[", "0", "]", "if", "msg_type", "==", "'broadcast'", ":", "return", "(", "'broadcast'", ",", "self", ".", "_parse_broadcast", "(", "msg", ")", ")", "else", ":", "return", "(", "'sensor-update'", ",", "self", ".", "_parse_sensorupdate", "(", "msg", ")", ")" ]
Parses a Scratch message and returns a tuple with the first element as the message type, and the second element as the message payload. The payload for a 'broadcast' message is a string, and the payload for a 'sensor-update' message is a dict whose keys are variables, and values are updated variable values. Returns None if msg is not a message.
[ "Parses", "a", "Scratch", "message", "and", "returns", "a", "tuple", "with", "the", "first", "element", "as", "the", "message", "type", "and", "the", "second", "element", "as", "the", "message", "payload", ".", "The", "payload", "for", "a", "broadcast", "message", "is", "a", "string", "and", "the", "payload", "for", "a", "sensor", "-", "update", "message", "is", "a", "dict", "whose", "keys", "are", "variables", "and", "values", "are", "updated", "variable", "values", ".", "Returns", "None", "if", "msg", "is", "not", "a", "message", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L136-L150
pilliq/scratchpy
scratch/scratch.py
Scratch._write
def _write(self, data): """ Writes string data out to Scratch """ total_sent = 0 length = len(data) while total_sent < length: try: sent = self.socket.send(data[total_sent:]) except socket.error as (err, msg): self.connected = False raise ScratchError("[Errno %d] %s" % (err, msg)) if sent == 0: self.connected = False raise ScratchConnectionError("Connection broken") total_sent += sent
python
def _write(self, data): """ Writes string data out to Scratch """ total_sent = 0 length = len(data) while total_sent < length: try: sent = self.socket.send(data[total_sent:]) except socket.error as (err, msg): self.connected = False raise ScratchError("[Errno %d] %s" % (err, msg)) if sent == 0: self.connected = False raise ScratchConnectionError("Connection broken") total_sent += sent
[ "def", "_write", "(", "self", ",", "data", ")", ":", "total_sent", "=", "0", "length", "=", "len", "(", "data", ")", "while", "total_sent", "<", "length", ":", "try", ":", "sent", "=", "self", ".", "socket", ".", "send", "(", "data", "[", "total_sent", ":", "]", ")", "except", "socket", ".", "error", "as", "(", "err", ",", "msg", ")", ":", "self", ".", "connected", "=", "False", "raise", "ScratchError", "(", "\"[Errno %d] %s\"", "%", "(", "err", ",", "msg", ")", ")", "if", "sent", "==", "0", ":", "self", ".", "connected", "=", "False", "raise", "ScratchConnectionError", "(", "\"Connection broken\"", ")", "total_sent", "+=", "sent" ]
Writes string data out to Scratch
[ "Writes", "string", "data", "out", "to", "Scratch" ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L152-L167
pilliq/scratchpy
scratch/scratch.py
Scratch._read
def _read(self, size): """ Reads size number of bytes from Scratch and returns data as a string """ data = '' while len(data) < size: try: chunk = self.socket.recv(size-len(data)) except socket.error as (err, msg): self.connected = False raise ScratchError("[Errno %d] %s" % (err, msg)) if chunk == '': self.connected = False raise ScratchConnectionError("Connection broken") data += chunk return data
python
def _read(self, size): """ Reads size number of bytes from Scratch and returns data as a string """ data = '' while len(data) < size: try: chunk = self.socket.recv(size-len(data)) except socket.error as (err, msg): self.connected = False raise ScratchError("[Errno %d] %s" % (err, msg)) if chunk == '': self.connected = False raise ScratchConnectionError("Connection broken") data += chunk return data
[ "def", "_read", "(", "self", ",", "size", ")", ":", "data", "=", "''", "while", "len", "(", "data", ")", "<", "size", ":", "try", ":", "chunk", "=", "self", ".", "socket", ".", "recv", "(", "size", "-", "len", "(", "data", ")", ")", "except", "socket", ".", "error", "as", "(", "err", ",", "msg", ")", ":", "self", ".", "connected", "=", "False", "raise", "ScratchError", "(", "\"[Errno %d] %s\"", "%", "(", "err", ",", "msg", ")", ")", "if", "chunk", "==", "''", ":", "self", ".", "connected", "=", "False", "raise", "ScratchConnectionError", "(", "\"Connection broken\"", ")", "data", "+=", "chunk", "return", "data" ]
Reads size number of bytes from Scratch and returns data as a string
[ "Reads", "size", "number", "of", "bytes", "from", "Scratch", "and", "returns", "data", "as", "a", "string" ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L175-L190
pilliq/scratchpy
scratch/scratch.py
Scratch._recv
def _recv(self): """ Receives and returns a message from Scratch """ prefix = self._read(self.prefix_len) msg = self._read(self._extract_len(prefix)) return prefix + msg
python
def _recv(self): """ Receives and returns a message from Scratch """ prefix = self._read(self.prefix_len) msg = self._read(self._extract_len(prefix)) return prefix + msg
[ "def", "_recv", "(", "self", ")", ":", "prefix", "=", "self", ".", "_read", "(", "self", ".", "prefix_len", ")", "msg", "=", "self", ".", "_read", "(", "self", ".", "_extract_len", "(", "prefix", ")", ")", "return", "prefix", "+", "msg" ]
Receives and returns a message from Scratch
[ "Receives", "and", "returns", "a", "message", "from", "Scratch" ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L192-L198
pilliq/scratchpy
scratch/scratch.py
Scratch.connect
def connect(self): """ Connects to Scratch. """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self.host, self.port)) except socket.error as (err, msg): self.connected = False raise ScratchError("[Errno %d] %s" % (err, msg)) self.connected = True
python
def connect(self): """ Connects to Scratch. """ self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: self.socket.connect((self.host, self.port)) except socket.error as (err, msg): self.connected = False raise ScratchError("[Errno %d] %s" % (err, msg)) self.connected = True
[ "def", "connect", "(", "self", ")", ":", "self", ".", "socket", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "try", ":", "self", ".", "socket", ".", "connect", "(", "(", "self", ".", "host", ",", "self", ".", "port", ")", ")", "except", "socket", ".", "error", "as", "(", "err", ",", "msg", ")", ":", "self", ".", "connected", "=", "False", "raise", "ScratchError", "(", "\"[Errno %d] %s\"", "%", "(", "err", ",", "msg", ")", ")", "self", ".", "connected", "=", "True" ]
Connects to Scratch.
[ "Connects", "to", "Scratch", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L200-L210
pilliq/scratchpy
scratch/scratch.py
Scratch.disconnect
def disconnect(self): """ Closes connection to Scratch """ try: # connection may already be disconnected, so catch exceptions self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect except socket.error: pass self.socket.close() self.connected = False
python
def disconnect(self): """ Closes connection to Scratch """ try: # connection may already be disconnected, so catch exceptions self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect except socket.error: pass self.socket.close() self.connected = False
[ "def", "disconnect", "(", "self", ")", ":", "try", ":", "# connection may already be disconnected, so catch exceptions", "self", ".", "socket", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "# a proper disconnect", "except", "socket", ".", "error", ":", "pass", "self", ".", "socket", ".", "close", "(", ")", "self", ".", "connected", "=", "False" ]
Closes connection to Scratch
[ "Closes", "connection", "to", "Scratch" ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L212-L221
pilliq/scratchpy
scratch/scratch.py
Scratch.sensorupdate
def sensorupdate(self, data): """ Given a dict of sensors and values, updates those sensors with the values in Scratch. """ if not isinstance(data, dict): raise TypeError('Expected a dict') msg = 'sensor-update ' for key in data.keys(): msg += '"%s" "%s" ' % (self._escape(str(key)), self._escape(str(data[key]))) self._send(msg)
python
def sensorupdate(self, data): """ Given a dict of sensors and values, updates those sensors with the values in Scratch. """ if not isinstance(data, dict): raise TypeError('Expected a dict') msg = 'sensor-update ' for key in data.keys(): msg += '"%s" "%s" ' % (self._escape(str(key)), self._escape(str(data[key]))) self._send(msg)
[ "def", "sensorupdate", "(", "self", ",", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "dict", ")", ":", "raise", "TypeError", "(", "'Expected a dict'", ")", "msg", "=", "'sensor-update '", "for", "key", "in", "data", ".", "keys", "(", ")", ":", "msg", "+=", "'\"%s\" \"%s\" '", "%", "(", "self", ".", "_escape", "(", "str", "(", "key", ")", ")", ",", "self", ".", "_escape", "(", "str", "(", "data", "[", "key", "]", ")", ")", ")", "self", ".", "_send", "(", "msg", ")" ]
Given a dict of sensors and values, updates those sensors with the values in Scratch.
[ "Given", "a", "dict", "of", "sensors", "and", "values", "updates", "those", "sensors", "with", "the", "values", "in", "Scratch", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L223-L234
pilliq/scratchpy
scratch/scratch.py
Scratch.broadcast
def broadcast(self, msg): """ Broadcasts msg to Scratch. msg can be a single message or an iterable (list, tuple, set, generator, etc.) of messages. """ if getattr(msg, '__iter__', False): # iterable for m in msg: self._send('broadcast "%s"' % self._escape(str(m))) else: # probably a string or number self._send('broadcast "%s"' % self._escape(str(msg)))
python
def broadcast(self, msg): """ Broadcasts msg to Scratch. msg can be a single message or an iterable (list, tuple, set, generator, etc.) of messages. """ if getattr(msg, '__iter__', False): # iterable for m in msg: self._send('broadcast "%s"' % self._escape(str(m))) else: # probably a string or number self._send('broadcast "%s"' % self._escape(str(msg)))
[ "def", "broadcast", "(", "self", ",", "msg", ")", ":", "if", "getattr", "(", "msg", ",", "'__iter__'", ",", "False", ")", ":", "# iterable", "for", "m", "in", "msg", ":", "self", ".", "_send", "(", "'broadcast \"%s\"'", "%", "self", ".", "_escape", "(", "str", "(", "m", ")", ")", ")", "else", ":", "# probably a string or number", "self", ".", "_send", "(", "'broadcast \"%s\"'", "%", "self", ".", "_escape", "(", "str", "(", "msg", ")", ")", ")" ]
Broadcasts msg to Scratch. msg can be a single message or an iterable (list, tuple, set, generator, etc.) of messages.
[ "Broadcasts", "msg", "to", "Scratch", ".", "msg", "can", "be", "a", "single", "message", "or", "an", "iterable", "(", "list", "tuple", "set", "generator", "etc", ".", ")", "of", "messages", "." ]
train
https://github.com/pilliq/scratchpy/blob/a594561c147b1cf6696231c26a0475c7d52b8039/scratch/scratch.py#L236-L245
AirSage/Petrel
petrel/petrel/mock.py
Mock.run_simple_topology
def run_simple_topology(cls, config, emitters, result_type=NAMEDTUPLE, max_spout_emits=None): """Tests a simple topology. "Simple" means there it has no branches or cycles. "emitters" is a list of emitters, starting with a spout followed by 0 or more bolts that run in a chain.""" # The config is almost always required. The only known reason to pass # None is when calling run_simple_topology() multiple times for the # same components. This can be useful for testing spout ack() and fail() # behavior. if config is not None: for emitter in emitters: emitter.initialize(config, {}) with cls() as self: # Read from the spout. spout = emitters[0] spout_id = self.emitter_id(spout) old_length = -1 length = len(self.pending[spout_id]) while length > old_length and (max_spout_emits is None or length < max_spout_emits): old_length = length self.activate(spout) spout.nextTuple() length = len(self.pending[spout_id]) # For each bolt in the sequence, consume all upstream input. for i, bolt in enumerate(emitters[1:]): previous = emitters[i] self.activate(bolt) while len(self.pending[self.emitter_id(previous)]) > 0: bolt.process(self.read(previous)) def make_storm_tuple(t, emitter): return t def make_python_list(t, emitter): return list(t.values) def make_python_tuple(t, emitter): return tuple(t.values) def make_named_tuple(t, emitter): return self.get_output_type(emitter)(*t.values) if result_type == STORM_TUPLE: make = make_storm_tuple elif result_type == LIST: make = make_python_list elif result_type == NAMEDTUPLE: make = make_named_tuple else: assert False, 'Invalid result type specified: %s' % result_type result_values = \ [ [ make(t, emitter) for t in self.processed[self.emitter_id(emitter)]] for emitter in emitters[:-1] ] + \ [ [ make(t, emitters[-1]) for t in self.pending[self.emitter_id(emitters[-1])] ] ] return dict((k, v) for k, v in zip(emitters, result_values))
python
def run_simple_topology(cls, config, emitters, result_type=NAMEDTUPLE, max_spout_emits=None): """Tests a simple topology. "Simple" means there it has no branches or cycles. "emitters" is a list of emitters, starting with a spout followed by 0 or more bolts that run in a chain.""" # The config is almost always required. The only known reason to pass # None is when calling run_simple_topology() multiple times for the # same components. This can be useful for testing spout ack() and fail() # behavior. if config is not None: for emitter in emitters: emitter.initialize(config, {}) with cls() as self: # Read from the spout. spout = emitters[0] spout_id = self.emitter_id(spout) old_length = -1 length = len(self.pending[spout_id]) while length > old_length and (max_spout_emits is None or length < max_spout_emits): old_length = length self.activate(spout) spout.nextTuple() length = len(self.pending[spout_id]) # For each bolt in the sequence, consume all upstream input. for i, bolt in enumerate(emitters[1:]): previous = emitters[i] self.activate(bolt) while len(self.pending[self.emitter_id(previous)]) > 0: bolt.process(self.read(previous)) def make_storm_tuple(t, emitter): return t def make_python_list(t, emitter): return list(t.values) def make_python_tuple(t, emitter): return tuple(t.values) def make_named_tuple(t, emitter): return self.get_output_type(emitter)(*t.values) if result_type == STORM_TUPLE: make = make_storm_tuple elif result_type == LIST: make = make_python_list elif result_type == NAMEDTUPLE: make = make_named_tuple else: assert False, 'Invalid result type specified: %s' % result_type result_values = \ [ [ make(t, emitter) for t in self.processed[self.emitter_id(emitter)]] for emitter in emitters[:-1] ] + \ [ [ make(t, emitters[-1]) for t in self.pending[self.emitter_id(emitters[-1])] ] ] return dict((k, v) for k, v in zip(emitters, result_values))
[ "def", "run_simple_topology", "(", "cls", ",", "config", ",", "emitters", ",", "result_type", "=", "NAMEDTUPLE", ",", "max_spout_emits", "=", "None", ")", ":", "# The config is almost always required. The only known reason to pass", "# None is when calling run_simple_topology() multiple times for the", "# same components. This can be useful for testing spout ack() and fail()", "# behavior.", "if", "config", "is", "not", "None", ":", "for", "emitter", "in", "emitters", ":", "emitter", ".", "initialize", "(", "config", ",", "{", "}", ")", "with", "cls", "(", ")", "as", "self", ":", "# Read from the spout.", "spout", "=", "emitters", "[", "0", "]", "spout_id", "=", "self", ".", "emitter_id", "(", "spout", ")", "old_length", "=", "-", "1", "length", "=", "len", "(", "self", ".", "pending", "[", "spout_id", "]", ")", "while", "length", ">", "old_length", "and", "(", "max_spout_emits", "is", "None", "or", "length", "<", "max_spout_emits", ")", ":", "old_length", "=", "length", "self", ".", "activate", "(", "spout", ")", "spout", ".", "nextTuple", "(", ")", "length", "=", "len", "(", "self", ".", "pending", "[", "spout_id", "]", ")", "# For each bolt in the sequence, consume all upstream input.", "for", "i", ",", "bolt", "in", "enumerate", "(", "emitters", "[", "1", ":", "]", ")", ":", "previous", "=", "emitters", "[", "i", "]", "self", ".", "activate", "(", "bolt", ")", "while", "len", "(", "self", ".", "pending", "[", "self", ".", "emitter_id", "(", "previous", ")", "]", ")", ">", "0", ":", "bolt", ".", "process", "(", "self", ".", "read", "(", "previous", ")", ")", "def", "make_storm_tuple", "(", "t", ",", "emitter", ")", ":", "return", "t", "def", "make_python_list", "(", "t", ",", "emitter", ")", ":", "return", "list", "(", "t", ".", "values", ")", "def", "make_python_tuple", "(", "t", ",", "emitter", ")", ":", "return", "tuple", "(", "t", ".", "values", ")", "def", "make_named_tuple", "(", "t", ",", "emitter", ")", ":", "return", "self", ".", "get_output_type", "(", "emitter", ")", "(", "*", "t", ".", "values", ")", "if", "result_type", "==", "STORM_TUPLE", ":", "make", "=", "make_storm_tuple", "elif", "result_type", "==", "LIST", ":", "make", "=", "make_python_list", "elif", "result_type", "==", "NAMEDTUPLE", ":", "make", "=", "make_named_tuple", "else", ":", "assert", "False", ",", "'Invalid result type specified: %s'", "%", "result_type", "result_values", "=", "[", "[", "make", "(", "t", ",", "emitter", ")", "for", "t", "in", "self", ".", "processed", "[", "self", ".", "emitter_id", "(", "emitter", ")", "]", "]", "for", "emitter", "in", "emitters", "[", ":", "-", "1", "]", "]", "+", "[", "[", "make", "(", "t", ",", "emitters", "[", "-", "1", "]", ")", "for", "t", "in", "self", ".", "pending", "[", "self", ".", "emitter_id", "(", "emitters", "[", "-", "1", "]", ")", "]", "]", "]", "return", "dict", "(", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "zip", "(", "emitters", ",", "result_values", ")", ")" ]
Tests a simple topology. "Simple" means there it has no branches or cycles. "emitters" is a list of emitters, starting with a spout followed by 0 or more bolts that run in a chain.
[ "Tests", "a", "simple", "topology", ".", "Simple", "means", "there", "it", "has", "no", "branches", "or", "cycles", ".", "emitters", "is", "a", "list", "of", "emitters", "starting", "with", "a", "spout", "followed", "by", "0", "or", "more", "bolts", "that", "run", "in", "a", "chain", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/mock.py#L108-L164
AirSage/Petrel
petrel/petrel/topologybuilder.py
TopologyBuilder.write
def write(self, stream): """Writes the topology to a stream or file.""" topology = self.createTopology() def write_it(stream): transportOut = TMemoryBuffer() protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut) topology.write(protocolOut) bytes = transportOut.getvalue() stream.write(bytes) if isinstance(stream, six.string_types): with open(stream, 'wb') as f: write_it(f) else: write_it(stream) return topology
python
def write(self, stream): """Writes the topology to a stream or file.""" topology = self.createTopology() def write_it(stream): transportOut = TMemoryBuffer() protocolOut = TBinaryProtocol.TBinaryProtocol(transportOut) topology.write(protocolOut) bytes = transportOut.getvalue() stream.write(bytes) if isinstance(stream, six.string_types): with open(stream, 'wb') as f: write_it(f) else: write_it(stream) return topology
[ "def", "write", "(", "self", ",", "stream", ")", ":", "topology", "=", "self", ".", "createTopology", "(", ")", "def", "write_it", "(", "stream", ")", ":", "transportOut", "=", "TMemoryBuffer", "(", ")", "protocolOut", "=", "TBinaryProtocol", ".", "TBinaryProtocol", "(", "transportOut", ")", "topology", ".", "write", "(", "protocolOut", ")", "bytes", "=", "transportOut", ".", "getvalue", "(", ")", "stream", ".", "write", "(", "bytes", ")", "if", "isinstance", "(", "stream", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "stream", ",", "'wb'", ")", "as", "f", ":", "write_it", "(", "f", ")", "else", ":", "write_it", "(", "stream", ")", "return", "topology" ]
Writes the topology to a stream or file.
[ "Writes", "the", "topology", "to", "a", "stream", "or", "file", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/topologybuilder.py#L110-L126
AirSage/Petrel
petrel/petrel/topologybuilder.py
TopologyBuilder.read
def read(self, stream): """Reads the topology from a stream or file.""" def read_it(stream): bytes = stream.read() transportIn = TMemoryBuffer(bytes) protocolIn = TBinaryProtocol.TBinaryProtocol(transportIn) topology = StormTopology() topology.read(protocolIn) return topology if isinstance(stream, six.string_types): with open(stream, 'rb') as f: return read_it(f) else: return read_it(stream)
python
def read(self, stream): """Reads the topology from a stream or file.""" def read_it(stream): bytes = stream.read() transportIn = TMemoryBuffer(bytes) protocolIn = TBinaryProtocol.TBinaryProtocol(transportIn) topology = StormTopology() topology.read(protocolIn) return topology if isinstance(stream, six.string_types): with open(stream, 'rb') as f: return read_it(f) else: return read_it(stream)
[ "def", "read", "(", "self", ",", "stream", ")", ":", "def", "read_it", "(", "stream", ")", ":", "bytes", "=", "stream", ".", "read", "(", ")", "transportIn", "=", "TMemoryBuffer", "(", "bytes", ")", "protocolIn", "=", "TBinaryProtocol", ".", "TBinaryProtocol", "(", "transportIn", ")", "topology", "=", "StormTopology", "(", ")", "topology", ".", "read", "(", "protocolIn", ")", "return", "topology", "if", "isinstance", "(", "stream", ",", "six", ".", "string_types", ")", ":", "with", "open", "(", "stream", ",", "'rb'", ")", "as", "f", ":", "return", "read_it", "(", "f", ")", "else", ":", "return", "read_it", "(", "stream", ")" ]
Reads the topology from a stream or file.
[ "Reads", "the", "topology", "from", "a", "stream", "or", "file", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/topologybuilder.py#L128-L142
AirSage/Petrel
petrel/petrel/package.py
build_jar
def build_jar(source_jar_path, dest_jar_path, config, venv=None, definition=None, logdir=None): """Build a StormTopology .jar which encapsulates the topology defined in topology_dir. Optionally override the module and function names. This feature supports the definition of multiple topologies in a single directory.""" if definition is None: definition = 'create.create' # Prepare data we'll use later for configuring parallelism. config_yaml = read_yaml(config) parallelism = dict((k.split('.')[-1], v) for k, v in six.iteritems(config_yaml) if k.startswith('petrel.parallelism')) pip_options = config_yaml.get('petrel.pip_options', '') module_name, dummy, function_name = definition.rpartition('.') topology_dir = os.getcwd() # Make a copy of the input "jvmpetrel" jar. This jar acts as a generic # starting point for all Petrel topologies. source_jar_path = os.path.abspath(source_jar_path) dest_jar_path = os.path.abspath(dest_jar_path) if source_jar_path == dest_jar_path: raise ValueError("Error: Destination and source path are the same.") shutil.copy(source_jar_path, dest_jar_path) jar = zipfile.ZipFile(dest_jar_path, 'a', compression=zipfile.ZIP_DEFLATED) added_path_entry = False try: # Add the files listed in manifest.txt to the jar. with open(os.path.join(topology_dir, MANIFEST), 'r') as f: for fn in f.readlines(): # Ignore blank and comment lines. fn = fn.strip() if len(fn) and not fn.startswith('#'): add_item_to_jar(jar, os.path.expandvars(fn.strip())) # Add user and machine information to the jar. add_to_jar(jar, '__submitter__.yaml', ''' petrel.user: %s petrel.host: %s ''' % (getpass.getuser(),socket.gethostname())) # Also add the topology configuration to the jar. with open(config, 'r') as f: config_text = f.read() add_to_jar(jar, '__topology__.yaml', config_text) # Call module_name/function_name to populate a Thrift topology object. builder = TopologyBuilder() module_dir = os.path.abspath(topology_dir) if module_dir not in sys.path: sys.path[:0] = [ module_dir ] added_path_entry = True module = __import__(module_name) getattr(module, function_name)(builder) # Add the spout and bolt Python scripts to the jar. Create a # setup_<script>.sh for each Python script. # Add Python scripts and any other per-script resources. for k, v in chain(six.iteritems(builder._spouts), six.iteritems(builder._bolts)): add_file_to_jar(jar, topology_dir, v.script) # Create a bootstrap script. if venv is not None: # Allow overriding the execution command from the "petrel" # command line. This is handy if the server already has a # virtualenv set up with the necessary libraries. v.execution_command = os.path.join(venv, 'bin/python') # If a parallelism value was specified in the configuration YAML, # override any setting provided in the topology definition script. if k in parallelism: builder._commons[k].parallelism_hint = int(parallelism.pop(k)) v.execution_command, v.script = \ intercept(venv, v.execution_command, os.path.splitext(v.script)[0], jar, pip_options, logdir) if len(parallelism): raise ValueError( 'Parallelism settings error: There are no components named: %s' % ','.join(parallelism.keys())) # Build the Thrift topology object and serialize it to the .jar. Must do # this *after* the intercept step above since that step may modify the # topology definition. buf = io.BytesIO() builder.write(buf) add_to_jar(jar, 'topology.ser', buf.getvalue()) finally: jar.close() if added_path_entry: # Undo our sys.path change. sys.path[:] = sys.path[1:]
python
def build_jar(source_jar_path, dest_jar_path, config, venv=None, definition=None, logdir=None): """Build a StormTopology .jar which encapsulates the topology defined in topology_dir. Optionally override the module and function names. This feature supports the definition of multiple topologies in a single directory.""" if definition is None: definition = 'create.create' # Prepare data we'll use later for configuring parallelism. config_yaml = read_yaml(config) parallelism = dict((k.split('.')[-1], v) for k, v in six.iteritems(config_yaml) if k.startswith('petrel.parallelism')) pip_options = config_yaml.get('petrel.pip_options', '') module_name, dummy, function_name = definition.rpartition('.') topology_dir = os.getcwd() # Make a copy of the input "jvmpetrel" jar. This jar acts as a generic # starting point for all Petrel topologies. source_jar_path = os.path.abspath(source_jar_path) dest_jar_path = os.path.abspath(dest_jar_path) if source_jar_path == dest_jar_path: raise ValueError("Error: Destination and source path are the same.") shutil.copy(source_jar_path, dest_jar_path) jar = zipfile.ZipFile(dest_jar_path, 'a', compression=zipfile.ZIP_DEFLATED) added_path_entry = False try: # Add the files listed in manifest.txt to the jar. with open(os.path.join(topology_dir, MANIFEST), 'r') as f: for fn in f.readlines(): # Ignore blank and comment lines. fn = fn.strip() if len(fn) and not fn.startswith('#'): add_item_to_jar(jar, os.path.expandvars(fn.strip())) # Add user and machine information to the jar. add_to_jar(jar, '__submitter__.yaml', ''' petrel.user: %s petrel.host: %s ''' % (getpass.getuser(),socket.gethostname())) # Also add the topology configuration to the jar. with open(config, 'r') as f: config_text = f.read() add_to_jar(jar, '__topology__.yaml', config_text) # Call module_name/function_name to populate a Thrift topology object. builder = TopologyBuilder() module_dir = os.path.abspath(topology_dir) if module_dir not in sys.path: sys.path[:0] = [ module_dir ] added_path_entry = True module = __import__(module_name) getattr(module, function_name)(builder) # Add the spout and bolt Python scripts to the jar. Create a # setup_<script>.sh for each Python script. # Add Python scripts and any other per-script resources. for k, v in chain(six.iteritems(builder._spouts), six.iteritems(builder._bolts)): add_file_to_jar(jar, topology_dir, v.script) # Create a bootstrap script. if venv is not None: # Allow overriding the execution command from the "petrel" # command line. This is handy if the server already has a # virtualenv set up with the necessary libraries. v.execution_command = os.path.join(venv, 'bin/python') # If a parallelism value was specified in the configuration YAML, # override any setting provided in the topology definition script. if k in parallelism: builder._commons[k].parallelism_hint = int(parallelism.pop(k)) v.execution_command, v.script = \ intercept(venv, v.execution_command, os.path.splitext(v.script)[0], jar, pip_options, logdir) if len(parallelism): raise ValueError( 'Parallelism settings error: There are no components named: %s' % ','.join(parallelism.keys())) # Build the Thrift topology object and serialize it to the .jar. Must do # this *after* the intercept step above since that step may modify the # topology definition. buf = io.BytesIO() builder.write(buf) add_to_jar(jar, 'topology.ser', buf.getvalue()) finally: jar.close() if added_path_entry: # Undo our sys.path change. sys.path[:] = sys.path[1:]
[ "def", "build_jar", "(", "source_jar_path", ",", "dest_jar_path", ",", "config", ",", "venv", "=", "None", ",", "definition", "=", "None", ",", "logdir", "=", "None", ")", ":", "if", "definition", "is", "None", ":", "definition", "=", "'create.create'", "# Prepare data we'll use later for configuring parallelism.", "config_yaml", "=", "read_yaml", "(", "config", ")", "parallelism", "=", "dict", "(", "(", "k", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ",", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "config_yaml", ")", "if", "k", ".", "startswith", "(", "'petrel.parallelism'", ")", ")", "pip_options", "=", "config_yaml", ".", "get", "(", "'petrel.pip_options'", ",", "''", ")", "module_name", ",", "dummy", ",", "function_name", "=", "definition", ".", "rpartition", "(", "'.'", ")", "topology_dir", "=", "os", ".", "getcwd", "(", ")", "# Make a copy of the input \"jvmpetrel\" jar. This jar acts as a generic", "# starting point for all Petrel topologies.", "source_jar_path", "=", "os", ".", "path", ".", "abspath", "(", "source_jar_path", ")", "dest_jar_path", "=", "os", ".", "path", ".", "abspath", "(", "dest_jar_path", ")", "if", "source_jar_path", "==", "dest_jar_path", ":", "raise", "ValueError", "(", "\"Error: Destination and source path are the same.\"", ")", "shutil", ".", "copy", "(", "source_jar_path", ",", "dest_jar_path", ")", "jar", "=", "zipfile", ".", "ZipFile", "(", "dest_jar_path", ",", "'a'", ",", "compression", "=", "zipfile", ".", "ZIP_DEFLATED", ")", "added_path_entry", "=", "False", "try", ":", "# Add the files listed in manifest.txt to the jar.", "with", "open", "(", "os", ".", "path", ".", "join", "(", "topology_dir", ",", "MANIFEST", ")", ",", "'r'", ")", "as", "f", ":", "for", "fn", "in", "f", ".", "readlines", "(", ")", ":", "# Ignore blank and comment lines.", "fn", "=", "fn", ".", "strip", "(", ")", "if", "len", "(", "fn", ")", "and", "not", "fn", ".", "startswith", "(", "'#'", ")", ":", "add_item_to_jar", "(", "jar", ",", "os", ".", "path", ".", "expandvars", "(", "fn", ".", "strip", "(", ")", ")", ")", "# Add user and machine information to the jar.", "add_to_jar", "(", "jar", ",", "'__submitter__.yaml'", ",", "'''\npetrel.user: %s\npetrel.host: %s\n'''", "%", "(", "getpass", ".", "getuser", "(", ")", ",", "socket", ".", "gethostname", "(", ")", ")", ")", "# Also add the topology configuration to the jar.", "with", "open", "(", "config", ",", "'r'", ")", "as", "f", ":", "config_text", "=", "f", ".", "read", "(", ")", "add_to_jar", "(", "jar", ",", "'__topology__.yaml'", ",", "config_text", ")", "# Call module_name/function_name to populate a Thrift topology object.", "builder", "=", "TopologyBuilder", "(", ")", "module_dir", "=", "os", ".", "path", ".", "abspath", "(", "topology_dir", ")", "if", "module_dir", "not", "in", "sys", ".", "path", ":", "sys", ".", "path", "[", ":", "0", "]", "=", "[", "module_dir", "]", "added_path_entry", "=", "True", "module", "=", "__import__", "(", "module_name", ")", "getattr", "(", "module", ",", "function_name", ")", "(", "builder", ")", "# Add the spout and bolt Python scripts to the jar. Create a", "# setup_<script>.sh for each Python script.", "# Add Python scripts and any other per-script resources.", "for", "k", ",", "v", "in", "chain", "(", "six", ".", "iteritems", "(", "builder", ".", "_spouts", ")", ",", "six", ".", "iteritems", "(", "builder", ".", "_bolts", ")", ")", ":", "add_file_to_jar", "(", "jar", ",", "topology_dir", ",", "v", ".", "script", ")", "# Create a bootstrap script.", "if", "venv", "is", "not", "None", ":", "# Allow overriding the execution command from the \"petrel\"", "# command line. This is handy if the server already has a", "# virtualenv set up with the necessary libraries.", "v", ".", "execution_command", "=", "os", ".", "path", ".", "join", "(", "venv", ",", "'bin/python'", ")", "# If a parallelism value was specified in the configuration YAML,", "# override any setting provided in the topology definition script.", "if", "k", "in", "parallelism", ":", "builder", ".", "_commons", "[", "k", "]", ".", "parallelism_hint", "=", "int", "(", "parallelism", ".", "pop", "(", "k", ")", ")", "v", ".", "execution_command", ",", "v", ".", "script", "=", "intercept", "(", "venv", ",", "v", ".", "execution_command", ",", "os", ".", "path", ".", "splitext", "(", "v", ".", "script", ")", "[", "0", "]", ",", "jar", ",", "pip_options", ",", "logdir", ")", "if", "len", "(", "parallelism", ")", ":", "raise", "ValueError", "(", "'Parallelism settings error: There are no components named: %s'", "%", "','", ".", "join", "(", "parallelism", ".", "keys", "(", ")", ")", ")", "# Build the Thrift topology object and serialize it to the .jar. Must do", "# this *after* the intercept step above since that step may modify the", "# topology definition.", "buf", "=", "io", ".", "BytesIO", "(", ")", "builder", ".", "write", "(", "buf", ")", "add_to_jar", "(", "jar", ",", "'topology.ser'", ",", "buf", ".", "getvalue", "(", ")", ")", "finally", ":", "jar", ".", "close", "(", ")", "if", "added_path_entry", ":", "# Undo our sys.path change.", "sys", ".", "path", "[", ":", "]", "=", "sys", ".", "path", "[", "1", ":", "]" ]
Build a StormTopology .jar which encapsulates the topology defined in topology_dir. Optionally override the module and function names. This feature supports the definition of multiple topologies in a single directory.
[ "Build", "a", "StormTopology", ".", "jar", "which", "encapsulates", "the", "topology", "defined", "in", "topology_dir", ".", "Optionally", "override", "the", "module", "and", "function", "names", ".", "This", "feature", "supports", "the", "definition", "of", "multiple", "topologies", "in", "a", "single", "directory", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/package.py#L74-L172
AirSage/Petrel
petrel/petrel/storm.py
sendFailureMsgToParent
def sendFailureMsgToParent(msg): """This function is kind of a hack, but useful when a Python task encounters a fatal exception. "msg" should be a simple string like "E_SPOUTFAILED". This function sends "msg" as-is to the Storm worker, which tries to parse it as JSON. The hacky aspect is that we *deliberately* make it fail by sending it non-JSON data. This causes the Storm worker to throw an error and restart the Python task. This is cleaner than simply letting the task die without notifying Storm, because this way Storm restarts the task more quickly.""" assert isinstance(msg, six.string_types) print(msg, file=old_stdout) print('end', file=old_stdout) storm_log.error('Sent failure message ("%s") to Storm', msg)
python
def sendFailureMsgToParent(msg): """This function is kind of a hack, but useful when a Python task encounters a fatal exception. "msg" should be a simple string like "E_SPOUTFAILED". This function sends "msg" as-is to the Storm worker, which tries to parse it as JSON. The hacky aspect is that we *deliberately* make it fail by sending it non-JSON data. This causes the Storm worker to throw an error and restart the Python task. This is cleaner than simply letting the task die without notifying Storm, because this way Storm restarts the task more quickly.""" assert isinstance(msg, six.string_types) print(msg, file=old_stdout) print('end', file=old_stdout) storm_log.error('Sent failure message ("%s") to Storm', msg)
[ "def", "sendFailureMsgToParent", "(", "msg", ")", ":", "assert", "isinstance", "(", "msg", ",", "six", ".", "string_types", ")", "print", "(", "msg", ",", "file", "=", "old_stdout", ")", "print", "(", "'end'", ",", "file", "=", "old_stdout", ")", "storm_log", ".", "error", "(", "'Sent failure message (\"%s\") to Storm'", ",", "msg", ")" ]
This function is kind of a hack, but useful when a Python task encounters a fatal exception. "msg" should be a simple string like "E_SPOUTFAILED". This function sends "msg" as-is to the Storm worker, which tries to parse it as JSON. The hacky aspect is that we *deliberately* make it fail by sending it non-JSON data. This causes the Storm worker to throw an error and restart the Python task. This is cleaner than simply letting the task die without notifying Storm, because this way Storm restarts the task more quickly.
[ "This", "function", "is", "kind", "of", "a", "hack", "but", "useful", "when", "a", "Python", "task", "encounters", "a", "fatal", "exception", ".", "msg", "should", "be", "a", "simple", "string", "like", "E_SPOUTFAILED", ".", "This", "function", "sends", "msg", "as", "-", "is", "to", "the", "Storm", "worker", "which", "tries", "to", "parse", "it", "as", "JSON", ".", "The", "hacky", "aspect", "is", "that", "we", "*", "deliberately", "*", "make", "it", "fail", "by", "sending", "it", "non", "-", "JSON", "data", ".", "This", "causes", "the", "Storm", "worker", "to", "throw", "an", "error", "and", "restart", "the", "Python", "task", ".", "This", "is", "cleaner", "than", "simply", "letting", "the", "task", "die", "without", "notifying", "Storm", "because", "this", "way", "Storm", "restarts", "the", "task", "more", "quickly", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/storm.py#L101-L113
AirSage/Petrel
petrel/petrel/storm.py
emitMany
def emitMany(*args, **kwargs): """A more efficient way to emit a number of tuples at once.""" global MODE if MODE == Bolt: emitManyBolt(*args, **kwargs) elif MODE == Spout: emitManySpout(*args, **kwargs)
python
def emitMany(*args, **kwargs): """A more efficient way to emit a number of tuples at once.""" global MODE if MODE == Bolt: emitManyBolt(*args, **kwargs) elif MODE == Spout: emitManySpout(*args, **kwargs)
[ "def", "emitMany", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "global", "MODE", "if", "MODE", "==", "Bolt", ":", "emitManyBolt", "(", "*", "args", ",", "*", "*", "kwargs", ")", "elif", "MODE", "==", "Spout", ":", "emitManySpout", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
A more efficient way to emit a number of tuples at once.
[ "A", "more", "efficient", "way", "to", "emit", "a", "number", "of", "tuples", "at", "once", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/storm.py#L132-L138
AirSage/Petrel
petrel/petrel/rdebug.py
remote_debug
def remote_debug(sig,frame): """Handler to allow process to be remotely debugged.""" def _raiseEx(ex): """Raise specified exception in the remote process""" _raiseEx.ex = ex _raiseEx.ex = None try: # Provide some useful functions. locs = {'_raiseEx' : _raiseEx} locs.update(frame.f_locals) # Unless shadowed. globs = frame.f_globals pid = os.getpid() # Use pipe name based on pid pipe = NamedPipe(pipename(pid)) old_stdout, old_stderr = sys.stdout, sys.stderr txt = '' pipe.put("Interrupting process at following point:\n" + ''.join(traceback.format_stack(frame)) + ">>> ") try: while pipe.is_open() and _raiseEx.ex is None: line = pipe.get() if line is None: continue # EOF txt += line try: code = codeop.compile_command(txt) if code: sys.stdout = six.StringIO() sys.stderr = sys.stdout six.exec_(code, globs, locs) txt = '' pipe.put(sys.stdout.getvalue() + '>>> ') else: pipe.put('... ') except: txt='' # May be syntax err. sys.stdout = six.StringIO() sys.stderr = sys.stdout traceback.print_exc() pipe.put(sys.stdout.getvalue() + '>>> ') finally: sys.stdout = old_stdout # Restore redirected output. sys.stderr = old_stderr pipe.close() except Exception: # Don't allow debug exceptions to propogate to real program. traceback.print_exc() if _raiseEx.ex is not None: raise _raiseEx.ex
python
def remote_debug(sig,frame): """Handler to allow process to be remotely debugged.""" def _raiseEx(ex): """Raise specified exception in the remote process""" _raiseEx.ex = ex _raiseEx.ex = None try: # Provide some useful functions. locs = {'_raiseEx' : _raiseEx} locs.update(frame.f_locals) # Unless shadowed. globs = frame.f_globals pid = os.getpid() # Use pipe name based on pid pipe = NamedPipe(pipename(pid)) old_stdout, old_stderr = sys.stdout, sys.stderr txt = '' pipe.put("Interrupting process at following point:\n" + ''.join(traceback.format_stack(frame)) + ">>> ") try: while pipe.is_open() and _raiseEx.ex is None: line = pipe.get() if line is None: continue # EOF txt += line try: code = codeop.compile_command(txt) if code: sys.stdout = six.StringIO() sys.stderr = sys.stdout six.exec_(code, globs, locs) txt = '' pipe.put(sys.stdout.getvalue() + '>>> ') else: pipe.put('... ') except: txt='' # May be syntax err. sys.stdout = six.StringIO() sys.stderr = sys.stdout traceback.print_exc() pipe.put(sys.stdout.getvalue() + '>>> ') finally: sys.stdout = old_stdout # Restore redirected output. sys.stderr = old_stderr pipe.close() except Exception: # Don't allow debug exceptions to propogate to real program. traceback.print_exc() if _raiseEx.ex is not None: raise _raiseEx.ex
[ "def", "remote_debug", "(", "sig", ",", "frame", ")", ":", "def", "_raiseEx", "(", "ex", ")", ":", "\"\"\"Raise specified exception in the remote process\"\"\"", "_raiseEx", ".", "ex", "=", "ex", "_raiseEx", ".", "ex", "=", "None", "try", ":", "# Provide some useful functions.", "locs", "=", "{", "'_raiseEx'", ":", "_raiseEx", "}", "locs", ".", "update", "(", "frame", ".", "f_locals", ")", "# Unless shadowed.", "globs", "=", "frame", ".", "f_globals", "pid", "=", "os", ".", "getpid", "(", ")", "# Use pipe name based on pid", "pipe", "=", "NamedPipe", "(", "pipename", "(", "pid", ")", ")", "old_stdout", ",", "old_stderr", "=", "sys", ".", "stdout", ",", "sys", ".", "stderr", "txt", "=", "''", "pipe", ".", "put", "(", "\"Interrupting process at following point:\\n\"", "+", "''", ".", "join", "(", "traceback", ".", "format_stack", "(", "frame", ")", ")", "+", "\">>> \"", ")", "try", ":", "while", "pipe", ".", "is_open", "(", ")", "and", "_raiseEx", ".", "ex", "is", "None", ":", "line", "=", "pipe", ".", "get", "(", ")", "if", "line", "is", "None", ":", "continue", "# EOF", "txt", "+=", "line", "try", ":", "code", "=", "codeop", ".", "compile_command", "(", "txt", ")", "if", "code", ":", "sys", ".", "stdout", "=", "six", ".", "StringIO", "(", ")", "sys", ".", "stderr", "=", "sys", ".", "stdout", "six", ".", "exec_", "(", "code", ",", "globs", ",", "locs", ")", "txt", "=", "''", "pipe", ".", "put", "(", "sys", ".", "stdout", ".", "getvalue", "(", ")", "+", "'>>> '", ")", "else", ":", "pipe", ".", "put", "(", "'... '", ")", "except", ":", "txt", "=", "''", "# May be syntax err.", "sys", ".", "stdout", "=", "six", ".", "StringIO", "(", ")", "sys", ".", "stderr", "=", "sys", ".", "stdout", "traceback", ".", "print_exc", "(", ")", "pipe", ".", "put", "(", "sys", ".", "stdout", ".", "getvalue", "(", ")", "+", "'>>> '", ")", "finally", ":", "sys", ".", "stdout", "=", "old_stdout", "# Restore redirected output.", "sys", ".", "stderr", "=", "old_stderr", "pipe", ".", "close", "(", ")", "except", "Exception", ":", "# Don't allow debug exceptions to propogate to real program.", "traceback", ".", "print_exc", "(", ")", "if", "_raiseEx", ".", "ex", "is", "not", "None", ":", "raise", "_raiseEx", ".", "ex" ]
Handler to allow process to be remotely debugged.
[ "Handler", "to", "allow", "process", "to", "be", "remotely", "debugged", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/rdebug.py#L72-L122
AirSage/Petrel
petrel/petrel/rdebug.py
debug_process
def debug_process(pid): """Interrupt a running process and debug it.""" os.kill(pid, signal.SIGUSR1) # Signal process. pipe = NamedPipe(pipename(pid), 1) try: while pipe.is_open(): txt=raw_input(pipe.get()) + '\n' pipe.put(txt) except EOFError: pass # Exit. pipe.close()
python
def debug_process(pid): """Interrupt a running process and debug it.""" os.kill(pid, signal.SIGUSR1) # Signal process. pipe = NamedPipe(pipename(pid), 1) try: while pipe.is_open(): txt=raw_input(pipe.get()) + '\n' pipe.put(txt) except EOFError: pass # Exit. pipe.close()
[ "def", "debug_process", "(", "pid", ")", ":", "os", ".", "kill", "(", "pid", ",", "signal", ".", "SIGUSR1", ")", "# Signal process.", "pipe", "=", "NamedPipe", "(", "pipename", "(", "pid", ")", ",", "1", ")", "try", ":", "while", "pipe", ".", "is_open", "(", ")", ":", "txt", "=", "raw_input", "(", "pipe", ".", "get", "(", ")", ")", "+", "'\\n'", "pipe", ".", "put", "(", "txt", ")", "except", "EOFError", ":", "pass", "# Exit.", "pipe", ".", "close", "(", ")" ]
Interrupt a running process and debug it.
[ "Interrupt", "a", "running", "process", "and", "debug", "it", "." ]
train
https://github.com/AirSage/Petrel/blob/c4be9b7da5916dcc028ddb88850e7703203eeb79/petrel/petrel/rdebug.py#L125-L135
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._encode_utf8
def _encode_utf8(self, **kwargs): """ UTF8 encodes all of the NVP values. """ if is_py3: # This is only valid for Python 2. In Python 3, unicode is # everywhere (yay). return kwargs unencoded_pairs = kwargs for i in unencoded_pairs.keys(): #noinspection PyUnresolvedReferences if isinstance(unencoded_pairs[i], types.UnicodeType): unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8') return unencoded_pairs
python
def _encode_utf8(self, **kwargs): """ UTF8 encodes all of the NVP values. """ if is_py3: # This is only valid for Python 2. In Python 3, unicode is # everywhere (yay). return kwargs unencoded_pairs = kwargs for i in unencoded_pairs.keys(): #noinspection PyUnresolvedReferences if isinstance(unencoded_pairs[i], types.UnicodeType): unencoded_pairs[i] = unencoded_pairs[i].encode('utf-8') return unencoded_pairs
[ "def", "_encode_utf8", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "is_py3", ":", "# This is only valid for Python 2. In Python 3, unicode is", "# everywhere (yay).", "return", "kwargs", "unencoded_pairs", "=", "kwargs", "for", "i", "in", "unencoded_pairs", ".", "keys", "(", ")", ":", "#noinspection PyUnresolvedReferences", "if", "isinstance", "(", "unencoded_pairs", "[", "i", "]", ",", "types", ".", "UnicodeType", ")", ":", "unencoded_pairs", "[", "i", "]", "=", "unencoded_pairs", "[", "i", "]", ".", "encode", "(", "'utf-8'", ")", "return", "unencoded_pairs" ]
UTF8 encodes all of the NVP values.
[ "UTF8", "encodes", "all", "of", "the", "NVP", "values", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L58-L72
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._check_required
def _check_required(self, requires, **kwargs): """ Checks kwargs for the values specified in 'requires', which is a tuple of strings. These strings are the NVP names of the required values. """ for req in requires: # PayPal api is never mixed-case. if req.lower() not in kwargs and req.upper() not in kwargs: raise PayPalError('missing required : %s' % req)
python
def _check_required(self, requires, **kwargs): """ Checks kwargs for the values specified in 'requires', which is a tuple of strings. These strings are the NVP names of the required values. """ for req in requires: # PayPal api is never mixed-case. if req.lower() not in kwargs and req.upper() not in kwargs: raise PayPalError('missing required : %s' % req)
[ "def", "_check_required", "(", "self", ",", "requires", ",", "*", "*", "kwargs", ")", ":", "for", "req", "in", "requires", ":", "# PayPal api is never mixed-case.", "if", "req", ".", "lower", "(", ")", "not", "in", "kwargs", "and", "req", ".", "upper", "(", ")", "not", "in", "kwargs", ":", "raise", "PayPalError", "(", "'missing required : %s'", "%", "req", ")" ]
Checks kwargs for the values specified in 'requires', which is a tuple of strings. These strings are the NVP names of the required values.
[ "Checks", "kwargs", "for", "the", "values", "specified", "in", "requires", "which", "is", "a", "tuple", "of", "strings", ".", "These", "strings", "are", "the", "NVP", "names", "of", "the", "required", "values", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L74-L82
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._call
def _call(self, method, **kwargs): """ Wrapper method for executing all API commands over HTTP. This method is further used to implement wrapper methods listed here: https://www.x.com/docs/DOC-1374 ``method`` must be a supported NVP method listed at the above address. ``kwargs`` the actual call parameters """ post_params = self._get_call_params(method, **kwargs) payload = post_params['data'] api_endpoint = post_params['url'] # This shows all of the key/val pairs we're sending to PayPal. if logger.isEnabledFor(logging.DEBUG): logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload)) http_response = requests.post(**post_params) response = PayPalResponse(http_response.text, self.config) logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint) if not response.success: raise PayPalAPIResponseError(response) return response
python
def _call(self, method, **kwargs): """ Wrapper method for executing all API commands over HTTP. This method is further used to implement wrapper methods listed here: https://www.x.com/docs/DOC-1374 ``method`` must be a supported NVP method listed at the above address. ``kwargs`` the actual call parameters """ post_params = self._get_call_params(method, **kwargs) payload = post_params['data'] api_endpoint = post_params['url'] # This shows all of the key/val pairs we're sending to PayPal. if logger.isEnabledFor(logging.DEBUG): logger.debug('PayPal NVP Query Key/Vals:\n%s' % pformat(payload)) http_response = requests.post(**post_params) response = PayPalResponse(http_response.text, self.config) logger.debug('PayPal NVP API Endpoint: %s' % api_endpoint) if not response.success: raise PayPalAPIResponseError(response) return response
[ "def", "_call", "(", "self", ",", "method", ",", "*", "*", "kwargs", ")", ":", "post_params", "=", "self", ".", "_get_call_params", "(", "method", ",", "*", "*", "kwargs", ")", "payload", "=", "post_params", "[", "'data'", "]", "api_endpoint", "=", "post_params", "[", "'url'", "]", "# This shows all of the key/val pairs we're sending to PayPal.", "if", "logger", ".", "isEnabledFor", "(", "logging", ".", "DEBUG", ")", ":", "logger", ".", "debug", "(", "'PayPal NVP Query Key/Vals:\\n%s'", "%", "pformat", "(", "payload", ")", ")", "http_response", "=", "requests", ".", "post", "(", "*", "*", "post_params", ")", "response", "=", "PayPalResponse", "(", "http_response", ".", "text", ",", "self", ".", "config", ")", "logger", ".", "debug", "(", "'PayPal NVP API Endpoint: %s'", "%", "api_endpoint", ")", "if", "not", "response", ".", "success", ":", "raise", "PayPalAPIResponseError", "(", "response", ")", "return", "response" ]
Wrapper method for executing all API commands over HTTP. This method is further used to implement wrapper methods listed here: https://www.x.com/docs/DOC-1374 ``method`` must be a supported NVP method listed at the above address. ``kwargs`` the actual call parameters
[ "Wrapper", "method", "for", "executing", "all", "API", "commands", "over", "HTTP", ".", "This", "method", "is", "further", "used", "to", "implement", "wrapper", "methods", "listed", "here", ":" ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L95-L120
gtaylor/paypal-python
paypal/interface.py
PayPalInterface._get_call_params
def _get_call_params(self, method, **kwargs): """ Returns the prepared call parameters. Mind, these will be keyword arguments to ``requests.post``. ``method`` the NVP method ``kwargs`` the actual call parameters """ payload = {'METHOD': method, 'VERSION': self.config.API_VERSION} certificate = None if self.config.API_AUTHENTICATION_MODE == "3TOKEN": payload['USER'] = self.config.API_USERNAME payload['PWD'] = self.config.API_PASSWORD payload['SIGNATURE'] = self.config.API_SIGNATURE elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE": payload['USER'] = self.config.API_USERNAME payload['PWD'] = self.config.API_PASSWORD certificate = (self.config.API_CERTIFICATE_FILENAME, self.config.API_KEY_FILENAME) elif self.config.API_AUTHENTICATION_MODE == "UNIPAY": payload['SUBJECT'] = self.config.UNIPAY_SUBJECT none_configs = [config for config, value in payload.items() if value is None] if none_configs: raise PayPalConfigError( "Config(s) %s cannot be None. Please, check this " "interface's config." % none_configs) # all keys in the payload must be uppercase for key, value in kwargs.items(): payload[key.upper()] = value return {'data': payload, 'cert': certificate, 'url': self.config.API_ENDPOINT, 'timeout': self.config.HTTP_TIMEOUT, 'verify': self.config.API_CA_CERTS}
python
def _get_call_params(self, method, **kwargs): """ Returns the prepared call parameters. Mind, these will be keyword arguments to ``requests.post``. ``method`` the NVP method ``kwargs`` the actual call parameters """ payload = {'METHOD': method, 'VERSION': self.config.API_VERSION} certificate = None if self.config.API_AUTHENTICATION_MODE == "3TOKEN": payload['USER'] = self.config.API_USERNAME payload['PWD'] = self.config.API_PASSWORD payload['SIGNATURE'] = self.config.API_SIGNATURE elif self.config.API_AUTHENTICATION_MODE == "CERTIFICATE": payload['USER'] = self.config.API_USERNAME payload['PWD'] = self.config.API_PASSWORD certificate = (self.config.API_CERTIFICATE_FILENAME, self.config.API_KEY_FILENAME) elif self.config.API_AUTHENTICATION_MODE == "UNIPAY": payload['SUBJECT'] = self.config.UNIPAY_SUBJECT none_configs = [config for config, value in payload.items() if value is None] if none_configs: raise PayPalConfigError( "Config(s) %s cannot be None. Please, check this " "interface's config." % none_configs) # all keys in the payload must be uppercase for key, value in kwargs.items(): payload[key.upper()] = value return {'data': payload, 'cert': certificate, 'url': self.config.API_ENDPOINT, 'timeout': self.config.HTTP_TIMEOUT, 'verify': self.config.API_CA_CERTS}
[ "def", "_get_call_params", "(", "self", ",", "method", ",", "*", "*", "kwargs", ")", ":", "payload", "=", "{", "'METHOD'", ":", "method", ",", "'VERSION'", ":", "self", ".", "config", ".", "API_VERSION", "}", "certificate", "=", "None", "if", "self", ".", "config", ".", "API_AUTHENTICATION_MODE", "==", "\"3TOKEN\"", ":", "payload", "[", "'USER'", "]", "=", "self", ".", "config", ".", "API_USERNAME", "payload", "[", "'PWD'", "]", "=", "self", ".", "config", ".", "API_PASSWORD", "payload", "[", "'SIGNATURE'", "]", "=", "self", ".", "config", ".", "API_SIGNATURE", "elif", "self", ".", "config", ".", "API_AUTHENTICATION_MODE", "==", "\"CERTIFICATE\"", ":", "payload", "[", "'USER'", "]", "=", "self", ".", "config", ".", "API_USERNAME", "payload", "[", "'PWD'", "]", "=", "self", ".", "config", ".", "API_PASSWORD", "certificate", "=", "(", "self", ".", "config", ".", "API_CERTIFICATE_FILENAME", ",", "self", ".", "config", ".", "API_KEY_FILENAME", ")", "elif", "self", ".", "config", ".", "API_AUTHENTICATION_MODE", "==", "\"UNIPAY\"", ":", "payload", "[", "'SUBJECT'", "]", "=", "self", ".", "config", ".", "UNIPAY_SUBJECT", "none_configs", "=", "[", "config", "for", "config", ",", "value", "in", "payload", ".", "items", "(", ")", "if", "value", "is", "None", "]", "if", "none_configs", ":", "raise", "PayPalConfigError", "(", "\"Config(s) %s cannot be None. Please, check this \"", "\"interface's config.\"", "%", "none_configs", ")", "# all keys in the payload must be uppercase", "for", "key", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "payload", "[", "key", ".", "upper", "(", ")", "]", "=", "value", "return", "{", "'data'", ":", "payload", ",", "'cert'", ":", "certificate", ",", "'url'", ":", "self", ".", "config", ".", "API_ENDPOINT", ",", "'timeout'", ":", "self", ".", "config", ".", "HTTP_TIMEOUT", ",", "'verify'", ":", "self", ".", "config", ".", "API_CA_CERTS", "}" ]
Returns the prepared call parameters. Mind, these will be keyword arguments to ``requests.post``. ``method`` the NVP method ``kwargs`` the actual call parameters
[ "Returns", "the", "prepared", "call", "parameters", ".", "Mind", "these", "will", "be", "keyword", "arguments", "to", "requests", ".", "post", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L122-L161
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.address_verify
def address_verify(self, email, street, zip): """Shortcut for the AddressVerify method. ``email``:: Email address of a PayPal member to verify. Maximum string length: 255 single-byte characters Input mask: ?@?.?? ``street``:: First line of the billing or shipping postal address to verify. To pass verification, the value of Street must match the first three single-byte characters of a postal address on file for the PayPal member. Maximum string length: 35 single-byte characters. Alphanumeric plus - , . ‘ # \ Whitespace and case of input value are ignored. ``zip``:: Postal code to verify. To pass verification, the value of Zip mustmatch the first five single-byte characters of the postal code of the verified postal address for the verified PayPal member. Maximumstring length: 16 single-byte characters. Whitespace and case of input value are ignored. """ args = self._sanitize_locals(locals()) return self._call('AddressVerify', **args)
python
def address_verify(self, email, street, zip): """Shortcut for the AddressVerify method. ``email``:: Email address of a PayPal member to verify. Maximum string length: 255 single-byte characters Input mask: ?@?.?? ``street``:: First line of the billing or shipping postal address to verify. To pass verification, the value of Street must match the first three single-byte characters of a postal address on file for the PayPal member. Maximum string length: 35 single-byte characters. Alphanumeric plus - , . ‘ # \ Whitespace and case of input value are ignored. ``zip``:: Postal code to verify. To pass verification, the value of Zip mustmatch the first five single-byte characters of the postal code of the verified postal address for the verified PayPal member. Maximumstring length: 16 single-byte characters. Whitespace and case of input value are ignored. """ args = self._sanitize_locals(locals()) return self._call('AddressVerify', **args)
[ "def", "address_verify", "(", "self", ",", "email", ",", "street", ",", "zip", ")", ":", "args", "=", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", "return", "self", ".", "_call", "(", "'AddressVerify'", ",", "*", "*", "args", ")" ]
Shortcut for the AddressVerify method. ``email``:: Email address of a PayPal member to verify. Maximum string length: 255 single-byte characters Input mask: ?@?.?? ``street``:: First line of the billing or shipping postal address to verify. To pass verification, the value of Street must match the first three single-byte characters of a postal address on file for the PayPal member. Maximum string length: 35 single-byte characters. Alphanumeric plus - , . ‘ # \ Whitespace and case of input value are ignored. ``zip``:: Postal code to verify. To pass verification, the value of Zip mustmatch the first five single-byte characters of the postal code of the verified postal address for the verified PayPal member. Maximumstring length: 16 single-byte characters. Whitespace and case of input value are ignored.
[ "Shortcut", "for", "the", "AddressVerify", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L163-L190
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.do_authorization
def do_authorization(self, transactionid, amt): """Shortcut for the DoAuthorization method. Use the TRANSACTIONID from DoExpressCheckoutPayment for the ``transactionid``. The latest version of the API does not support the creation of an Order from `DoDirectPayment`. The `amt` should be the same as passed to `DoExpressCheckoutPayment`. Flow for a payment involving a `DoAuthorization` call:: 1. One or many calls to `SetExpressCheckout` with pertinent order details, returns `TOKEN` 1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to Order, `AMT` set to the amount of the transaction, returns `TRANSACTIONID` 1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the amount of the transaction. 1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID` returned by `DoAuthorization`) """ args = self._sanitize_locals(locals()) return self._call('DoAuthorization', **args)
python
def do_authorization(self, transactionid, amt): """Shortcut for the DoAuthorization method. Use the TRANSACTIONID from DoExpressCheckoutPayment for the ``transactionid``. The latest version of the API does not support the creation of an Order from `DoDirectPayment`. The `amt` should be the same as passed to `DoExpressCheckoutPayment`. Flow for a payment involving a `DoAuthorization` call:: 1. One or many calls to `SetExpressCheckout` with pertinent order details, returns `TOKEN` 1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to Order, `AMT` set to the amount of the transaction, returns `TRANSACTIONID` 1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the amount of the transaction. 1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID` returned by `DoAuthorization`) """ args = self._sanitize_locals(locals()) return self._call('DoAuthorization', **args)
[ "def", "do_authorization", "(", "self", ",", "transactionid", ",", "amt", ")", ":", "args", "=", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", "return", "self", ".", "_call", "(", "'DoAuthorization'", ",", "*", "*", "args", ")" ]
Shortcut for the DoAuthorization method. Use the TRANSACTIONID from DoExpressCheckoutPayment for the ``transactionid``. The latest version of the API does not support the creation of an Order from `DoDirectPayment`. The `amt` should be the same as passed to `DoExpressCheckoutPayment`. Flow for a payment involving a `DoAuthorization` call:: 1. One or many calls to `SetExpressCheckout` with pertinent order details, returns `TOKEN` 1. `DoExpressCheckoutPayment` with `TOKEN`, `PAYMENTACTION` set to Order, `AMT` set to the amount of the transaction, returns `TRANSACTIONID` 1. `DoAuthorization` with `TRANSACTIONID` and `AMT` set to the amount of the transaction. 1. `DoCapture` with the `AUTHORIZATIONID` (the `TRANSACTIONID` returned by `DoAuthorization`)
[ "Shortcut", "for", "the", "DoAuthorization", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L228-L251
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.do_capture
def do_capture(self, authorizationid, amt, completetype='Complete', **kwargs): """Shortcut for the DoCapture method. Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or DoExpressCheckoutPayment for the ``authorizationid``. The `amt` should be the same as the authorized transaction. """ kwargs.update(self._sanitize_locals(locals())) return self._call('DoCapture', **kwargs)
python
def do_capture(self, authorizationid, amt, completetype='Complete', **kwargs): """Shortcut for the DoCapture method. Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or DoExpressCheckoutPayment for the ``authorizationid``. The `amt` should be the same as the authorized transaction. """ kwargs.update(self._sanitize_locals(locals())) return self._call('DoCapture', **kwargs)
[ "def", "do_capture", "(", "self", ",", "authorizationid", ",", "amt", ",", "completetype", "=", "'Complete'", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", ")", "return", "self", ".", "_call", "(", "'DoCapture'", ",", "*", "*", "kwargs", ")" ]
Shortcut for the DoCapture method. Use the TRANSACTIONID from DoAuthorization, DoDirectPayment or DoExpressCheckoutPayment for the ``authorizationid``. The `amt` should be the same as the authorized transaction.
[ "Shortcut", "for", "the", "DoCapture", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L253-L263
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.do_direct_payment
def do_direct_payment(self, paymentaction="Sale", **kwargs): """Shortcut for the DoDirectPayment method. ``paymentaction`` could be 'Authorization' or 'Sale' To issue a Sale immediately:: charge = { 'amt': '10.00', 'creditcardtype': 'Visa', 'acct': '4812177017895760', 'expdate': '012010', 'cvv2': '962', 'firstname': 'John', 'lastname': 'Doe', 'street': '1 Main St', 'city': 'San Jose', 'state': 'CA', 'zip': '95131', 'countrycode': 'US', 'currencycode': 'USD', } direct_payment("Sale", **charge) Or, since "Sale" is the default: direct_payment(**charge) To issue an Authorization, simply pass "Authorization" instead of "Sale". You may also explicitly set ``paymentaction`` as a keyword argument: ... direct_payment(paymentaction="Sale", **charge) """ kwargs.update(self._sanitize_locals(locals())) return self._call('DoDirectPayment', **kwargs)
python
def do_direct_payment(self, paymentaction="Sale", **kwargs): """Shortcut for the DoDirectPayment method. ``paymentaction`` could be 'Authorization' or 'Sale' To issue a Sale immediately:: charge = { 'amt': '10.00', 'creditcardtype': 'Visa', 'acct': '4812177017895760', 'expdate': '012010', 'cvv2': '962', 'firstname': 'John', 'lastname': 'Doe', 'street': '1 Main St', 'city': 'San Jose', 'state': 'CA', 'zip': '95131', 'countrycode': 'US', 'currencycode': 'USD', } direct_payment("Sale", **charge) Or, since "Sale" is the default: direct_payment(**charge) To issue an Authorization, simply pass "Authorization" instead of "Sale". You may also explicitly set ``paymentaction`` as a keyword argument: ... direct_payment(paymentaction="Sale", **charge) """ kwargs.update(self._sanitize_locals(locals())) return self._call('DoDirectPayment', **kwargs)
[ "def", "do_direct_payment", "(", "self", ",", "paymentaction", "=", "\"Sale\"", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", ")", "return", "self", ".", "_call", "(", "'DoDirectPayment'", ",", "*", "*", "kwargs", ")" ]
Shortcut for the DoDirectPayment method. ``paymentaction`` could be 'Authorization' or 'Sale' To issue a Sale immediately:: charge = { 'amt': '10.00', 'creditcardtype': 'Visa', 'acct': '4812177017895760', 'expdate': '012010', 'cvv2': '962', 'firstname': 'John', 'lastname': 'Doe', 'street': '1 Main St', 'city': 'San Jose', 'state': 'CA', 'zip': '95131', 'countrycode': 'US', 'currencycode': 'USD', } direct_payment("Sale", **charge) Or, since "Sale" is the default: direct_payment(**charge) To issue an Authorization, simply pass "Authorization" instead of "Sale". You may also explicitly set ``paymentaction`` as a keyword argument: ... direct_payment(paymentaction="Sale", **charge)
[ "Shortcut", "for", "the", "DoDirectPayment", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L265-L302
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.transaction_search
def transaction_search(self, **kwargs): """Shortcut for the TransactionSearch method. Returns a PayPalResponseList object, which merges the L_ syntax list to a list of dictionaries with properly named keys. Note that the API will limit returned transactions to 100. Required Kwargs --------------- * STARTDATE Optional Kwargs --------------- STATUS = one of ['Pending','Processing','Success','Denied','Reversed'] """ plain = self._call('TransactionSearch', **kwargs) return PayPalResponseList(plain.raw, self.config)
python
def transaction_search(self, **kwargs): """Shortcut for the TransactionSearch method. Returns a PayPalResponseList object, which merges the L_ syntax list to a list of dictionaries with properly named keys. Note that the API will limit returned transactions to 100. Required Kwargs --------------- * STARTDATE Optional Kwargs --------------- STATUS = one of ['Pending','Processing','Success','Denied','Reversed'] """ plain = self._call('TransactionSearch', **kwargs) return PayPalResponseList(plain.raw, self.config)
[ "def", "transaction_search", "(", "self", ",", "*", "*", "kwargs", ")", ":", "plain", "=", "self", ".", "_call", "(", "'TransactionSearch'", ",", "*", "*", "kwargs", ")", "return", "PayPalResponseList", "(", "plain", ".", "raw", ",", "self", ".", "config", ")" ]
Shortcut for the TransactionSearch method. Returns a PayPalResponseList object, which merges the L_ syntax list to a list of dictionaries with properly named keys. Note that the API will limit returned transactions to 100. Required Kwargs --------------- * STARTDATE Optional Kwargs --------------- STATUS = one of ['Pending','Processing','Success','Denied','Reversed']
[ "Shortcut", "for", "the", "TransactionSearch", "method", ".", "Returns", "a", "PayPalResponseList", "object", "which", "merges", "the", "L_", "syntax", "list", "to", "a", "list", "of", "dictionaries", "with", "properly", "named", "keys", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L338-L355
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.refund_transaction
def refund_transaction(self, transactionid=None, payerid=None, **kwargs): """Shortcut for RefundTransaction method. Note new API supports passing a PayerID instead of a transaction id, exactly one must be provided. Optional: INVOICEID REFUNDTYPE AMT CURRENCYCODE NOTE RETRYUNTIL REFUNDSOURCE MERCHANTSTOREDETAILS REFUNDADVICE REFUNDITEMDETAILS MSGSUBID MERCHANSTOREDETAILS has two fields: STOREID TERMINALID """ # This line seems like a complete waste of time... kwargs should not # be populated if (transactionid is None) and (payerid is None): raise PayPalError( 'RefundTransaction requires either a transactionid or ' 'a payerid') if (transactionid is not None) and (payerid is not None): raise PayPalError( 'RefundTransaction requires only one of transactionid %s ' 'and payerid %s' % (transactionid, payerid)) if transactionid is not None: kwargs['TRANSACTIONID'] = transactionid else: kwargs['PAYERID'] = payerid return self._call('RefundTransaction', **kwargs)
python
def refund_transaction(self, transactionid=None, payerid=None, **kwargs): """Shortcut for RefundTransaction method. Note new API supports passing a PayerID instead of a transaction id, exactly one must be provided. Optional: INVOICEID REFUNDTYPE AMT CURRENCYCODE NOTE RETRYUNTIL REFUNDSOURCE MERCHANTSTOREDETAILS REFUNDADVICE REFUNDITEMDETAILS MSGSUBID MERCHANSTOREDETAILS has two fields: STOREID TERMINALID """ # This line seems like a complete waste of time... kwargs should not # be populated if (transactionid is None) and (payerid is None): raise PayPalError( 'RefundTransaction requires either a transactionid or ' 'a payerid') if (transactionid is not None) and (payerid is not None): raise PayPalError( 'RefundTransaction requires only one of transactionid %s ' 'and payerid %s' % (transactionid, payerid)) if transactionid is not None: kwargs['TRANSACTIONID'] = transactionid else: kwargs['PAYERID'] = payerid return self._call('RefundTransaction', **kwargs)
[ "def", "refund_transaction", "(", "self", ",", "transactionid", "=", "None", ",", "payerid", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# This line seems like a complete waste of time... kwargs should not", "# be populated", "if", "(", "transactionid", "is", "None", ")", "and", "(", "payerid", "is", "None", ")", ":", "raise", "PayPalError", "(", "'RefundTransaction requires either a transactionid or '", "'a payerid'", ")", "if", "(", "transactionid", "is", "not", "None", ")", "and", "(", "payerid", "is", "not", "None", ")", ":", "raise", "PayPalError", "(", "'RefundTransaction requires only one of transactionid %s '", "'and payerid %s'", "%", "(", "transactionid", ",", "payerid", ")", ")", "if", "transactionid", "is", "not", "None", ":", "kwargs", "[", "'TRANSACTIONID'", "]", "=", "transactionid", "else", ":", "kwargs", "[", "'PAYERID'", "]", "=", "payerid", "return", "self", ".", "_call", "(", "'RefundTransaction'", ",", "*", "*", "kwargs", ")" ]
Shortcut for RefundTransaction method. Note new API supports passing a PayerID instead of a transaction id, exactly one must be provided. Optional: INVOICEID REFUNDTYPE AMT CURRENCYCODE NOTE RETRYUNTIL REFUNDSOURCE MERCHANTSTOREDETAILS REFUNDADVICE REFUNDITEMDETAILS MSGSUBID MERCHANSTOREDETAILS has two fields: STOREID TERMINALID
[ "Shortcut", "for", "RefundTransaction", "method", ".", "Note", "new", "API", "supports", "passing", "a", "PayerID", "instead", "of", "a", "transaction", "id", "exactly", "one", "must", "be", "provided", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L375-L412
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.generate_express_checkout_redirect_url
def generate_express_checkout_redirect_url(self, token, useraction=None): """Returns the URL to redirect the user to for the Express checkout. Express Checkouts must be verified by the customer by redirecting them to the PayPal website. Use the token returned in the response from :meth:`set_express_checkout` with this function to figure out where to redirect the user to. The button text on the PayPal page can be controlled via `useraction`. The documented possible values are `commit` and `continue`. However, any other value will only result in a warning. :param str token: The unique token identifying this transaction. :param str useraction: Control the button text on the PayPal page. :rtype: str :returns: The URL to redirect the user to for approval. """ url_vars = (self.config.PAYPAL_URL_BASE, token) url = "%s?cmd=_express-checkout&token=%s" % url_vars if useraction: if not useraction.lower() in ('commit', 'continue'): warnings.warn('useraction=%s is not documented' % useraction, RuntimeWarning) url += '&useraction=%s' % useraction return url
python
def generate_express_checkout_redirect_url(self, token, useraction=None): """Returns the URL to redirect the user to for the Express checkout. Express Checkouts must be verified by the customer by redirecting them to the PayPal website. Use the token returned in the response from :meth:`set_express_checkout` with this function to figure out where to redirect the user to. The button text on the PayPal page can be controlled via `useraction`. The documented possible values are `commit` and `continue`. However, any other value will only result in a warning. :param str token: The unique token identifying this transaction. :param str useraction: Control the button text on the PayPal page. :rtype: str :returns: The URL to redirect the user to for approval. """ url_vars = (self.config.PAYPAL_URL_BASE, token) url = "%s?cmd=_express-checkout&token=%s" % url_vars if useraction: if not useraction.lower() in ('commit', 'continue'): warnings.warn('useraction=%s is not documented' % useraction, RuntimeWarning) url += '&useraction=%s' % useraction return url
[ "def", "generate_express_checkout_redirect_url", "(", "self", ",", "token", ",", "useraction", "=", "None", ")", ":", "url_vars", "=", "(", "self", ".", "config", ".", "PAYPAL_URL_BASE", ",", "token", ")", "url", "=", "\"%s?cmd=_express-checkout&token=%s\"", "%", "url_vars", "if", "useraction", ":", "if", "not", "useraction", ".", "lower", "(", ")", "in", "(", "'commit'", ",", "'continue'", ")", ":", "warnings", ".", "warn", "(", "'useraction=%s is not documented'", "%", "useraction", ",", "RuntimeWarning", ")", "url", "+=", "'&useraction=%s'", "%", "useraction", "return", "url" ]
Returns the URL to redirect the user to for the Express checkout. Express Checkouts must be verified by the customer by redirecting them to the PayPal website. Use the token returned in the response from :meth:`set_express_checkout` with this function to figure out where to redirect the user to. The button text on the PayPal page can be controlled via `useraction`. The documented possible values are `commit` and `continue`. However, any other value will only result in a warning. :param str token: The unique token identifying this transaction. :param str useraction: Control the button text on the PayPal page. :rtype: str :returns: The URL to redirect the user to for approval.
[ "Returns", "the", "URL", "to", "redirect", "the", "user", "to", "for", "the", "Express", "checkout", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L430-L454
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.generate_cart_upload_redirect_url
def generate_cart_upload_redirect_url(self, **kwargs): """https://www.sandbox.paypal.com/webscr ?cmd=_cart &upload=1 """ required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1') self._check_required(required_vals, **kwargs) url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE additional = self._encode_utf8(**kwargs) additional = urlencode(additional) return url + "&" + additional
python
def generate_cart_upload_redirect_url(self, **kwargs): """https://www.sandbox.paypal.com/webscr ?cmd=_cart &upload=1 """ required_vals = ('business', 'item_name_1', 'amount_1', 'quantity_1') self._check_required(required_vals, **kwargs) url = "%s?cmd=_cart&upload=1" % self.config.PAYPAL_URL_BASE additional = self._encode_utf8(**kwargs) additional = urlencode(additional) return url + "&" + additional
[ "def", "generate_cart_upload_redirect_url", "(", "self", ",", "*", "*", "kwargs", ")", ":", "required_vals", "=", "(", "'business'", ",", "'item_name_1'", ",", "'amount_1'", ",", "'quantity_1'", ")", "self", ".", "_check_required", "(", "required_vals", ",", "*", "*", "kwargs", ")", "url", "=", "\"%s?cmd=_cart&upload=1\"", "%", "self", ".", "config", ".", "PAYPAL_URL_BASE", "additional", "=", "self", ".", "_encode_utf8", "(", "*", "*", "kwargs", ")", "additional", "=", "urlencode", "(", "additional", ")", "return", "url", "+", "\"&\"", "+", "additional" ]
https://www.sandbox.paypal.com/webscr ?cmd=_cart &upload=1
[ "https", ":", "//", "www", ".", "sandbox", ".", "paypal", ".", "com", "/", "webscr", "?cmd", "=", "_cart", "&upload", "=", "1" ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L456-L466
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.get_recurring_payments_profile_details
def get_recurring_payments_profile_details(self, profileid): """Shortcut for the GetRecurringPaymentsProfile method. This returns details for a recurring payment plan. The ``profileid`` is a value included in the response retrieved by the function ``create_recurring_payments_profile``. The profile details include the data provided when the profile was created as well as default values for ignored fields and some pertinent stastics. e.g.: response = create_recurring_payments_profile(**profile_info) profileid = response.PROFILEID details = get_recurring_payments_profile(profileid) The response from PayPal is somewhat self-explanatory, but for a description of each field, visit the following URI: https://www.x.com/docs/DOC-1194 """ args = self._sanitize_locals(locals()) return self._call('GetRecurringPaymentsProfileDetails', **args)
python
def get_recurring_payments_profile_details(self, profileid): """Shortcut for the GetRecurringPaymentsProfile method. This returns details for a recurring payment plan. The ``profileid`` is a value included in the response retrieved by the function ``create_recurring_payments_profile``. The profile details include the data provided when the profile was created as well as default values for ignored fields and some pertinent stastics. e.g.: response = create_recurring_payments_profile(**profile_info) profileid = response.PROFILEID details = get_recurring_payments_profile(profileid) The response from PayPal is somewhat self-explanatory, but for a description of each field, visit the following URI: https://www.x.com/docs/DOC-1194 """ args = self._sanitize_locals(locals()) return self._call('GetRecurringPaymentsProfileDetails', **args)
[ "def", "get_recurring_payments_profile_details", "(", "self", ",", "profileid", ")", ":", "args", "=", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", "return", "self", ".", "_call", "(", "'GetRecurringPaymentsProfileDetails'", ",", "*", "*", "args", ")" ]
Shortcut for the GetRecurringPaymentsProfile method. This returns details for a recurring payment plan. The ``profileid`` is a value included in the response retrieved by the function ``create_recurring_payments_profile``. The profile details include the data provided when the profile was created as well as default values for ignored fields and some pertinent stastics. e.g.: response = create_recurring_payments_profile(**profile_info) profileid = response.PROFILEID details = get_recurring_payments_profile(profileid) The response from PayPal is somewhat self-explanatory, but for a description of each field, visit the following URI: https://www.x.com/docs/DOC-1194
[ "Shortcut", "for", "the", "GetRecurringPaymentsProfile", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L468-L487
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.manage_recurring_payments_profile_status
def manage_recurring_payments_profile_status(self, profileid, action, note=None): """Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'. ``note`` is optional and is visible to the user. It contains the reason for the change in status. """ args = self._sanitize_locals(locals()) if not note: del args['note'] return self._call('ManageRecurringPaymentsProfileStatus', **args)
python
def manage_recurring_payments_profile_status(self, profileid, action, note=None): """Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'. ``note`` is optional and is visible to the user. It contains the reason for the change in status. """ args = self._sanitize_locals(locals()) if not note: del args['note'] return self._call('ManageRecurringPaymentsProfileStatus', **args)
[ "def", "manage_recurring_payments_profile_status", "(", "self", ",", "profileid", ",", "action", ",", "note", "=", "None", ")", ":", "args", "=", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", "if", "not", "note", ":", "del", "args", "[", "'note'", "]", "return", "self", ".", "_call", "(", "'ManageRecurringPaymentsProfileStatus'", ",", "*", "*", "args", ")" ]
Shortcut to the ManageRecurringPaymentsProfileStatus method. ``profileid`` is the same profile id used for getting profile details. ``action`` should be either 'Cancel', 'Suspend', or 'Reactivate'. ``note`` is optional and is visible to the user. It contains the reason for the change in status.
[ "Shortcut", "to", "the", "ManageRecurringPaymentsProfileStatus", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L489-L501
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.update_recurring_payments_profile
def update_recurring_payments_profile(self, profileid, **kwargs): """Shortcut to the UpdateRecurringPaymentsProfile method. ``profileid`` is the same profile id used for getting profile details. The keyed arguments are data in the payment profile which you wish to change. The profileid does not change. Anything else will take the new value. Most of, though not all of, the fields available are shared with creating a profile, but for the complete list of parameters, you can visit the following URI: https://www.x.com/docs/DOC-1212 """ kwargs.update(self._sanitize_locals(locals())) return self._call('UpdateRecurringPaymentsProfile', **kwargs)
python
def update_recurring_payments_profile(self, profileid, **kwargs): """Shortcut to the UpdateRecurringPaymentsProfile method. ``profileid`` is the same profile id used for getting profile details. The keyed arguments are data in the payment profile which you wish to change. The profileid does not change. Anything else will take the new value. Most of, though not all of, the fields available are shared with creating a profile, but for the complete list of parameters, you can visit the following URI: https://www.x.com/docs/DOC-1212 """ kwargs.update(self._sanitize_locals(locals())) return self._call('UpdateRecurringPaymentsProfile', **kwargs)
[ "def", "update_recurring_payments_profile", "(", "self", ",", "profileid", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", ")", "return", "self", ".", "_call", "(", "'UpdateRecurringPaymentsProfile'", ",", "*", "*", "kwargs", ")" ]
Shortcut to the UpdateRecurringPaymentsProfile method. ``profileid`` is the same profile id used for getting profile details. The keyed arguments are data in the payment profile which you wish to change. The profileid does not change. Anything else will take the new value. Most of, though not all of, the fields available are shared with creating a profile, but for the complete list of parameters, you can visit the following URI: https://www.x.com/docs/DOC-1212
[ "Shortcut", "to", "the", "UpdateRecurringPaymentsProfile", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L503-L516
gtaylor/paypal-python
paypal/interface.py
PayPalInterface.bm_create_button
def bm_create_button(self, **kwargs): """Shortcut to the BMCreateButton method. See the docs for details on arguments: https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton The L_BUTTONVARn fields are especially important, so make sure to read those and act accordingly. See unit tests for some examples. """ kwargs.update(self._sanitize_locals(locals())) return self._call('BMCreateButton', **kwargs)
python
def bm_create_button(self, **kwargs): """Shortcut to the BMCreateButton method. See the docs for details on arguments: https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton The L_BUTTONVARn fields are especially important, so make sure to read those and act accordingly. See unit tests for some examples. """ kwargs.update(self._sanitize_locals(locals())) return self._call('BMCreateButton', **kwargs)
[ "def", "bm_create_button", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "_sanitize_locals", "(", "locals", "(", ")", ")", ")", "return", "self", ".", "_call", "(", "'BMCreateButton'", ",", "*", "*", "kwargs", ")" ]
Shortcut to the BMCreateButton method. See the docs for details on arguments: https://cms.paypal.com/mx/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_nvp_BMCreateButton The L_BUTTONVARn fields are especially important, so make sure to read those and act accordingly. See unit tests for some examples.
[ "Shortcut", "to", "the", "BMCreateButton", "method", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/interface.py#L518-L528
gtaylor/paypal-python
paypal/response.py
PayPalResponse.success
def success(self): """ Checks for the presence of errors in the response. Returns ``True`` if all is well, ``False`` otherwise. :rtype: bool :returns ``True`` if PayPal says our query was successful. """ return self.ack.upper() in (self.config.ACK_SUCCESS, self.config.ACK_SUCCESS_WITH_WARNING)
python
def success(self): """ Checks for the presence of errors in the response. Returns ``True`` if all is well, ``False`` otherwise. :rtype: bool :returns ``True`` if PayPal says our query was successful. """ return self.ack.upper() in (self.config.ACK_SUCCESS, self.config.ACK_SUCCESS_WITH_WARNING)
[ "def", "success", "(", "self", ")", ":", "return", "self", ".", "ack", ".", "upper", "(", ")", "in", "(", "self", ".", "config", ".", "ACK_SUCCESS", ",", "self", ".", "config", ".", "ACK_SUCCESS_WITH_WARNING", ")" ]
Checks for the presence of errors in the response. Returns ``True`` if all is well, ``False`` otherwise. :rtype: bool :returns ``True`` if PayPal says our query was successful.
[ "Checks", "for", "the", "presence", "of", "errors", "in", "the", "response", ".", "Returns", "True", "if", "all", "is", "well", "False", "otherwise", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/response.py#L109-L118
gtaylor/paypal-python
paypal/countries.py
is_valid_country_abbrev
def is_valid_country_abbrev(abbrev, case_sensitive=False): """ Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not. """ if case_sensitive: country_code = abbrev else: country_code = abbrev.upper() for code, full_name in COUNTRY_TUPLES: if country_code == code: return True return False
python
def is_valid_country_abbrev(abbrev, case_sensitive=False): """ Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not. """ if case_sensitive: country_code = abbrev else: country_code = abbrev.upper() for code, full_name in COUNTRY_TUPLES: if country_code == code: return True return False
[ "def", "is_valid_country_abbrev", "(", "abbrev", ",", "case_sensitive", "=", "False", ")", ":", "if", "case_sensitive", ":", "country_code", "=", "abbrev", "else", ":", "country_code", "=", "abbrev", ".", "upper", "(", ")", "for", "code", ",", "full_name", "in", "COUNTRY_TUPLES", ":", "if", "country_code", "==", "code", ":", "return", "True", "return", "False" ]
Given a country code abbreviation, check to see if it matches the country table. abbrev: (str) Country code to evaluate. case_sensitive: (bool) When True, enforce case sensitivity. Returns True if valid, False if not.
[ "Given", "a", "country", "code", "abbreviation", "check", "to", "see", "if", "it", "matches", "the", "country", "table", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/countries.py#L254-L273
gtaylor/paypal-python
paypal/countries.py
get_name_from_abbrev
def get_name_from_abbrev(abbrev, case_sensitive=False): """ Given a country code abbreviation, get the full name from the table. abbrev: (str) Country code to retrieve the full name of. case_sensitive: (bool) When True, enforce case sensitivity. """ if case_sensitive: country_code = abbrev else: country_code = abbrev.upper() for code, full_name in COUNTRY_TUPLES: if country_code == code: return full_name raise KeyError('No country with that country code.')
python
def get_name_from_abbrev(abbrev, case_sensitive=False): """ Given a country code abbreviation, get the full name from the table. abbrev: (str) Country code to retrieve the full name of. case_sensitive: (bool) When True, enforce case sensitivity. """ if case_sensitive: country_code = abbrev else: country_code = abbrev.upper() for code, full_name in COUNTRY_TUPLES: if country_code == code: return full_name raise KeyError('No country with that country code.')
[ "def", "get_name_from_abbrev", "(", "abbrev", ",", "case_sensitive", "=", "False", ")", ":", "if", "case_sensitive", ":", "country_code", "=", "abbrev", "else", ":", "country_code", "=", "abbrev", ".", "upper", "(", ")", "for", "code", ",", "full_name", "in", "COUNTRY_TUPLES", ":", "if", "country_code", "==", "code", ":", "return", "full_name", "raise", "KeyError", "(", "'No country with that country code.'", ")" ]
Given a country code abbreviation, get the full name from the table. abbrev: (str) Country code to retrieve the full name of. case_sensitive: (bool) When True, enforce case sensitivity.
[ "Given", "a", "country", "code", "abbreviation", "get", "the", "full", "name", "from", "the", "table", "." ]
train
https://github.com/gtaylor/paypal-python/blob/aa7a987ea9e9b7f37bcd8a8b54a440aad6c871b1/paypal/countries.py#L276-L292
touilleMan/marshmallow-mongoengine
marshmallow_mongoengine/schema.py
SchemaMeta.get_declared_fields
def get_declared_fields(mcs, klass, *args, **kwargs): """Updates declared fields with fields converted from the Mongoengine model passed as the `model` class Meta option. """ declared_fields = kwargs.get('dict_class', dict)() # Generate the fields provided through inheritance opts = klass.opts model = getattr(opts, 'model', None) if model: converter = opts.model_converter() declared_fields.update(converter.fields_for_model( model, fields=opts.fields )) # Generate the fields provided in the current class base_fields = super(SchemaMeta, mcs).get_declared_fields( klass, *args, **kwargs ) declared_fields.update(base_fields) # Customize fields with provided kwargs for field_name, field_kwargs in klass.opts.model_fields_kwargs.items(): field = declared_fields.get(field_name, None) if field: # Copy to prevent alteration of a possible parent class's field field = copy.copy(field) for key, value in field_kwargs.items(): setattr(field, key, value) declared_fields[field_name] = field if opts.model_dump_only_pk and opts.model: # If primary key is automatically generated (nominal case), we # must make sure this field is read-only if opts.model._auto_id_field is True: field_name = opts.model._meta['id_field'] id_field = declared_fields.get(field_name) if id_field: # Copy to prevent alteration of a possible parent class's field id_field = copy.copy(id_field) id_field.dump_only = True declared_fields[field_name] = id_field return declared_fields
python
def get_declared_fields(mcs, klass, *args, **kwargs): """Updates declared fields with fields converted from the Mongoengine model passed as the `model` class Meta option. """ declared_fields = kwargs.get('dict_class', dict)() # Generate the fields provided through inheritance opts = klass.opts model = getattr(opts, 'model', None) if model: converter = opts.model_converter() declared_fields.update(converter.fields_for_model( model, fields=opts.fields )) # Generate the fields provided in the current class base_fields = super(SchemaMeta, mcs).get_declared_fields( klass, *args, **kwargs ) declared_fields.update(base_fields) # Customize fields with provided kwargs for field_name, field_kwargs in klass.opts.model_fields_kwargs.items(): field = declared_fields.get(field_name, None) if field: # Copy to prevent alteration of a possible parent class's field field = copy.copy(field) for key, value in field_kwargs.items(): setattr(field, key, value) declared_fields[field_name] = field if opts.model_dump_only_pk and opts.model: # If primary key is automatically generated (nominal case), we # must make sure this field is read-only if opts.model._auto_id_field is True: field_name = opts.model._meta['id_field'] id_field = declared_fields.get(field_name) if id_field: # Copy to prevent alteration of a possible parent class's field id_field = copy.copy(id_field) id_field.dump_only = True declared_fields[field_name] = id_field return declared_fields
[ "def", "get_declared_fields", "(", "mcs", ",", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "declared_fields", "=", "kwargs", ".", "get", "(", "'dict_class'", ",", "dict", ")", "(", ")", "# Generate the fields provided through inheritance", "opts", "=", "klass", ".", "opts", "model", "=", "getattr", "(", "opts", ",", "'model'", ",", "None", ")", "if", "model", ":", "converter", "=", "opts", ".", "model_converter", "(", ")", "declared_fields", ".", "update", "(", "converter", ".", "fields_for_model", "(", "model", ",", "fields", "=", "opts", ".", "fields", ")", ")", "# Generate the fields provided in the current class", "base_fields", "=", "super", "(", "SchemaMeta", ",", "mcs", ")", ".", "get_declared_fields", "(", "klass", ",", "*", "args", ",", "*", "*", "kwargs", ")", "declared_fields", ".", "update", "(", "base_fields", ")", "# Customize fields with provided kwargs", "for", "field_name", ",", "field_kwargs", "in", "klass", ".", "opts", ".", "model_fields_kwargs", ".", "items", "(", ")", ":", "field", "=", "declared_fields", ".", "get", "(", "field_name", ",", "None", ")", "if", "field", ":", "# Copy to prevent alteration of a possible parent class's field", "field", "=", "copy", ".", "copy", "(", "field", ")", "for", "key", ",", "value", "in", "field_kwargs", ".", "items", "(", ")", ":", "setattr", "(", "field", ",", "key", ",", "value", ")", "declared_fields", "[", "field_name", "]", "=", "field", "if", "opts", ".", "model_dump_only_pk", "and", "opts", ".", "model", ":", "# If primary key is automatically generated (nominal case), we", "# must make sure this field is read-only", "if", "opts", ".", "model", ".", "_auto_id_field", "is", "True", ":", "field_name", "=", "opts", ".", "model", ".", "_meta", "[", "'id_field'", "]", "id_field", "=", "declared_fields", ".", "get", "(", "field_name", ")", "if", "id_field", ":", "# Copy to prevent alteration of a possible parent class's field", "id_field", "=", "copy", ".", "copy", "(", "id_field", ")", "id_field", ".", "dump_only", "=", "True", "declared_fields", "[", "field_name", "]", "=", "id_field", "return", "declared_fields" ]
Updates declared fields with fields converted from the Mongoengine model passed as the `model` class Meta option.
[ "Updates", "declared", "fields", "with", "fields", "converted", "from", "the", "Mongoengine", "model", "passed", "as", "the", "model", "class", "Meta", "option", "." ]
train
https://github.com/touilleMan/marshmallow-mongoengine/blob/21223700ea1f1d0209c967761e5c22635ee721e7/marshmallow_mongoengine/schema.py#L49-L88
touilleMan/marshmallow-mongoengine
marshmallow_mongoengine/schema.py
ModelSchema.update
def update(self, obj, data): """Helper function to update an already existing document instead of creating a new one. :param obj: Mongoengine Document to update :param data: incomming payload to deserialize :return: an :class UnmarshallResult: Example: :: from marshmallow_mongoengine import ModelSchema from mymodels import User class UserSchema(ModelSchema): class Meta: model = User def update_obj(id, payload): user = User.objects(id=id).first() result = UserSchema().update(user, payload) result.data is user # True Note: Given the update is done on a existing object, the required param on the fields is ignored """ # TODO: find a cleaner way to skip required validation on update required_fields = [k for k, f in self.fields.items() if f.required] for field in required_fields: self.fields[field].required = False loaded_data, errors = self._do_load(data, postprocess=False) for field in required_fields: self.fields[field].required = True if not errors: # Update the given obj fields for k, v in loaded_data.items(): # Skip default values that have been automatically # added during unserialization if k in data: setattr(obj, k, v) return ma.UnmarshalResult(data=obj, errors=errors)
python
def update(self, obj, data): """Helper function to update an already existing document instead of creating a new one. :param obj: Mongoengine Document to update :param data: incomming payload to deserialize :return: an :class UnmarshallResult: Example: :: from marshmallow_mongoengine import ModelSchema from mymodels import User class UserSchema(ModelSchema): class Meta: model = User def update_obj(id, payload): user = User.objects(id=id).first() result = UserSchema().update(user, payload) result.data is user # True Note: Given the update is done on a existing object, the required param on the fields is ignored """ # TODO: find a cleaner way to skip required validation on update required_fields = [k for k, f in self.fields.items() if f.required] for field in required_fields: self.fields[field].required = False loaded_data, errors = self._do_load(data, postprocess=False) for field in required_fields: self.fields[field].required = True if not errors: # Update the given obj fields for k, v in loaded_data.items(): # Skip default values that have been automatically # added during unserialization if k in data: setattr(obj, k, v) return ma.UnmarshalResult(data=obj, errors=errors)
[ "def", "update", "(", "self", ",", "obj", ",", "data", ")", ":", "# TODO: find a cleaner way to skip required validation on update", "required_fields", "=", "[", "k", "for", "k", ",", "f", "in", "self", ".", "fields", ".", "items", "(", ")", "if", "f", ".", "required", "]", "for", "field", "in", "required_fields", ":", "self", ".", "fields", "[", "field", "]", ".", "required", "=", "False", "loaded_data", ",", "errors", "=", "self", ".", "_do_load", "(", "data", ",", "postprocess", "=", "False", ")", "for", "field", "in", "required_fields", ":", "self", ".", "fields", "[", "field", "]", ".", "required", "=", "True", "if", "not", "errors", ":", "# Update the given obj fields", "for", "k", ",", "v", "in", "loaded_data", ".", "items", "(", ")", ":", "# Skip default values that have been automatically", "# added during unserialization", "if", "k", "in", "data", ":", "setattr", "(", "obj", ",", "k", ",", "v", ")", "return", "ma", ".", "UnmarshalResult", "(", "data", "=", "obj", ",", "errors", "=", "errors", ")" ]
Helper function to update an already existing document instead of creating a new one. :param obj: Mongoengine Document to update :param data: incomming payload to deserialize :return: an :class UnmarshallResult: Example: :: from marshmallow_mongoengine import ModelSchema from mymodels import User class UserSchema(ModelSchema): class Meta: model = User def update_obj(id, payload): user = User.objects(id=id).first() result = UserSchema().update(user, payload) result.data is user # True Note: Given the update is done on a existing object, the required param on the fields is ignored
[ "Helper", "function", "to", "update", "an", "already", "existing", "document", "instead", "of", "creating", "a", "new", "one", ".", ":", "param", "obj", ":", "Mongoengine", "Document", "to", "update", ":", "param", "data", ":", "incomming", "payload", "to", "deserialize", ":", "return", ":", "an", ":", "class", "UnmarshallResult", ":" ]
train
https://github.com/touilleMan/marshmallow-mongoengine/blob/21223700ea1f1d0209c967761e5c22635ee721e7/marshmallow_mongoengine/schema.py#L120-L160
touilleMan/marshmallow-mongoengine
marshmallow_mongoengine/conversion/fields.py
register_field
def register_field(mongo_field_cls, marshmallow_field_cls, available_params=()): """ Bind a marshmallow field to it corresponding mongoengine field :param mongo_field_cls: Mongoengine Field :param marshmallow_field_cls: Marshmallow Field :param available_params: List of :class marshmallow_mongoengine.cnoversion.params.MetaParam: instances to import the mongoengine field config to marshmallow """ class Builder(MetaFieldBuilder): AVAILABLE_PARAMS = available_params MARSHMALLOW_FIELD_CLS = marshmallow_field_cls register_field_builder(mongo_field_cls, Builder)
python
def register_field(mongo_field_cls, marshmallow_field_cls, available_params=()): """ Bind a marshmallow field to it corresponding mongoengine field :param mongo_field_cls: Mongoengine Field :param marshmallow_field_cls: Marshmallow Field :param available_params: List of :class marshmallow_mongoengine.cnoversion.params.MetaParam: instances to import the mongoengine field config to marshmallow """ class Builder(MetaFieldBuilder): AVAILABLE_PARAMS = available_params MARSHMALLOW_FIELD_CLS = marshmallow_field_cls register_field_builder(mongo_field_cls, Builder)
[ "def", "register_field", "(", "mongo_field_cls", ",", "marshmallow_field_cls", ",", "available_params", "=", "(", ")", ")", ":", "class", "Builder", "(", "MetaFieldBuilder", ")", ":", "AVAILABLE_PARAMS", "=", "available_params", "MARSHMALLOW_FIELD_CLS", "=", "marshmallow_field_cls", "register_field_builder", "(", "mongo_field_cls", ",", "Builder", ")" ]
Bind a marshmallow field to it corresponding mongoengine field :param mongo_field_cls: Mongoengine Field :param marshmallow_field_cls: Marshmallow Field :param available_params: List of :class marshmallow_mongoengine.cnoversion.params.MetaParam: instances to import the mongoengine field config to marshmallow
[ "Bind", "a", "marshmallow", "field", "to", "it", "corresponding", "mongoengine", "field", ":", "param", "mongo_field_cls", ":", "Mongoengine", "Field", ":", "param", "marshmallow_field_cls", ":", "Marshmallow", "Field", ":", "param", "available_params", ":", "List", "of", ":", "class", "marshmallow_mongoengine", ".", "cnoversion", ".", "params", ".", "MetaParam", ":", "instances", "to", "import", "the", "mongoengine", "field", "config", "to", "marshmallow" ]
train
https://github.com/touilleMan/marshmallow-mongoengine/blob/21223700ea1f1d0209c967761e5c22635ee721e7/marshmallow_mongoengine/conversion/fields.py#L143-L155
touilleMan/marshmallow-mongoengine
marshmallow_mongoengine/conversion/fields.py
MetaFieldBuilder.build_marshmallow_field
def build_marshmallow_field(self, **kwargs): """ :return: The Marshmallow Field instanciated and configured """ field_kwargs = None for param in self.params: field_kwargs = param.apply(field_kwargs) field_kwargs.update(kwargs) return self.marshmallow_field_cls(**field_kwargs)
python
def build_marshmallow_field(self, **kwargs): """ :return: The Marshmallow Field instanciated and configured """ field_kwargs = None for param in self.params: field_kwargs = param.apply(field_kwargs) field_kwargs.update(kwargs) return self.marshmallow_field_cls(**field_kwargs)
[ "def", "build_marshmallow_field", "(", "self", ",", "*", "*", "kwargs", ")", ":", "field_kwargs", "=", "None", "for", "param", "in", "self", ".", "params", ":", "field_kwargs", "=", "param", ".", "apply", "(", "field_kwargs", ")", "field_kwargs", ".", "update", "(", "kwargs", ")", "return", "self", ".", "marshmallow_field_cls", "(", "*", "*", "field_kwargs", ")" ]
:return: The Marshmallow Field instanciated and configured
[ ":", "return", ":", "The", "Marshmallow", "Field", "instanciated", "and", "configured" ]
train
https://github.com/touilleMan/marshmallow-mongoengine/blob/21223700ea1f1d0209c967761e5c22635ee721e7/marshmallow_mongoengine/conversion/fields.py#L25-L33
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.loop
def loop(self, timeout = 1): """Main loop.""" rlist = [self.sock] wlist = [] if len(self.out_packet) > 0: wlist.append(self.sock) to_read, to_write, _ = select.select(rlist, wlist, [], timeout) if len(to_read) > 0: ret, _ = self.loop_read() if ret != NC.ERR_SUCCESS: return ret if len(to_write) > 0: ret, _ = self.loop_write() if ret != NC.ERR_SUCCESS: return ret self.loop_misc() return NC.ERR_SUCCESS
python
def loop(self, timeout = 1): """Main loop.""" rlist = [self.sock] wlist = [] if len(self.out_packet) > 0: wlist.append(self.sock) to_read, to_write, _ = select.select(rlist, wlist, [], timeout) if len(to_read) > 0: ret, _ = self.loop_read() if ret != NC.ERR_SUCCESS: return ret if len(to_write) > 0: ret, _ = self.loop_write() if ret != NC.ERR_SUCCESS: return ret self.loop_misc() return NC.ERR_SUCCESS
[ "def", "loop", "(", "self", ",", "timeout", "=", "1", ")", ":", "rlist", "=", "[", "self", ".", "sock", "]", "wlist", "=", "[", "]", "if", "len", "(", "self", ".", "out_packet", ")", ">", "0", ":", "wlist", ".", "append", "(", "self", ".", "sock", ")", "to_read", ",", "to_write", ",", "_", "=", "select", ".", "select", "(", "rlist", ",", "wlist", ",", "[", "]", ",", "timeout", ")", "if", "len", "(", "to_read", ")", ">", "0", ":", "ret", ",", "_", "=", "self", ".", "loop_read", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "if", "len", "(", "to_write", ")", ">", "0", ":", "ret", ",", "_", "=", "self", ".", "loop_write", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "self", ".", "loop_misc", "(", ")", "return", "NC", ".", "ERR_SUCCESS" ]
Main loop.
[ "Main", "loop", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L49-L70
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.loop_misc
def loop_misc(self): """Misc loop.""" self.check_keepalive() if self.last_retry_check + 1 < time.time(): pass return NC.ERR_SUCCESS
python
def loop_misc(self): """Misc loop.""" self.check_keepalive() if self.last_retry_check + 1 < time.time(): pass return NC.ERR_SUCCESS
[ "def", "loop_misc", "(", "self", ")", ":", "self", ".", "check_keepalive", "(", ")", "if", "self", ".", "last_retry_check", "+", "1", "<", "time", ".", "time", "(", ")", ":", "pass", "return", "NC", ".", "ERR_SUCCESS" ]
Misc loop.
[ "Misc", "loop", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L82-L87
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.check_keepalive
def check_keepalive(self): """Send keepalive/PING if necessary.""" if self.sock != NC.INVALID_SOCKET and time.time() - self.last_msg_out >= self.keep_alive: if self.state == NC.CS_CONNECTED: self.send_pingreq() else: self.socket_close()
python
def check_keepalive(self): """Send keepalive/PING if necessary.""" if self.sock != NC.INVALID_SOCKET and time.time() - self.last_msg_out >= self.keep_alive: if self.state == NC.CS_CONNECTED: self.send_pingreq() else: self.socket_close()
[ "def", "check_keepalive", "(", "self", ")", ":", "if", "self", ".", "sock", "!=", "NC", ".", "INVALID_SOCKET", "and", "time", ".", "time", "(", ")", "-", "self", ".", "last_msg_out", ">=", "self", ".", "keep_alive", ":", "if", "self", ".", "state", "==", "NC", ".", "CS_CONNECTED", ":", "self", ".", "send_pingreq", "(", ")", "else", ":", "self", ".", "socket_close", "(", ")" ]
Send keepalive/PING if necessary.
[ "Send", "keepalive", "/", "PING", "if", "necessary", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L89-L95
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.packet_handle
def packet_handle(self): """Incoming packet handler dispatcher.""" cmd = self.in_packet.command & 0xF0 if cmd == NC.CMD_CONNACK: return self.handle_connack() elif cmd == NC.CMD_PINGRESP: return self.handle_pingresp() elif cmd == NC.CMD_PUBLISH: return self.handle_publish() elif cmd == NC.CMD_PUBACK: return self.handle_puback() elif cmd == NC.CMD_PUBREC: return self.handle_pubrec() elif cmd == NC.CMD_PUBREL: return self.handle_pubrel() elif cmd == NC.CMD_PUBCOMP: return self.handle_pubcomp() elif cmd == NC.CMD_SUBSCRIBE: sys.exit(-1) elif cmd == NC.CMD_SUBACK: return self.handle_suback() elif cmd == NC.CMD_UNSUBSCRIBE: print "Received UNSUBSCRIBE" sys.exit(-1) elif cmd == NC.CMD_UNSUBACK: return self.handle_unsuback() else: self.logger.warning("Unknown protocol. Cmd = %d", cmd) return NC.ERR_PROTOCOL
python
def packet_handle(self): """Incoming packet handler dispatcher.""" cmd = self.in_packet.command & 0xF0 if cmd == NC.CMD_CONNACK: return self.handle_connack() elif cmd == NC.CMD_PINGRESP: return self.handle_pingresp() elif cmd == NC.CMD_PUBLISH: return self.handle_publish() elif cmd == NC.CMD_PUBACK: return self.handle_puback() elif cmd == NC.CMD_PUBREC: return self.handle_pubrec() elif cmd == NC.CMD_PUBREL: return self.handle_pubrel() elif cmd == NC.CMD_PUBCOMP: return self.handle_pubcomp() elif cmd == NC.CMD_SUBSCRIBE: sys.exit(-1) elif cmd == NC.CMD_SUBACK: return self.handle_suback() elif cmd == NC.CMD_UNSUBSCRIBE: print "Received UNSUBSCRIBE" sys.exit(-1) elif cmd == NC.CMD_UNSUBACK: return self.handle_unsuback() else: self.logger.warning("Unknown protocol. Cmd = %d", cmd) return NC.ERR_PROTOCOL
[ "def", "packet_handle", "(", "self", ")", ":", "cmd", "=", "self", ".", "in_packet", ".", "command", "&", "0xF0", "if", "cmd", "==", "NC", ".", "CMD_CONNACK", ":", "return", "self", ".", "handle_connack", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_PINGRESP", ":", "return", "self", ".", "handle_pingresp", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_PUBLISH", ":", "return", "self", ".", "handle_publish", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_PUBACK", ":", "return", "self", ".", "handle_puback", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_PUBREC", ":", "return", "self", ".", "handle_pubrec", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_PUBREL", ":", "return", "self", ".", "handle_pubrel", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_PUBCOMP", ":", "return", "self", ".", "handle_pubcomp", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_SUBSCRIBE", ":", "sys", ".", "exit", "(", "-", "1", ")", "elif", "cmd", "==", "NC", ".", "CMD_SUBACK", ":", "return", "self", ".", "handle_suback", "(", ")", "elif", "cmd", "==", "NC", ".", "CMD_UNSUBSCRIBE", ":", "print", "\"Received UNSUBSCRIBE\"", "sys", ".", "exit", "(", "-", "1", ")", "elif", "cmd", "==", "NC", ".", "CMD_UNSUBACK", ":", "return", "self", ".", "handle_unsuback", "(", ")", "else", ":", "self", ".", "logger", ".", "warning", "(", "\"Unknown protocol. Cmd = %d\"", ",", "cmd", ")", "return", "NC", ".", "ERR_PROTOCOL" ]
Incoming packet handler dispatcher.
[ "Incoming", "packet", "handler", "dispatcher", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L97-L126
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.connect
def connect(self, version = 3, clean_session = 1, will = None): """Connect to server.""" self.clean_session = clean_session self.will = None if will is not None: self.will = NyamukMsg( topic = will['topic'], # unicode text needs to be utf8 encoded to be sent on the wire # str or bytearray are kept as it is payload = utf8encode(will.get('message','')), qos = will.get('qos', 0), retain = will.get('retain', False) ) #CONNECT packet pkt = MqttPkt() pkt.connect_build(self, self.keep_alive, clean_session, version = version) #create socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.ssl: opts = { 'do_handshake_on_connect': True, 'ssl_version': ssl.PROTOCOL_TLSv1 } opts.update(self.ssl_opts) #print opts, self.port try: self.sock = ssl.wrap_socket(self.sock, **opts) except Exception, e: self.logger.error("failed to initiate SSL connection: {0}".format(e)) return NC.ERR_UNKNOWN nyamuk_net.setkeepalives(self.sock) self.logger.info("Connecting to server ....%s", self.server) err = nyamuk_net.connect(self.sock,(self.server, self.port)) #print self.sock.cipher() if err != None: self.logger.error(err[1]) return NC.ERR_UNKNOWN #set to nonblock self.sock.setblocking(0) return self.packet_queue(pkt)
python
def connect(self, version = 3, clean_session = 1, will = None): """Connect to server.""" self.clean_session = clean_session self.will = None if will is not None: self.will = NyamukMsg( topic = will['topic'], # unicode text needs to be utf8 encoded to be sent on the wire # str or bytearray are kept as it is payload = utf8encode(will.get('message','')), qos = will.get('qos', 0), retain = will.get('retain', False) ) #CONNECT packet pkt = MqttPkt() pkt.connect_build(self, self.keep_alive, clean_session, version = version) #create socket self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if self.ssl: opts = { 'do_handshake_on_connect': True, 'ssl_version': ssl.PROTOCOL_TLSv1 } opts.update(self.ssl_opts) #print opts, self.port try: self.sock = ssl.wrap_socket(self.sock, **opts) except Exception, e: self.logger.error("failed to initiate SSL connection: {0}".format(e)) return NC.ERR_UNKNOWN nyamuk_net.setkeepalives(self.sock) self.logger.info("Connecting to server ....%s", self.server) err = nyamuk_net.connect(self.sock,(self.server, self.port)) #print self.sock.cipher() if err != None: self.logger.error(err[1]) return NC.ERR_UNKNOWN #set to nonblock self.sock.setblocking(0) return self.packet_queue(pkt)
[ "def", "connect", "(", "self", ",", "version", "=", "3", ",", "clean_session", "=", "1", ",", "will", "=", "None", ")", ":", "self", ".", "clean_session", "=", "clean_session", "self", ".", "will", "=", "None", "if", "will", "is", "not", "None", ":", "self", ".", "will", "=", "NyamukMsg", "(", "topic", "=", "will", "[", "'topic'", "]", ",", "# unicode text needs to be utf8 encoded to be sent on the wire", "# str or bytearray are kept as it is", "payload", "=", "utf8encode", "(", "will", ".", "get", "(", "'message'", ",", "''", ")", ")", ",", "qos", "=", "will", ".", "get", "(", "'qos'", ",", "0", ")", ",", "retain", "=", "will", ".", "get", "(", "'retain'", ",", "False", ")", ")", "#CONNECT packet", "pkt", "=", "MqttPkt", "(", ")", "pkt", ".", "connect_build", "(", "self", ",", "self", ".", "keep_alive", ",", "clean_session", ",", "version", "=", "version", ")", "#create socket", "self", ".", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "if", "self", ".", "ssl", ":", "opts", "=", "{", "'do_handshake_on_connect'", ":", "True", ",", "'ssl_version'", ":", "ssl", ".", "PROTOCOL_TLSv1", "}", "opts", ".", "update", "(", "self", ".", "ssl_opts", ")", "#print opts, self.port", "try", ":", "self", ".", "sock", "=", "ssl", ".", "wrap_socket", "(", "self", ".", "sock", ",", "*", "*", "opts", ")", "except", "Exception", ",", "e", ":", "self", ".", "logger", ".", "error", "(", "\"failed to initiate SSL connection: {0}\"", ".", "format", "(", "e", ")", ")", "return", "NC", ".", "ERR_UNKNOWN", "nyamuk_net", ".", "setkeepalives", "(", "self", ".", "sock", ")", "self", ".", "logger", ".", "info", "(", "\"Connecting to server ....%s\"", ",", "self", ".", "server", ")", "err", "=", "nyamuk_net", ".", "connect", "(", "self", ".", "sock", ",", "(", "self", ".", "server", ",", "self", ".", "port", ")", ")", "#print self.sock.cipher()", "if", "err", "!=", "None", ":", "self", ".", "logger", ".", "error", "(", "err", "[", "1", "]", ")", "return", "NC", ".", "ERR_UNKNOWN", "#set to nonblock", "self", ".", "sock", ".", "setblocking", "(", "0", ")", "return", "self", ".", "packet_queue", "(", "pkt", ")" ]
Connect to server.
[ "Connect", "to", "server", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L132-L180
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.disconnect
def disconnect(self): """Disconnect from server.""" self.logger.info("DISCONNECT") if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.state = NC.CS_DISCONNECTING ret = self.send_disconnect() ret2, bytes_written = self.packet_write() self.socket_close() return ret
python
def disconnect(self): """Disconnect from server.""" self.logger.info("DISCONNECT") if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.state = NC.CS_DISCONNECTING ret = self.send_disconnect() ret2, bytes_written = self.packet_write() self.socket_close() return ret
[ "def", "disconnect", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"DISCONNECT\"", ")", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOCKET", ":", "return", "NC", ".", "ERR_NO_CONN", "self", ".", "state", "=", "NC", ".", "CS_DISCONNECTING", "ret", "=", "self", ".", "send_disconnect", "(", ")", "ret2", ",", "bytes_written", "=", "self", ".", "packet_write", "(", ")", "self", ".", "socket_close", "(", ")", "return", "ret" ]
Disconnect from server.
[ "Disconnect", "from", "server", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L182-L193
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.subscribe
def subscribe(self, topic, qos): """Subscribe to some topic.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("SUBSCRIBE: %s", topic) return self.send_subscribe(False, [(utf8encode(topic), qos)])
python
def subscribe(self, topic, qos): """Subscribe to some topic.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("SUBSCRIBE: %s", topic) return self.send_subscribe(False, [(utf8encode(topic), qos)])
[ "def", "subscribe", "(", "self", ",", "topic", ",", "qos", ")", ":", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOCKET", ":", "return", "NC", ".", "ERR_NO_CONN", "self", ".", "logger", ".", "info", "(", "\"SUBSCRIBE: %s\"", ",", "topic", ")", "return", "self", ".", "send_subscribe", "(", "False", ",", "[", "(", "utf8encode", "(", "topic", ")", ",", "qos", ")", "]", ")" ]
Subscribe to some topic.
[ "Subscribe", "to", "some", "topic", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L195-L201
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.subscribe_multi
def subscribe_multi(self, topics): """Subscribe to some topics.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("SUBSCRIBE: %s", ', '.join([t for (t,q) in topics])) return self.send_subscribe(False, [(utf8encode(topic), qos) for (topic, qos) in topics])
python
def subscribe_multi(self, topics): """Subscribe to some topics.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("SUBSCRIBE: %s", ', '.join([t for (t,q) in topics])) return self.send_subscribe(False, [(utf8encode(topic), qos) for (topic, qos) in topics])
[ "def", "subscribe_multi", "(", "self", ",", "topics", ")", ":", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOCKET", ":", "return", "NC", ".", "ERR_NO_CONN", "self", ".", "logger", ".", "info", "(", "\"SUBSCRIBE: %s\"", ",", "', '", ".", "join", "(", "[", "t", "for", "(", "t", ",", "q", ")", "in", "topics", "]", ")", ")", "return", "self", ".", "send_subscribe", "(", "False", ",", "[", "(", "utf8encode", "(", "topic", ")", ",", "qos", ")", "for", "(", "topic", ",", "qos", ")", "in", "topics", "]", ")" ]
Subscribe to some topics.
[ "Subscribe", "to", "some", "topics", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L204-L210
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.unsubscribe
def unsubscribe(self, topic): """Unsubscribe to some topic.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("UNSUBSCRIBE: %s", topic) return self.send_unsubscribe(False, [utf8encode(topic)])
python
def unsubscribe(self, topic): """Unsubscribe to some topic.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("UNSUBSCRIBE: %s", topic) return self.send_unsubscribe(False, [utf8encode(topic)])
[ "def", "unsubscribe", "(", "self", ",", "topic", ")", ":", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOCKET", ":", "return", "NC", ".", "ERR_NO_CONN", "self", ".", "logger", ".", "info", "(", "\"UNSUBSCRIBE: %s\"", ",", "topic", ")", "return", "self", ".", "send_unsubscribe", "(", "False", ",", "[", "utf8encode", "(", "topic", ")", "]", ")" ]
Unsubscribe to some topic.
[ "Unsubscribe", "to", "some", "topic", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L212-L218
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.unsubscribe_multi
def unsubscribe_multi(self, topics): """Unsubscribe to some topics.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("UNSUBSCRIBE: %s", ', '.join(topics)) return self.send_unsubscribe(False, [utf8encode(topic) for topic in topics])
python
def unsubscribe_multi(self, topics): """Unsubscribe to some topics.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("UNSUBSCRIBE: %s", ', '.join(topics)) return self.send_unsubscribe(False, [utf8encode(topic) for topic in topics])
[ "def", "unsubscribe_multi", "(", "self", ",", "topics", ")", ":", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOCKET", ":", "return", "NC", ".", "ERR_NO_CONN", "self", ".", "logger", ".", "info", "(", "\"UNSUBSCRIBE: %s\"", ",", "', '", ".", "join", "(", "topics", ")", ")", "return", "self", ".", "send_unsubscribe", "(", "False", ",", "[", "utf8encode", "(", "topic", ")", "for", "topic", "in", "topics", "]", ")" ]
Unsubscribe to some topics.
[ "Unsubscribe", "to", "some", "topics", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L220-L226
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.send_subscribe
def send_subscribe(self, dup, topics): """Send subscribe COMMAND to server.""" pkt = MqttPkt() pktlen = 2 + sum([2+len(topic)+1 for (topic, qos) in topics]) pkt.command = NC.CMD_SUBSCRIBE | (dup << 3) | (1 << 1) pkt.remaining_length = pktlen ret = pkt.alloc() if ret != NC.ERR_SUCCESS: return ret #variable header mid = self.mid_generate() pkt.write_uint16(mid) #payload for (topic, qos) in topics: pkt.write_string(topic) pkt.write_byte(qos) return self.packet_queue(pkt)
python
def send_subscribe(self, dup, topics): """Send subscribe COMMAND to server.""" pkt = MqttPkt() pktlen = 2 + sum([2+len(topic)+1 for (topic, qos) in topics]) pkt.command = NC.CMD_SUBSCRIBE | (dup << 3) | (1 << 1) pkt.remaining_length = pktlen ret = pkt.alloc() if ret != NC.ERR_SUCCESS: return ret #variable header mid = self.mid_generate() pkt.write_uint16(mid) #payload for (topic, qos) in topics: pkt.write_string(topic) pkt.write_byte(qos) return self.packet_queue(pkt)
[ "def", "send_subscribe", "(", "self", ",", "dup", ",", "topics", ")", ":", "pkt", "=", "MqttPkt", "(", ")", "pktlen", "=", "2", "+", "sum", "(", "[", "2", "+", "len", "(", "topic", ")", "+", "1", "for", "(", "topic", ",", "qos", ")", "in", "topics", "]", ")", "pkt", ".", "command", "=", "NC", ".", "CMD_SUBSCRIBE", "|", "(", "dup", "<<", "3", ")", "|", "(", "1", "<<", "1", ")", "pkt", ".", "remaining_length", "=", "pktlen", "ret", "=", "pkt", ".", "alloc", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "#variable header", "mid", "=", "self", ".", "mid_generate", "(", ")", "pkt", ".", "write_uint16", "(", "mid", ")", "#payload", "for", "(", "topic", ",", "qos", ")", "in", "topics", ":", "pkt", ".", "write_string", "(", "topic", ")", "pkt", ".", "write_byte", "(", "qos", ")", "return", "self", ".", "packet_queue", "(", "pkt", ")" ]
Send subscribe COMMAND to server.
[ "Send", "subscribe", "COMMAND", "to", "server", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L233-L254
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.send_unsubscribe
def send_unsubscribe(self, dup, topics): """Send unsubscribe COMMAND to server.""" pkt = MqttPkt() pktlen = 2 + sum([2+len(topic) for topic in topics]) pkt.command = NC.CMD_UNSUBSCRIBE | (dup << 3) | (1 << 1) pkt.remaining_length = pktlen ret = pkt.alloc() if ret != NC.ERR_SUCCESS: return ret #variable header mid = self.mid_generate() pkt.write_uint16(mid) #payload for topic in topics: pkt.write_string(topic) return self.packet_queue(pkt)
python
def send_unsubscribe(self, dup, topics): """Send unsubscribe COMMAND to server.""" pkt = MqttPkt() pktlen = 2 + sum([2+len(topic) for topic in topics]) pkt.command = NC.CMD_UNSUBSCRIBE | (dup << 3) | (1 << 1) pkt.remaining_length = pktlen ret = pkt.alloc() if ret != NC.ERR_SUCCESS: return ret #variable header mid = self.mid_generate() pkt.write_uint16(mid) #payload for topic in topics: pkt.write_string(topic) return self.packet_queue(pkt)
[ "def", "send_unsubscribe", "(", "self", ",", "dup", ",", "topics", ")", ":", "pkt", "=", "MqttPkt", "(", ")", "pktlen", "=", "2", "+", "sum", "(", "[", "2", "+", "len", "(", "topic", ")", "for", "topic", "in", "topics", "]", ")", "pkt", ".", "command", "=", "NC", ".", "CMD_UNSUBSCRIBE", "|", "(", "dup", "<<", "3", ")", "|", "(", "1", "<<", "1", ")", "pkt", ".", "remaining_length", "=", "pktlen", "ret", "=", "pkt", ".", "alloc", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "#variable header", "mid", "=", "self", ".", "mid_generate", "(", ")", "pkt", ".", "write_uint16", "(", "mid", ")", "#payload", "for", "topic", "in", "topics", ":", "pkt", ".", "write_string", "(", "topic", ")", "return", "self", ".", "packet_queue", "(", "pkt", ")" ]
Send unsubscribe COMMAND to server.
[ "Send", "unsubscribe", "COMMAND", "to", "server", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L256-L276
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.publish
def publish(self, topic, payload = None, qos = 0, retain = False): """Publish some payload to server.""" #print "PUBLISHING (",topic,"): ", payload payloadlen = len(payload) if topic is None or qos < 0 or qos > 2: print "PUBLISH:err inval" return NC.ERR_INVAL #payloadlen <= 250MB if payloadlen > (250 * 1024 * 1204): self.logger.error("PUBLISH:err payload len:%d", payloadlen) return NC.ERR_PAYLOAD_SIZE #wildcard check : TODO mid = self.mid_generate() if qos in (0,1,2): return self.send_publish(mid, topic, payload, qos, retain, False) else: self.logger.error("Unsupport QoS= %d", qos) return NC.ERR_NOT_SUPPORTED
python
def publish(self, topic, payload = None, qos = 0, retain = False): """Publish some payload to server.""" #print "PUBLISHING (",topic,"): ", payload payloadlen = len(payload) if topic is None or qos < 0 or qos > 2: print "PUBLISH:err inval" return NC.ERR_INVAL #payloadlen <= 250MB if payloadlen > (250 * 1024 * 1204): self.logger.error("PUBLISH:err payload len:%d", payloadlen) return NC.ERR_PAYLOAD_SIZE #wildcard check : TODO mid = self.mid_generate() if qos in (0,1,2): return self.send_publish(mid, topic, payload, qos, retain, False) else: self.logger.error("Unsupport QoS= %d", qos) return NC.ERR_NOT_SUPPORTED
[ "def", "publish", "(", "self", ",", "topic", ",", "payload", "=", "None", ",", "qos", "=", "0", ",", "retain", "=", "False", ")", ":", "#print \"PUBLISHING (\",topic,\"): \", payload", "payloadlen", "=", "len", "(", "payload", ")", "if", "topic", "is", "None", "or", "qos", "<", "0", "or", "qos", ">", "2", ":", "print", "\"PUBLISH:err inval\"", "return", "NC", ".", "ERR_INVAL", "#payloadlen <= 250MB", "if", "payloadlen", ">", "(", "250", "*", "1024", "*", "1204", ")", ":", "self", ".", "logger", ".", "error", "(", "\"PUBLISH:err payload len:%d\"", ",", "payloadlen", ")", "return", "NC", ".", "ERR_PAYLOAD_SIZE", "#wildcard check : TODO", "mid", "=", "self", ".", "mid_generate", "(", ")", "if", "qos", "in", "(", "0", ",", "1", ",", "2", ")", ":", "return", "self", ".", "send_publish", "(", "mid", ",", "topic", ",", "payload", ",", "qos", ",", "retain", ",", "False", ")", "else", ":", "self", ".", "logger", ".", "error", "(", "\"Unsupport QoS= %d\"", ",", "qos", ")", "return", "NC", ".", "ERR_NOT_SUPPORTED" ]
Publish some payload to server.
[ "Publish", "some", "payload", "to", "server", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L278-L300
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_connack
def handle_connack(self): """Handle incoming CONNACK command.""" self.logger.info("CONNACK reveived") ret, flags = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: self.logger.error("error read byte") return ret # useful for v3.1.1 only session_present = flags & 0x01 ret, retcode = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: return ret evt = event.EventConnack(retcode, session_present) self.push_event(evt) if retcode == NC.CONNECT_ACCEPTED: self.state = NC.CS_CONNECTED return NC.ERR_SUCCESS elif retcode >= 1 and retcode <= 5: return NC.ERR_CONN_REFUSED else: return NC.ERR_PROTOCOL
python
def handle_connack(self): """Handle incoming CONNACK command.""" self.logger.info("CONNACK reveived") ret, flags = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: self.logger.error("error read byte") return ret # useful for v3.1.1 only session_present = flags & 0x01 ret, retcode = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: return ret evt = event.EventConnack(retcode, session_present) self.push_event(evt) if retcode == NC.CONNECT_ACCEPTED: self.state = NC.CS_CONNECTED return NC.ERR_SUCCESS elif retcode >= 1 and retcode <= 5: return NC.ERR_CONN_REFUSED else: return NC.ERR_PROTOCOL
[ "def", "handle_connack", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"CONNACK reveived\"", ")", "ret", ",", "flags", "=", "self", ".", "in_packet", ".", "read_byte", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "self", ".", "logger", ".", "error", "(", "\"error read byte\"", ")", "return", "ret", "# useful for v3.1.1 only", "session_present", "=", "flags", "&", "0x01", "ret", ",", "retcode", "=", "self", ".", "in_packet", ".", "read_byte", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "evt", "=", "event", ".", "EventConnack", "(", "retcode", ",", "session_present", ")", "self", ".", "push_event", "(", "evt", ")", "if", "retcode", "==", "NC", ".", "CONNECT_ACCEPTED", ":", "self", ".", "state", "=", "NC", ".", "CS_CONNECTED", "return", "NC", ".", "ERR_SUCCESS", "elif", "retcode", ">=", "1", "and", "retcode", "<=", "5", ":", "return", "NC", ".", "ERR_CONN_REFUSED", "else", ":", "return", "NC", ".", "ERR_PROTOCOL" ]
Handle incoming CONNACK command.
[ "Handle", "incoming", "CONNACK", "command", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L302-L327
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_pingresp
def handle_pingresp(self): """Handle incoming PINGRESP packet.""" self.logger.debug("PINGRESP received") self.push_event(event.EventPingResp()) return NC.ERR_SUCCESS
python
def handle_pingresp(self): """Handle incoming PINGRESP packet.""" self.logger.debug("PINGRESP received") self.push_event(event.EventPingResp()) return NC.ERR_SUCCESS
[ "def", "handle_pingresp", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"PINGRESP received\"", ")", "self", ".", "push_event", "(", "event", ".", "EventPingResp", "(", ")", ")", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming PINGRESP packet.
[ "Handle", "incoming", "PINGRESP", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L329-L333
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_suback
def handle_suback(self): """Handle incoming SUBACK packet.""" self.logger.info("SUBACK received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret qos_count = self.in_packet.remaining_length - self.in_packet.pos granted_qos = bytearray(qos_count) if granted_qos is None: return NC.ERR_NO_MEM i = 0 while self.in_packet.pos < self.in_packet.remaining_length: ret, byte = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: granted_qos = None return ret granted_qos[i] = byte i += 1 evt = event.EventSuback(mid, list(granted_qos)) self.push_event(evt) granted_qos = None return NC.ERR_SUCCESS
python
def handle_suback(self): """Handle incoming SUBACK packet.""" self.logger.info("SUBACK received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret qos_count = self.in_packet.remaining_length - self.in_packet.pos granted_qos = bytearray(qos_count) if granted_qos is None: return NC.ERR_NO_MEM i = 0 while self.in_packet.pos < self.in_packet.remaining_length: ret, byte = self.in_packet.read_byte() if ret != NC.ERR_SUCCESS: granted_qos = None return ret granted_qos[i] = byte i += 1 evt = event.EventSuback(mid, list(granted_qos)) self.push_event(evt) granted_qos = None return NC.ERR_SUCCESS
[ "def", "handle_suback", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"SUBACK received\"", ")", "ret", ",", "mid", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "qos_count", "=", "self", ".", "in_packet", ".", "remaining_length", "-", "self", ".", "in_packet", ".", "pos", "granted_qos", "=", "bytearray", "(", "qos_count", ")", "if", "granted_qos", "is", "None", ":", "return", "NC", ".", "ERR_NO_MEM", "i", "=", "0", "while", "self", ".", "in_packet", ".", "pos", "<", "self", ".", "in_packet", ".", "remaining_length", ":", "ret", ",", "byte", "=", "self", ".", "in_packet", ".", "read_byte", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "granted_qos", "=", "None", "return", "ret", "granted_qos", "[", "i", "]", "=", "byte", "i", "+=", "1", "evt", "=", "event", ".", "EventSuback", "(", "mid", ",", "list", "(", "granted_qos", ")", ")", "self", ".", "push_event", "(", "evt", ")", "granted_qos", "=", "None", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming SUBACK packet.
[ "Handle", "incoming", "SUBACK", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L335-L367
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_unsuback
def handle_unsuback(self): """Handle incoming UNSUBACK packet.""" self.logger.info("UNSUBACK received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventUnsuback(mid) self.push_event(evt) return NC.ERR_SUCCESS
python
def handle_unsuback(self): """Handle incoming UNSUBACK packet.""" self.logger.info("UNSUBACK received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventUnsuback(mid) self.push_event(evt) return NC.ERR_SUCCESS
[ "def", "handle_unsuback", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"UNSUBACK received\"", ")", "ret", ",", "mid", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "evt", "=", "event", ".", "EventUnsuback", "(", "mid", ")", "self", ".", "push_event", "(", "evt", ")", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming UNSUBACK packet.
[ "Handle", "incoming", "UNSUBACK", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L369-L381
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_publish
def handle_publish(self): """Handle incoming PUBLISH packet.""" self.logger.debug("PUBLISH received") header = self.in_packet.command message = NyamukMsgAll() message.direction = NC.DIRECTION_IN message.dup = (header & 0x08) >> 3 message.msg.qos = (header & 0x06) >> 1 message.msg.retain = (header & 0x01) ret, ba_data = self.in_packet.read_string() message.msg.topic = ba_data.decode('utf8') if ret != NC.ERR_SUCCESS: return ret #fix_sub_topic TODO if message.msg.qos > 0: ret, word = self.in_packet.read_uint16() message.msg.mid = word if ret != NC.ERR_SUCCESS: return ret message.msg.payloadlen = self.in_packet.remaining_length - self.in_packet.pos if message.msg.payloadlen > 0: ret, message.msg.payload = self.in_packet.read_bytes(message.msg.payloadlen) if ret != NC.ERR_SUCCESS: return ret self.logger.debug("Received PUBLISH(dup = %d,qos=%d,retain=%s", message.dup, message.msg.qos, message.msg.retain) self.logger.debug("\tmid=%d, topic=%s, payloadlen=%d", message.msg.mid, message.msg.topic, message.msg.payloadlen) message.timestamp = time.time() qos = message.msg.qos if qos in (0,1,2): evt = event.EventPublish(message.msg) self.push_event(evt) return NC.ERR_SUCCESS else: return NC.ERR_PROTOCOL return NC.ERR_SUCCESS
python
def handle_publish(self): """Handle incoming PUBLISH packet.""" self.logger.debug("PUBLISH received") header = self.in_packet.command message = NyamukMsgAll() message.direction = NC.DIRECTION_IN message.dup = (header & 0x08) >> 3 message.msg.qos = (header & 0x06) >> 1 message.msg.retain = (header & 0x01) ret, ba_data = self.in_packet.read_string() message.msg.topic = ba_data.decode('utf8') if ret != NC.ERR_SUCCESS: return ret #fix_sub_topic TODO if message.msg.qos > 0: ret, word = self.in_packet.read_uint16() message.msg.mid = word if ret != NC.ERR_SUCCESS: return ret message.msg.payloadlen = self.in_packet.remaining_length - self.in_packet.pos if message.msg.payloadlen > 0: ret, message.msg.payload = self.in_packet.read_bytes(message.msg.payloadlen) if ret != NC.ERR_SUCCESS: return ret self.logger.debug("Received PUBLISH(dup = %d,qos=%d,retain=%s", message.dup, message.msg.qos, message.msg.retain) self.logger.debug("\tmid=%d, topic=%s, payloadlen=%d", message.msg.mid, message.msg.topic, message.msg.payloadlen) message.timestamp = time.time() qos = message.msg.qos if qos in (0,1,2): evt = event.EventPublish(message.msg) self.push_event(evt) return NC.ERR_SUCCESS else: return NC.ERR_PROTOCOL return NC.ERR_SUCCESS
[ "def", "handle_publish", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"PUBLISH received\"", ")", "header", "=", "self", ".", "in_packet", ".", "command", "message", "=", "NyamukMsgAll", "(", ")", "message", ".", "direction", "=", "NC", ".", "DIRECTION_IN", "message", ".", "dup", "=", "(", "header", "&", "0x08", ")", ">>", "3", "message", ".", "msg", ".", "qos", "=", "(", "header", "&", "0x06", ")", ">>", "1", "message", ".", "msg", ".", "retain", "=", "(", "header", "&", "0x01", ")", "ret", ",", "ba_data", "=", "self", ".", "in_packet", ".", "read_string", "(", ")", "message", ".", "msg", ".", "topic", "=", "ba_data", ".", "decode", "(", "'utf8'", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "#fix_sub_topic TODO", "if", "message", ".", "msg", ".", "qos", ">", "0", ":", "ret", ",", "word", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "message", ".", "msg", ".", "mid", "=", "word", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "message", ".", "msg", ".", "payloadlen", "=", "self", ".", "in_packet", ".", "remaining_length", "-", "self", ".", "in_packet", ".", "pos", "if", "message", ".", "msg", ".", "payloadlen", ">", "0", ":", "ret", ",", "message", ".", "msg", ".", "payload", "=", "self", ".", "in_packet", ".", "read_bytes", "(", "message", ".", "msg", ".", "payloadlen", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "self", ".", "logger", ".", "debug", "(", "\"Received PUBLISH(dup = %d,qos=%d,retain=%s\"", ",", "message", ".", "dup", ",", "message", ".", "msg", ".", "qos", ",", "message", ".", "msg", ".", "retain", ")", "self", ".", "logger", ".", "debug", "(", "\"\\tmid=%d, topic=%s, payloadlen=%d\"", ",", "message", ".", "msg", ".", "mid", ",", "message", ".", "msg", ".", "topic", ",", "message", ".", "msg", ".", "payloadlen", ")", "message", ".", "timestamp", "=", "time", ".", "time", "(", ")", "qos", "=", "message", ".", "msg", ".", "qos", "if", "qos", "in", "(", "0", ",", "1", ",", "2", ")", ":", "evt", "=", "event", ".", "EventPublish", "(", "message", ".", "msg", ")", "self", ".", "push_event", "(", "evt", ")", "return", "NC", ".", "ERR_SUCCESS", "else", ":", "return", "NC", ".", "ERR_PROTOCOL", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming PUBLISH packet.
[ "Handle", "incoming", "PUBLISH", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L388-L436
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.send_publish
def send_publish(self, mid, topic, payload, qos, retain, dup): """Send PUBLISH.""" self.logger.debug("Send PUBLISH") if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN #NOTE: payload may be any kind of data # yet if it is a unicode string we utf8-encode it as convenience return self._do_send_publish(mid, utf8encode(topic), utf8encode(payload), qos, retain, dup)
python
def send_publish(self, mid, topic, payload, qos, retain, dup): """Send PUBLISH.""" self.logger.debug("Send PUBLISH") if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN #NOTE: payload may be any kind of data # yet if it is a unicode string we utf8-encode it as convenience return self._do_send_publish(mid, utf8encode(topic), utf8encode(payload), qos, retain, dup)
[ "def", "send_publish", "(", "self", ",", "mid", ",", "topic", ",", "payload", ",", "qos", ",", "retain", ",", "dup", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Send PUBLISH\"", ")", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOCKET", ":", "return", "NC", ".", "ERR_NO_CONN", "#NOTE: payload may be any kind of data", "# yet if it is a unicode string we utf8-encode it as convenience", "return", "self", ".", "_do_send_publish", "(", "mid", ",", "utf8encode", "(", "topic", ")", ",", "utf8encode", "(", "payload", ")", ",", "qos", ",", "retain", ",", "dup", ")" ]
Send PUBLISH.
[ "Send", "PUBLISH", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L438-L446
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_puback
def handle_puback(self): """Handle incoming PUBACK packet.""" self.logger.info("PUBACK received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPuback(mid) self.push_event(evt) return NC.ERR_SUCCESS
python
def handle_puback(self): """Handle incoming PUBACK packet.""" self.logger.info("PUBACK received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPuback(mid) self.push_event(evt) return NC.ERR_SUCCESS
[ "def", "handle_puback", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"PUBACK received\"", ")", "ret", ",", "mid", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "evt", "=", "event", ".", "EventPuback", "(", "mid", ")", "self", ".", "push_event", "(", "evt", ")", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming PUBACK packet.
[ "Handle", "incoming", "PUBACK", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L455-L467
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_pubrec
def handle_pubrec(self): """Handle incoming PUBREC packet.""" self.logger.info("PUBREC received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPubrec(mid) self.push_event(evt) return NC.ERR_SUCCESS
python
def handle_pubrec(self): """Handle incoming PUBREC packet.""" self.logger.info("PUBREC received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPubrec(mid) self.push_event(evt) return NC.ERR_SUCCESS
[ "def", "handle_pubrec", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"PUBREC received\"", ")", "ret", ",", "mid", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "evt", "=", "event", ".", "EventPubrec", "(", "mid", ")", "self", ".", "push_event", "(", "evt", ")", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming PUBREC packet.
[ "Handle", "incoming", "PUBREC", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L469-L481
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_pubrel
def handle_pubrel(self): """Handle incoming PUBREL packet.""" self.logger.info("PUBREL received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPubrel(mid) self.push_event(evt) return NC.ERR_SUCCESS
python
def handle_pubrel(self): """Handle incoming PUBREL packet.""" self.logger.info("PUBREL received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPubrel(mid) self.push_event(evt) return NC.ERR_SUCCESS
[ "def", "handle_pubrel", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"PUBREL received\"", ")", "ret", ",", "mid", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "evt", "=", "event", ".", "EventPubrel", "(", "mid", ")", "self", ".", "push_event", "(", "evt", ")", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming PUBREL packet.
[ "Handle", "incoming", "PUBREL", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L483-L495
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.handle_pubcomp
def handle_pubcomp(self): """Handle incoming PUBCOMP packet.""" self.logger.info("PUBCOMP received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPubcomp(mid) self.push_event(evt) return NC.ERR_SUCCESS
python
def handle_pubcomp(self): """Handle incoming PUBCOMP packet.""" self.logger.info("PUBCOMP received") ret, mid = self.in_packet.read_uint16() if ret != NC.ERR_SUCCESS: return ret evt = event.EventPubcomp(mid) self.push_event(evt) return NC.ERR_SUCCESS
[ "def", "handle_pubcomp", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"PUBCOMP received\"", ")", "ret", ",", "mid", "=", "self", ".", "in_packet", ".", "read_uint16", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "evt", "=", "event", ".", "EventPubcomp", "(", "mid", ")", "self", ".", "push_event", "(", "evt", ")", "return", "NC", ".", "ERR_SUCCESS" ]
Handle incoming PUBCOMP packet.
[ "Handle", "incoming", "PUBCOMP", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L497-L509
iwanbk/nyamuk
nyamuk/nyamuk.py
Nyamuk.pubrec
def pubrec(self, mid): """Send PUBREC response to server.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("Send PUBREC (msgid=%s)", mid) pkt = MqttPkt() pkt.command = NC.CMD_PUBREC pkt.remaining_length = 2 ret = pkt.alloc() if ret != NC.ERR_SUCCESS: return ret #variable header: acknowledged message id pkt.write_uint16(mid) return self.packet_queue(pkt)
python
def pubrec(self, mid): """Send PUBREC response to server.""" if self.sock == NC.INVALID_SOCKET: return NC.ERR_NO_CONN self.logger.info("Send PUBREC (msgid=%s)", mid) pkt = MqttPkt() pkt.command = NC.CMD_PUBREC pkt.remaining_length = 2 ret = pkt.alloc() if ret != NC.ERR_SUCCESS: return ret #variable header: acknowledged message id pkt.write_uint16(mid) return self.packet_queue(pkt)
[ "def", "pubrec", "(", "self", ",", "mid", ")", ":", "if", "self", ".", "sock", "==", "NC", ".", "INVALID_SOCKET", ":", "return", "NC", ".", "ERR_NO_CONN", "self", ".", "logger", ".", "info", "(", "\"Send PUBREC (msgid=%s)\"", ",", "mid", ")", "pkt", "=", "MqttPkt", "(", ")", "pkt", ".", "command", "=", "NC", ".", "CMD_PUBREC", "pkt", ".", "remaining_length", "=", "2", "ret", "=", "pkt", ".", "alloc", "(", ")", "if", "ret", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "ret", "#variable header: acknowledged message id", "pkt", ".", "write_uint16", "(", "mid", ")", "return", "self", ".", "packet_queue", "(", "pkt", ")" ]
Send PUBREC response to server.
[ "Send", "PUBREC", "response", "to", "server", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk.py#L552-L570
iwanbk/nyamuk
nyamuk/nyamuk_net.py
connect
def connect(sock, addr): """Connect to some addr.""" try: sock.connect(addr) except ssl.SSLError as e: return (ssl.SSLError, e.strerror if e.strerror else e.message) except socket.herror as (_, msg): return (socket.herror, msg) except socket.gaierror as (_, msg): return (socket.gaierror, msg) except socket.timeout: return (socket.timeout, "timeout") except socket.error as e: return (socket.error, e.strerror if e.strerror else e.message) return None
python
def connect(sock, addr): """Connect to some addr.""" try: sock.connect(addr) except ssl.SSLError as e: return (ssl.SSLError, e.strerror if e.strerror else e.message) except socket.herror as (_, msg): return (socket.herror, msg) except socket.gaierror as (_, msg): return (socket.gaierror, msg) except socket.timeout: return (socket.timeout, "timeout") except socket.error as e: return (socket.error, e.strerror if e.strerror else e.message) return None
[ "def", "connect", "(", "sock", ",", "addr", ")", ":", "try", ":", "sock", ".", "connect", "(", "addr", ")", "except", "ssl", ".", "SSLError", "as", "e", ":", "return", "(", "ssl", ".", "SSLError", ",", "e", ".", "strerror", "if", "e", ".", "strerror", "else", "e", ".", "message", ")", "except", "socket", ".", "herror", "as", "(", "_", ",", "msg", ")", ":", "return", "(", "socket", ".", "herror", ",", "msg", ")", "except", "socket", ".", "gaierror", "as", "(", "_", ",", "msg", ")", ":", "return", "(", "socket", ".", "gaierror", ",", "msg", ")", "except", "socket", ".", "timeout", ":", "return", "(", "socket", ".", "timeout", ",", "\"timeout\"", ")", "except", "socket", ".", "error", "as", "e", ":", "return", "(", "socket", ".", "error", ",", "e", ".", "strerror", "if", "e", ".", "strerror", "else", "e", ".", "message", ")", "return", "None" ]
Connect to some addr.
[ "Connect", "to", "some", "addr", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk_net.py#L17-L32
iwanbk/nyamuk
nyamuk/nyamuk_net.py
read
def read(sock, count): """Read from socket and return it's byte array representation. count = number of bytes to read """ data = None try: data = sock.recv(count) except ssl.SSLError as e: return data, e.errno, e.strerror if strerror else e.message except socket.herror as (errnum, errmsg): return data, errnum, errmsg except socket.gaierror as (errnum, errmsg): return data, errnum, errmsg except socket.timeout: return data, errno.ETIMEDOUT, "Connection timed out" except socket.error as (errnum, errmsg): return data, errnum, errmsg ba_data = bytearray(data) if len(ba_data) == 0: return ba_data, errno.ECONNRESET, "Connection closed" return ba_data, 0, ""
python
def read(sock, count): """Read from socket and return it's byte array representation. count = number of bytes to read """ data = None try: data = sock.recv(count) except ssl.SSLError as e: return data, e.errno, e.strerror if strerror else e.message except socket.herror as (errnum, errmsg): return data, errnum, errmsg except socket.gaierror as (errnum, errmsg): return data, errnum, errmsg except socket.timeout: return data, errno.ETIMEDOUT, "Connection timed out" except socket.error as (errnum, errmsg): return data, errnum, errmsg ba_data = bytearray(data) if len(ba_data) == 0: return ba_data, errno.ECONNRESET, "Connection closed" return ba_data, 0, ""
[ "def", "read", "(", "sock", ",", "count", ")", ":", "data", "=", "None", "try", ":", "data", "=", "sock", ".", "recv", "(", "count", ")", "except", "ssl", ".", "SSLError", "as", "e", ":", "return", "data", ",", "e", ".", "errno", ",", "e", ".", "strerror", "if", "strerror", "else", "e", ".", "message", "except", "socket", ".", "herror", "as", "(", "errnum", ",", "errmsg", ")", ":", "return", "data", ",", "errnum", ",", "errmsg", "except", "socket", ".", "gaierror", "as", "(", "errnum", ",", "errmsg", ")", ":", "return", "data", ",", "errnum", ",", "errmsg", "except", "socket", ".", "timeout", ":", "return", "data", ",", "errno", ".", "ETIMEDOUT", ",", "\"Connection timed out\"", "except", "socket", ".", "error", "as", "(", "errnum", ",", "errmsg", ")", ":", "return", "data", ",", "errnum", ",", "errmsg", "ba_data", "=", "bytearray", "(", "data", ")", "if", "len", "(", "ba_data", ")", "==", "0", ":", "return", "ba_data", ",", "errno", ".", "ECONNRESET", ",", "\"Connection closed\"", "return", "ba_data", ",", "0", ",", "\"\"" ]
Read from socket and return it's byte array representation. count = number of bytes to read
[ "Read", "from", "socket", "and", "return", "it", "s", "byte", "array", "representation", ".", "count", "=", "number", "of", "bytes", "to", "read" ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk_net.py#L34-L58
iwanbk/nyamuk
nyamuk/nyamuk_net.py
write
def write(sock, payload): """Write payload to socket.""" try: length = sock.send(payload) except ssl.SSLError as e: return -1, (ssl.SSLError, e.strerror if strerror else e.message) except socket.herror as (_, msg): return -1, (socket.error, msg) except socket.gaierror as (_, msg): return -1, (socket.gaierror, msg) except socket.timeout: return -1, (socket.timeout, "timeout") except socket.error as (_, msg): return -1, (socket.error, msg) return length, None
python
def write(sock, payload): """Write payload to socket.""" try: length = sock.send(payload) except ssl.SSLError as e: return -1, (ssl.SSLError, e.strerror if strerror else e.message) except socket.herror as (_, msg): return -1, (socket.error, msg) except socket.gaierror as (_, msg): return -1, (socket.gaierror, msg) except socket.timeout: return -1, (socket.timeout, "timeout") except socket.error as (_, msg): return -1, (socket.error, msg) return length, None
[ "def", "write", "(", "sock", ",", "payload", ")", ":", "try", ":", "length", "=", "sock", ".", "send", "(", "payload", ")", "except", "ssl", ".", "SSLError", "as", "e", ":", "return", "-", "1", ",", "(", "ssl", ".", "SSLError", ",", "e", ".", "strerror", "if", "strerror", "else", "e", ".", "message", ")", "except", "socket", ".", "herror", "as", "(", "_", ",", "msg", ")", ":", "return", "-", "1", ",", "(", "socket", ".", "error", ",", "msg", ")", "except", "socket", ".", "gaierror", "as", "(", "_", ",", "msg", ")", ":", "return", "-", "1", ",", "(", "socket", ".", "gaierror", ",", "msg", ")", "except", "socket", ".", "timeout", ":", "return", "-", "1", ",", "(", "socket", ".", "timeout", ",", "\"timeout\"", ")", "except", "socket", ".", "error", "as", "(", "_", ",", "msg", ")", ":", "return", "-", "1", ",", "(", "socket", ".", "error", ",", "msg", ")", "return", "length", ",", "None" ]
Write payload to socket.
[ "Write", "payload", "to", "socket", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/nyamuk_net.py#L60-L75
iwanbk/nyamuk
nyamuk/mqtt_pkt.py
MqttPkt.dump
def dump(self): """Print packet content.""" print "-----MqttPkt------" print "command = ", self.command print "have_remaining = ", self.have_remaining print "remaining_count = ", self.remaining_count print "mid = ", self.mid print "remaining_mult = ", self.remaining_mult print "remaining_length = ", self.remaining_length print "packet_length = ", self.packet_length print "to_process = ", self.to_process print "pos = ", self.pos print "payload = ", self.payload print "------------------"
python
def dump(self): """Print packet content.""" print "-----MqttPkt------" print "command = ", self.command print "have_remaining = ", self.have_remaining print "remaining_count = ", self.remaining_count print "mid = ", self.mid print "remaining_mult = ", self.remaining_mult print "remaining_length = ", self.remaining_length print "packet_length = ", self.packet_length print "to_process = ", self.to_process print "pos = ", self.pos print "payload = ", self.payload print "------------------"
[ "def", "dump", "(", "self", ")", ":", "print", "\"-----MqttPkt------\"", "print", "\"command = \"", ",", "self", ".", "command", "print", "\"have_remaining = \"", ",", "self", ".", "have_remaining", "print", "\"remaining_count = \"", ",", "self", ".", "remaining_count", "print", "\"mid = \"", ",", "self", ".", "mid", "print", "\"remaining_mult = \"", ",", "self", ".", "remaining_mult", "print", "\"remaining_length = \"", ",", "self", ".", "remaining_length", "print", "\"packet_length = \"", ",", "self", ".", "packet_length", "print", "\"to_process = \"", ",", "self", ".", "to_process", "print", "\"pos = \"", ",", "self", ".", "pos", "print", "\"payload = \"", ",", "self", ".", "payload", "print", "\"------------------\"" ]
Print packet content.
[ "Print", "packet", "content", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/mqtt_pkt.py#L32-L45
iwanbk/nyamuk
nyamuk/mqtt_pkt.py
MqttPkt.alloc
def alloc(self): """from _mosquitto_packet_alloc.""" byte = 0 remaining_bytes = bytearray(5) i = 0 remaining_length = self.remaining_length self.payload = None self.remaining_count = 0 loop_flag = True #self.dump() while loop_flag: byte = remaining_length % 128 remaining_length = remaining_length / 128 if remaining_length > 0: byte = byte | 0x80 remaining_bytes[self.remaining_count] = byte self.remaining_count += 1 if not (remaining_length > 0 and self.remaining_count < 5): loop_flag = False if self.remaining_count == 5: return NC.ERR_PAYLOAD_SIZE self.packet_length = self.remaining_length + 1 + self.remaining_count self.payload = bytearray(self.packet_length) self.payload[0] = self.command i = 0 while i < self.remaining_count: self.payload[i+1] = remaining_bytes[i] i += 1 self.pos = 1 + self.remaining_count return NC.ERR_SUCCESS
python
def alloc(self): """from _mosquitto_packet_alloc.""" byte = 0 remaining_bytes = bytearray(5) i = 0 remaining_length = self.remaining_length self.payload = None self.remaining_count = 0 loop_flag = True #self.dump() while loop_flag: byte = remaining_length % 128 remaining_length = remaining_length / 128 if remaining_length > 0: byte = byte | 0x80 remaining_bytes[self.remaining_count] = byte self.remaining_count += 1 if not (remaining_length > 0 and self.remaining_count < 5): loop_flag = False if self.remaining_count == 5: return NC.ERR_PAYLOAD_SIZE self.packet_length = self.remaining_length + 1 + self.remaining_count self.payload = bytearray(self.packet_length) self.payload[0] = self.command i = 0 while i < self.remaining_count: self.payload[i+1] = remaining_bytes[i] i += 1 self.pos = 1 + self.remaining_count return NC.ERR_SUCCESS
[ "def", "alloc", "(", "self", ")", ":", "byte", "=", "0", "remaining_bytes", "=", "bytearray", "(", "5", ")", "i", "=", "0", "remaining_length", "=", "self", ".", "remaining_length", "self", ".", "payload", "=", "None", "self", ".", "remaining_count", "=", "0", "loop_flag", "=", "True", "#self.dump()", "while", "loop_flag", ":", "byte", "=", "remaining_length", "%", "128", "remaining_length", "=", "remaining_length", "/", "128", "if", "remaining_length", ">", "0", ":", "byte", "=", "byte", "|", "0x80", "remaining_bytes", "[", "self", ".", "remaining_count", "]", "=", "byte", "self", ".", "remaining_count", "+=", "1", "if", "not", "(", "remaining_length", ">", "0", "and", "self", ".", "remaining_count", "<", "5", ")", ":", "loop_flag", "=", "False", "if", "self", ".", "remaining_count", "==", "5", ":", "return", "NC", ".", "ERR_PAYLOAD_SIZE", "self", ".", "packet_length", "=", "self", ".", "remaining_length", "+", "1", "+", "self", ".", "remaining_count", "self", ".", "payload", "=", "bytearray", "(", "self", ".", "packet_length", ")", "self", ".", "payload", "[", "0", "]", "=", "self", ".", "command", "i", "=", "0", "while", "i", "<", "self", ".", "remaining_count", ":", "self", ".", "payload", "[", "i", "+", "1", "]", "=", "remaining_bytes", "[", "i", "]", "i", "+=", "1", "self", ".", "pos", "=", "1", "+", "self", ".", "remaining_count", "return", "NC", ".", "ERR_SUCCESS" ]
from _mosquitto_packet_alloc.
[ "from", "_mosquitto_packet_alloc", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/mqtt_pkt.py#L47-L88
iwanbk/nyamuk
nyamuk/mqtt_pkt.py
MqttPkt.connect_build
def connect_build(self, nyamuk, keepalive, clean_session, retain = 0, dup = 0, version = 3): """Build packet for CONNECT command.""" will = 0; will_topic = None byte = 0 client_id = utf8encode(nyamuk.client_id) username = utf8encode(nyamuk.username) if nyamuk.username is not None else None password = utf8encode(nyamuk.password) if nyamuk.password is not None else None #payload len payload_len = 2 + len(client_id) if nyamuk.will is not None: will = 1 will_topic = utf8encode(nyamuk.will.topic) payload_len = payload_len + 2 + len(will_topic) + 2 + nyamuk.will.payloadlen if username is not None: payload_len = payload_len + 2 + len(username) if password != None: payload_len = payload_len + 2 + len(password) self.command = NC.CMD_CONNECT self.remaining_length = 12 + payload_len rc = self.alloc() if rc != NC.ERR_SUCCESS: return rc #var header self.write_string(getattr(NC, 'PROTOCOL_NAME_{0}'.format(version))) self.write_byte( getattr(NC, 'PROTOCOL_VERSION_{0}'.format(version))) byte = (clean_session & 0x1) << 1 if will: byte = byte | ((nyamuk.will.retain & 0x1) << 5) | ((nyamuk.will.qos & 0x3) << 3) | ((will & 0x1) << 2) if nyamuk.username is not None: byte = byte | 0x1 << 7 if nyamuk.password is not None: byte = byte | 0x1 << 6 self.write_byte(byte) self.write_uint16(keepalive) #payload self.write_string(client_id) if will: self.write_string(will_topic) self.write_string(nyamuk.will.payload) if username is not None: self.write_string(username) if password is not None: self.write_string(password) nyamuk.keep_alive = keepalive return NC.ERR_SUCCESS
python
def connect_build(self, nyamuk, keepalive, clean_session, retain = 0, dup = 0, version = 3): """Build packet for CONNECT command.""" will = 0; will_topic = None byte = 0 client_id = utf8encode(nyamuk.client_id) username = utf8encode(nyamuk.username) if nyamuk.username is not None else None password = utf8encode(nyamuk.password) if nyamuk.password is not None else None #payload len payload_len = 2 + len(client_id) if nyamuk.will is not None: will = 1 will_topic = utf8encode(nyamuk.will.topic) payload_len = payload_len + 2 + len(will_topic) + 2 + nyamuk.will.payloadlen if username is not None: payload_len = payload_len + 2 + len(username) if password != None: payload_len = payload_len + 2 + len(password) self.command = NC.CMD_CONNECT self.remaining_length = 12 + payload_len rc = self.alloc() if rc != NC.ERR_SUCCESS: return rc #var header self.write_string(getattr(NC, 'PROTOCOL_NAME_{0}'.format(version))) self.write_byte( getattr(NC, 'PROTOCOL_VERSION_{0}'.format(version))) byte = (clean_session & 0x1) << 1 if will: byte = byte | ((nyamuk.will.retain & 0x1) << 5) | ((nyamuk.will.qos & 0x3) << 3) | ((will & 0x1) << 2) if nyamuk.username is not None: byte = byte | 0x1 << 7 if nyamuk.password is not None: byte = byte | 0x1 << 6 self.write_byte(byte) self.write_uint16(keepalive) #payload self.write_string(client_id) if will: self.write_string(will_topic) self.write_string(nyamuk.will.payload) if username is not None: self.write_string(username) if password is not None: self.write_string(password) nyamuk.keep_alive = keepalive return NC.ERR_SUCCESS
[ "def", "connect_build", "(", "self", ",", "nyamuk", ",", "keepalive", ",", "clean_session", ",", "retain", "=", "0", ",", "dup", "=", "0", ",", "version", "=", "3", ")", ":", "will", "=", "0", "will_topic", "=", "None", "byte", "=", "0", "client_id", "=", "utf8encode", "(", "nyamuk", ".", "client_id", ")", "username", "=", "utf8encode", "(", "nyamuk", ".", "username", ")", "if", "nyamuk", ".", "username", "is", "not", "None", "else", "None", "password", "=", "utf8encode", "(", "nyamuk", ".", "password", ")", "if", "nyamuk", ".", "password", "is", "not", "None", "else", "None", "#payload len", "payload_len", "=", "2", "+", "len", "(", "client_id", ")", "if", "nyamuk", ".", "will", "is", "not", "None", ":", "will", "=", "1", "will_topic", "=", "utf8encode", "(", "nyamuk", ".", "will", ".", "topic", ")", "payload_len", "=", "payload_len", "+", "2", "+", "len", "(", "will_topic", ")", "+", "2", "+", "nyamuk", ".", "will", ".", "payloadlen", "if", "username", "is", "not", "None", ":", "payload_len", "=", "payload_len", "+", "2", "+", "len", "(", "username", ")", "if", "password", "!=", "None", ":", "payload_len", "=", "payload_len", "+", "2", "+", "len", "(", "password", ")", "self", ".", "command", "=", "NC", ".", "CMD_CONNECT", "self", ".", "remaining_length", "=", "12", "+", "payload_len", "rc", "=", "self", ".", "alloc", "(", ")", "if", "rc", "!=", "NC", ".", "ERR_SUCCESS", ":", "return", "rc", "#var header", "self", ".", "write_string", "(", "getattr", "(", "NC", ",", "'PROTOCOL_NAME_{0}'", ".", "format", "(", "version", ")", ")", ")", "self", ".", "write_byte", "(", "getattr", "(", "NC", ",", "'PROTOCOL_VERSION_{0}'", ".", "format", "(", "version", ")", ")", ")", "byte", "=", "(", "clean_session", "&", "0x1", ")", "<<", "1", "if", "will", ":", "byte", "=", "byte", "|", "(", "(", "nyamuk", ".", "will", ".", "retain", "&", "0x1", ")", "<<", "5", ")", "|", "(", "(", "nyamuk", ".", "will", ".", "qos", "&", "0x3", ")", "<<", "3", ")", "|", "(", "(", "will", "&", "0x1", ")", "<<", "2", ")", "if", "nyamuk", ".", "username", "is", "not", "None", ":", "byte", "=", "byte", "|", "0x1", "<<", "7", "if", "nyamuk", ".", "password", "is", "not", "None", ":", "byte", "=", "byte", "|", "0x1", "<<", "6", "self", ".", "write_byte", "(", "byte", ")", "self", ".", "write_uint16", "(", "keepalive", ")", "#payload", "self", ".", "write_string", "(", "client_id", ")", "if", "will", ":", "self", ".", "write_string", "(", "will_topic", ")", "self", ".", "write_string", "(", "nyamuk", ".", "will", ".", "payload", ")", "if", "username", "is", "not", "None", ":", "self", ".", "write_string", "(", "username", ")", "if", "password", "is", "not", "None", ":", "self", ".", "write_string", "(", "password", ")", "nyamuk", ".", "keep_alive", "=", "keepalive", "return", "NC", ".", "ERR_SUCCESS" ]
Build packet for CONNECT command.
[ "Build", "packet", "for", "CONNECT", "command", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/mqtt_pkt.py#L100-L159
iwanbk/nyamuk
nyamuk/mqtt_pkt.py
MqttPkt.write_string
def write_string(self, string): """Write a string to this packet.""" self.write_uint16(len(string)) self.write_bytes(string, len(string))
python
def write_string(self, string): """Write a string to this packet.""" self.write_uint16(len(string)) self.write_bytes(string, len(string))
[ "def", "write_string", "(", "self", ",", "string", ")", ":", "self", ".", "write_uint16", "(", "len", "(", "string", ")", ")", "self", ".", "write_bytes", "(", "string", ",", "len", "(", "string", ")", ")" ]
Write a string to this packet.
[ "Write", "a", "string", "to", "this", "packet", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/mqtt_pkt.py#L161-L164
iwanbk/nyamuk
nyamuk/mqtt_pkt.py
MqttPkt.write_uint16
def write_uint16(self, word): """Write 2 bytes.""" self.write_byte(nyamuk_net.MOSQ_MSB(word)) self.write_byte(nyamuk_net.MOSQ_LSB(word))
python
def write_uint16(self, word): """Write 2 bytes.""" self.write_byte(nyamuk_net.MOSQ_MSB(word)) self.write_byte(nyamuk_net.MOSQ_LSB(word))
[ "def", "write_uint16", "(", "self", ",", "word", ")", ":", "self", ".", "write_byte", "(", "nyamuk_net", ".", "MOSQ_MSB", "(", "word", ")", ")", "self", ".", "write_byte", "(", "nyamuk_net", ".", "MOSQ_LSB", "(", "word", ")", ")" ]
Write 2 bytes.
[ "Write", "2", "bytes", "." ]
train
https://github.com/iwanbk/nyamuk/blob/ac4c6028de288a4c8e0b332ae16eae889deb643d/nyamuk/mqtt_pkt.py#L166-L169