repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat.get_temperature_from_pressure
def get_temperature_from_pressure(self): """ Returns the temperature in Celsius from the pressure sensor """ self._init_pressure() # Ensure pressure sensor is initialised temp = 0 data = self._pressure.pressureRead() if (data[2]): # Temp valid temp = data[3] return temp
python
def get_temperature_from_pressure(self): """ Returns the temperature in Celsius from the pressure sensor """ self._init_pressure() # Ensure pressure sensor is initialised temp = 0 data = self._pressure.pressureRead() if (data[2]): # Temp valid temp = data[3] return temp
[ "def", "get_temperature_from_pressure", "(", "self", ")", ":", "self", ".", "_init_pressure", "(", ")", "# Ensure pressure sensor is initialised", "temp", "=", "0", "data", "=", "self", ".", "_pressure", ".", "pressureRead", "(", ")", "if", "(", "data", "[", "...
Returns the temperature in Celsius from the pressure sensor
[ "Returns", "the", "temperature", "in", "Celsius", "from", "the", "pressure", "sensor" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L589-L599
train
198,300
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat.get_pressure
def get_pressure(self): """ Returns the pressure in Millibars """ self._init_pressure() # Ensure pressure sensor is initialised pressure = 0 data = self._pressure.pressureRead() if (data[0]): # Pressure valid pressure = data[1] return pressure
python
def get_pressure(self): """ Returns the pressure in Millibars """ self._init_pressure() # Ensure pressure sensor is initialised pressure = 0 data = self._pressure.pressureRead() if (data[0]): # Pressure valid pressure = data[1] return pressure
[ "def", "get_pressure", "(", "self", ")", ":", "self", ".", "_init_pressure", "(", ")", "# Ensure pressure sensor is initialised", "pressure", "=", "0", "data", "=", "self", ".", "_pressure", ".", "pressureRead", "(", ")", "if", "(", "data", "[", "0", "]", ...
Returns the pressure in Millibars
[ "Returns", "the", "pressure", "in", "Millibars" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L616-L626
train
198,301
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat._init_imu
def _init_imu(self): """ Internal. Initialises the IMU sensor via RTIMU """ if not self._imu_init: self._imu_init = self._imu.IMUInit() if self._imu_init: self._imu_poll_interval = self._imu.IMUGetPollInterval() * 0.001 # Enable everything on IMU self.set_imu_config(True, True, True) else: raise OSError('IMU Init Failed')
python
def _init_imu(self): """ Internal. Initialises the IMU sensor via RTIMU """ if not self._imu_init: self._imu_init = self._imu.IMUInit() if self._imu_init: self._imu_poll_interval = self._imu.IMUGetPollInterval() * 0.001 # Enable everything on IMU self.set_imu_config(True, True, True) else: raise OSError('IMU Init Failed')
[ "def", "_init_imu", "(", "self", ")", ":", "if", "not", "self", ".", "_imu_init", ":", "self", ".", "_imu_init", "=", "self", ".", "_imu", ".", "IMUInit", "(", ")", "if", "self", ".", "_imu_init", ":", "self", ".", "_imu_poll_interval", "=", "self", ...
Internal. Initialises the IMU sensor via RTIMU
[ "Internal", ".", "Initialises", "the", "IMU", "sensor", "via", "RTIMU" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L636-L648
train
198,302
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat._read_imu
def _read_imu(self): """ Internal. Tries to read the IMU sensor three times before giving up """ self._init_imu() # Ensure imu is initialised attempts = 0 success = False while not success and attempts < 3: success = self._imu.IMURead() attempts += 1 time.sleep(self._imu_poll_interval) return success
python
def _read_imu(self): """ Internal. Tries to read the IMU sensor three times before giving up """ self._init_imu() # Ensure imu is initialised attempts = 0 success = False while not success and attempts < 3: success = self._imu.IMURead() attempts += 1 time.sleep(self._imu_poll_interval) return success
[ "def", "_read_imu", "(", "self", ")", ":", "self", ".", "_init_imu", "(", ")", "# Ensure imu is initialised", "attempts", "=", "0", "success", "=", "False", "while", "not", "success", "and", "attempts", "<", "3", ":", "success", "=", "self", ".", "_imu", ...
Internal. Tries to read the IMU sensor three times before giving up
[ "Internal", ".", "Tries", "to", "read", "the", "IMU", "sensor", "three", "times", "before", "giving", "up" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L679-L694
train
198,303
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat._get_raw_data
def _get_raw_data(self, is_valid_key, data_key): """ Internal. Returns the specified raw data from the IMU when valid """ result = None if self._read_imu(): data = self._imu.getIMUData() if data[is_valid_key]: raw = data[data_key] result = { 'x': raw[0], 'y': raw[1], 'z': raw[2] } return result
python
def _get_raw_data(self, is_valid_key, data_key): """ Internal. Returns the specified raw data from the IMU when valid """ result = None if self._read_imu(): data = self._imu.getIMUData() if data[is_valid_key]: raw = data[data_key] result = { 'x': raw[0], 'y': raw[1], 'z': raw[2] } return result
[ "def", "_get_raw_data", "(", "self", ",", "is_valid_key", ",", "data_key", ")", ":", "result", "=", "None", "if", "self", ".", "_read_imu", "(", ")", ":", "data", "=", "self", ".", "_imu", ".", "getIMUData", "(", ")", "if", "data", "[", "is_valid_key",...
Internal. Returns the specified raw data from the IMU when valid
[ "Internal", ".", "Returns", "the", "specified", "raw", "data", "from", "the", "IMU", "when", "valid" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L696-L713
train
198,304
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat.get_orientation_radians
def get_orientation_radians(self): """ Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch, roll and yaw """ raw = self._get_raw_data('fusionPoseValid', 'fusionPose') if raw is not None: raw['roll'] = raw.pop('x') raw['pitch'] = raw.pop('y') raw['yaw'] = raw.pop('z') self._last_orientation = raw return deepcopy(self._last_orientation)
python
def get_orientation_radians(self): """ Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch, roll and yaw """ raw = self._get_raw_data('fusionPoseValid', 'fusionPose') if raw is not None: raw['roll'] = raw.pop('x') raw['pitch'] = raw.pop('y') raw['yaw'] = raw.pop('z') self._last_orientation = raw return deepcopy(self._last_orientation)
[ "def", "get_orientation_radians", "(", "self", ")", ":", "raw", "=", "self", ".", "_get_raw_data", "(", "'fusionPoseValid'", ",", "'fusionPose'", ")", "if", "raw", "is", "not", "None", ":", "raw", "[", "'roll'", "]", "=", "raw", ".", "pop", "(", "'x'", ...
Returns a dictionary object to represent the current orientation in radians using the aircraft principal axes of pitch, roll and yaw
[ "Returns", "a", "dictionary", "object", "to", "represent", "the", "current", "orientation", "in", "radians", "using", "the", "aircraft", "principal", "axes", "of", "pitch", "roll", "and", "yaw" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L715-L729
train
198,305
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat.get_orientation_degrees
def get_orientation_degrees(self): """ Returns a dictionary object to represent the current orientation in degrees, 0 to 360, using the aircraft principal axes of pitch, roll and yaw """ orientation = self.get_orientation_radians() for key, val in orientation.items(): deg = math.degrees(val) # Result is -180 to +180 orientation[key] = deg + 360 if deg < 0 else deg return orientation
python
def get_orientation_degrees(self): """ Returns a dictionary object to represent the current orientation in degrees, 0 to 360, using the aircraft principal axes of pitch, roll and yaw """ orientation = self.get_orientation_radians() for key, val in orientation.items(): deg = math.degrees(val) # Result is -180 to +180 orientation[key] = deg + 360 if deg < 0 else deg return orientation
[ "def", "get_orientation_degrees", "(", "self", ")", ":", "orientation", "=", "self", ".", "get_orientation_radians", "(", ")", "for", "key", ",", "val", "in", "orientation", ".", "items", "(", ")", ":", "deg", "=", "math", ".", "degrees", "(", "val", ")"...
Returns a dictionary object to represent the current orientation in degrees, 0 to 360, using the aircraft principal axes of pitch, roll and yaw
[ "Returns", "a", "dictionary", "object", "to", "represent", "the", "current", "orientation", "in", "degrees", "0", "to", "360", "using", "the", "aircraft", "principal", "axes", "of", "pitch", "roll", "and", "yaw" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L735-L746
train
198,306
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat.get_compass
def get_compass(self): """ Gets the direction of North from the magnetometer in degrees """ self.set_imu_config(True, False, False) orientation = self.get_orientation_degrees() if type(orientation) is dict and 'yaw' in orientation.keys(): return orientation['yaw'] else: return None
python
def get_compass(self): """ Gets the direction of North from the magnetometer in degrees """ self.set_imu_config(True, False, False) orientation = self.get_orientation_degrees() if type(orientation) is dict and 'yaw' in orientation.keys(): return orientation['yaw'] else: return None
[ "def", "get_compass", "(", "self", ")", ":", "self", ".", "set_imu_config", "(", "True", ",", "False", ",", "False", ")", "orientation", "=", "self", ".", "get_orientation_degrees", "(", ")", "if", "type", "(", "orientation", ")", "is", "dict", "and", "'...
Gets the direction of North from the magnetometer in degrees
[ "Gets", "the", "direction", "of", "North", "from", "the", "magnetometer", "in", "degrees" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L755-L765
train
198,307
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat.get_gyroscope_raw
def get_gyroscope_raw(self): """ Gyroscope x y z raw data in radians per second """ raw = self._get_raw_data('gyroValid', 'gyro') if raw is not None: self._last_gyro_raw = raw return deepcopy(self._last_gyro_raw)
python
def get_gyroscope_raw(self): """ Gyroscope x y z raw data in radians per second """ raw = self._get_raw_data('gyroValid', 'gyro') if raw is not None: self._last_gyro_raw = raw return deepcopy(self._last_gyro_raw)
[ "def", "get_gyroscope_raw", "(", "self", ")", ":", "raw", "=", "self", ".", "_get_raw_data", "(", "'gyroValid'", ",", "'gyro'", ")", "if", "raw", "is", "not", "None", ":", "self", ".", "_last_gyro_raw", "=", "raw", "return", "deepcopy", "(", "self", ".",...
Gyroscope x y z raw data in radians per second
[ "Gyroscope", "x", "y", "z", "raw", "data", "in", "radians", "per", "second" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L803-L813
train
198,308
RPi-Distro/python-sense-hat
sense_hat/sense_hat.py
SenseHat.get_accelerometer_raw
def get_accelerometer_raw(self): """ Accelerometer x y z raw data in Gs """ raw = self._get_raw_data('accelValid', 'accel') if raw is not None: self._last_accel_raw = raw return deepcopy(self._last_accel_raw)
python
def get_accelerometer_raw(self): """ Accelerometer x y z raw data in Gs """ raw = self._get_raw_data('accelValid', 'accel') if raw is not None: self._last_accel_raw = raw return deepcopy(self._last_accel_raw)
[ "def", "get_accelerometer_raw", "(", "self", ")", ":", "raw", "=", "self", ".", "_get_raw_data", "(", "'accelValid'", ",", "'accel'", ")", "if", "raw", "is", "not", "None", ":", "self", ".", "_last_accel_raw", "=", "raw", "return", "deepcopy", "(", "self",...
Accelerometer x y z raw data in Gs
[ "Accelerometer", "x", "y", "z", "raw", "data", "in", "Gs" ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/sense_hat.py#L839-L849
train
198,309
RPi-Distro/python-sense-hat
sense_hat/stick.py
SenseStick._stick_device
def _stick_device(self): """ Discovers the filename of the evdev device that represents the Sense HAT's joystick. """ for evdev in glob.glob('/sys/class/input/event*'): try: with io.open(os.path.join(evdev, 'device', 'name'), 'r') as f: if f.read().strip() == self.SENSE_HAT_EVDEV_NAME: return os.path.join('/dev', 'input', os.path.basename(evdev)) except IOError as e: if e.errno != errno.ENOENT: raise raise RuntimeError('unable to locate SenseHAT joystick device')
python
def _stick_device(self): """ Discovers the filename of the evdev device that represents the Sense HAT's joystick. """ for evdev in glob.glob('/sys/class/input/event*'): try: with io.open(os.path.join(evdev, 'device', 'name'), 'r') as f: if f.read().strip() == self.SENSE_HAT_EVDEV_NAME: return os.path.join('/dev', 'input', os.path.basename(evdev)) except IOError as e: if e.errno != errno.ENOENT: raise raise RuntimeError('unable to locate SenseHAT joystick device')
[ "def", "_stick_device", "(", "self", ")", ":", "for", "evdev", "in", "glob", ".", "glob", "(", "'/sys/class/input/event*'", ")", ":", "try", ":", "with", "io", ".", "open", "(", "os", ".", "path", ".", "join", "(", "evdev", ",", "'device'", ",", "'na...
Discovers the filename of the evdev device that represents the Sense HAT's joystick.
[ "Discovers", "the", "filename", "of", "the", "evdev", "device", "that", "represents", "the", "Sense", "HAT", "s", "joystick", "." ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/stick.py#L75-L88
train
198,310
RPi-Distro/python-sense-hat
sense_hat/stick.py
SenseStick._read
def _read(self): """ Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise. """ event = self._stick_file.read(self.EVENT_SIZE) (tv_sec, tv_usec, type, code, value) = struct.unpack(self.EVENT_FORMAT, event) if type == self.EV_KEY: return InputEvent( timestamp=tv_sec + (tv_usec / 1000000), direction={ self.KEY_UP: DIRECTION_UP, self.KEY_DOWN: DIRECTION_DOWN, self.KEY_LEFT: DIRECTION_LEFT, self.KEY_RIGHT: DIRECTION_RIGHT, self.KEY_ENTER: DIRECTION_MIDDLE, }[code], action={ self.STATE_PRESS: ACTION_PRESSED, self.STATE_RELEASE: ACTION_RELEASED, self.STATE_HOLD: ACTION_HELD, }[value]) else: return None
python
def _read(self): """ Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise. """ event = self._stick_file.read(self.EVENT_SIZE) (tv_sec, tv_usec, type, code, value) = struct.unpack(self.EVENT_FORMAT, event) if type == self.EV_KEY: return InputEvent( timestamp=tv_sec + (tv_usec / 1000000), direction={ self.KEY_UP: DIRECTION_UP, self.KEY_DOWN: DIRECTION_DOWN, self.KEY_LEFT: DIRECTION_LEFT, self.KEY_RIGHT: DIRECTION_RIGHT, self.KEY_ENTER: DIRECTION_MIDDLE, }[code], action={ self.STATE_PRESS: ACTION_PRESSED, self.STATE_RELEASE: ACTION_RELEASED, self.STATE_HOLD: ACTION_HELD, }[value]) else: return None
[ "def", "_read", "(", "self", ")", ":", "event", "=", "self", ".", "_stick_file", ".", "read", "(", "self", ".", "EVENT_SIZE", ")", "(", "tv_sec", ",", "tv_usec", ",", "type", ",", "code", ",", "value", ")", "=", "struct", ".", "unpack", "(", "self"...
Reads a single event from the joystick, blocking until one is available. Returns `None` if a non-key event was read, or an `InputEvent` tuple describing the event otherwise.
[ "Reads", "a", "single", "event", "from", "the", "joystick", "blocking", "until", "one", "is", "available", ".", "Returns", "None", "if", "a", "non", "-", "key", "event", "was", "read", "or", "an", "InputEvent", "tuple", "describing", "the", "event", "other...
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/stick.py#L90-L114
train
198,311
RPi-Distro/python-sense-hat
sense_hat/stick.py
SenseStick.wait_for_event
def wait_for_event(self, emptybuffer=False): """ Waits until a joystick event becomes available. Returns the event, as an `InputEvent` tuple. If *emptybuffer* is `True` (it defaults to `False`), any pending events will be thrown away first. This is most useful if you are only interested in "pressed" events. """ if emptybuffer: while self._wait(0): self._read() while self._wait(): event = self._read() if event: return event
python
def wait_for_event(self, emptybuffer=False): """ Waits until a joystick event becomes available. Returns the event, as an `InputEvent` tuple. If *emptybuffer* is `True` (it defaults to `False`), any pending events will be thrown away first. This is most useful if you are only interested in "pressed" events. """ if emptybuffer: while self._wait(0): self._read() while self._wait(): event = self._read() if event: return event
[ "def", "wait_for_event", "(", "self", ",", "emptybuffer", "=", "False", ")", ":", "if", "emptybuffer", ":", "while", "self", ".", "_wait", "(", "0", ")", ":", "self", ".", "_read", "(", ")", "while", "self", ".", "_wait", "(", ")", ":", "event", "=...
Waits until a joystick event becomes available. Returns the event, as an `InputEvent` tuple. If *emptybuffer* is `True` (it defaults to `False`), any pending events will be thrown away first. This is most useful if you are only interested in "pressed" events.
[ "Waits", "until", "a", "joystick", "event", "becomes", "available", ".", "Returns", "the", "event", "as", "an", "InputEvent", "tuple", "." ]
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/stick.py#L183-L198
train
198,312
RPi-Distro/python-sense-hat
sense_hat/stick.py
SenseStick.get_events
def get_events(self): """ Returns a list of all joystick events that have occurred since the last call to `get_events`. The list contains events in the order that they occurred. If no events have occurred in the intervening time, the result is an empty list. """ result = [] while self._wait(0): event = self._read() if event: result.append(event) return result
python
def get_events(self): """ Returns a list of all joystick events that have occurred since the last call to `get_events`. The list contains events in the order that they occurred. If no events have occurred in the intervening time, the result is an empty list. """ result = [] while self._wait(0): event = self._read() if event: result.append(event) return result
[ "def", "get_events", "(", "self", ")", ":", "result", "=", "[", "]", "while", "self", ".", "_wait", "(", "0", ")", ":", "event", "=", "self", ".", "_read", "(", ")", "if", "event", ":", "result", ".", "append", "(", "event", ")", "return", "resul...
Returns a list of all joystick events that have occurred since the last call to `get_events`. The list contains events in the order that they occurred. If no events have occurred in the intervening time, the result is an empty list.
[ "Returns", "a", "list", "of", "all", "joystick", "events", "that", "have", "occurred", "since", "the", "last", "call", "to", "get_events", ".", "The", "list", "contains", "events", "in", "the", "order", "that", "they", "occurred", ".", "If", "no", "events"...
9a37f0923ce8dbde69514c3b8d58d30de01c9ee7
https://github.com/RPi-Distro/python-sense-hat/blob/9a37f0923ce8dbde69514c3b8d58d30de01c9ee7/sense_hat/stick.py#L200-L212
train
198,313
miguelgrinberg/python-engineio
engineio/client.py
signal_handler
def signal_handler(sig, frame): """SIGINT handler. Disconnect all active clients and then invoke the original signal handler. """ for client in connected_clients[:]: if client.is_asyncio_based(): client.start_background_task(client.disconnect, abort=True) else: client.disconnect(abort=True) return original_signal_handler(sig, frame)
python
def signal_handler(sig, frame): """SIGINT handler. Disconnect all active clients and then invoke the original signal handler. """ for client in connected_clients[:]: if client.is_asyncio_based(): client.start_background_task(client.disconnect, abort=True) else: client.disconnect(abort=True) return original_signal_handler(sig, frame)
[ "def", "signal_handler", "(", "sig", ",", "frame", ")", ":", "for", "client", "in", "connected_clients", "[", ":", "]", ":", "if", "client", ".", "is_asyncio_based", "(", ")", ":", "client", ".", "start_background_task", "(", "client", ".", "disconnect", "...
SIGINT handler. Disconnect all active clients and then invoke the original signal handler.
[ "SIGINT", "handler", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/client.py#L31-L41
train
198,314
miguelgrinberg/python-engineio
engineio/client.py
Client.start_background_task
def start_background_task(self, target, *args, **kwargs): """Start a background task. This is a utility function that applications can use to start a background task. :param target: the target function to execute. :param args: arguments to pass to the function. :param kwargs: keyword arguments to pass to the function. This function returns an object compatible with the `Thread` class in the Python standard library. The `start()` method on this object is already called by this function. """ th = threading.Thread(target=target, args=args, kwargs=kwargs) th.start() return th
python
def start_background_task(self, target, *args, **kwargs): """Start a background task. This is a utility function that applications can use to start a background task. :param target: the target function to execute. :param args: arguments to pass to the function. :param kwargs: keyword arguments to pass to the function. This function returns an object compatible with the `Thread` class in the Python standard library. The `start()` method on this object is already called by this function. """ th = threading.Thread(target=target, args=args, kwargs=kwargs) th.start() return th
[ "def", "start_background_task", "(", "self", ",", "target", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "th", "=", "threading", ".", "Thread", "(", "target", "=", "target", ",", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")", "th", ...
Start a background task. This is a utility function that applications can use to start a background task. :param target: the target function to execute. :param args: arguments to pass to the function. :param kwargs: keyword arguments to pass to the function. This function returns an object compatible with the `Thread` class in the Python standard library. The `start()` method on this object is already called by this function.
[ "Start", "a", "background", "task", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/client.py#L221-L237
train
198,315
miguelgrinberg/python-engineio
engineio/client.py
Client._get_engineio_url
def _get_engineio_url(self, url, engineio_path, transport): """Generate the Engine.IO connection URL.""" engineio_path = engineio_path.strip('/') parsed_url = urllib.parse.urlparse(url) if transport == 'polling': scheme = 'http' elif transport == 'websocket': scheme = 'ws' else: # pragma: no cover raise ValueError('invalid transport') if parsed_url.scheme in ['https', 'wss']: scheme += 's' return ('{scheme}://{netloc}/{path}/?{query}' '{sep}transport={transport}&EIO=3').format( scheme=scheme, netloc=parsed_url.netloc, path=engineio_path, query=parsed_url.query, sep='&' if parsed_url.query else '', transport=transport)
python
def _get_engineio_url(self, url, engineio_path, transport): """Generate the Engine.IO connection URL.""" engineio_path = engineio_path.strip('/') parsed_url = urllib.parse.urlparse(url) if transport == 'polling': scheme = 'http' elif transport == 'websocket': scheme = 'ws' else: # pragma: no cover raise ValueError('invalid transport') if parsed_url.scheme in ['https', 'wss']: scheme += 's' return ('{scheme}://{netloc}/{path}/?{query}' '{sep}transport={transport}&EIO=3').format( scheme=scheme, netloc=parsed_url.netloc, path=engineio_path, query=parsed_url.query, sep='&' if parsed_url.query else '', transport=transport)
[ "def", "_get_engineio_url", "(", "self", ",", "url", ",", "engineio_path", ",", "transport", ")", ":", "engineio_path", "=", "engineio_path", ".", "strip", "(", "'/'", ")", "parsed_url", "=", "urllib", ".", "parse", ".", "urlparse", "(", "url", ")", "if", ...
Generate the Engine.IO connection URL.
[ "Generate", "the", "Engine", ".", "IO", "connection", "URL", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/client.py#L458-L477
train
198,316
miguelgrinberg/python-engineio
engineio/client.py
Client._ping_loop
def _ping_loop(self): """This background task sends a PING to the server at the requested interval. """ self.pong_received = True self.ping_loop_event.clear() while self.state == 'connected': if not self.pong_received: self.logger.info( 'PONG response has not been received, aborting') if self.ws: self.ws.close() self.queue.put(None) break self.pong_received = False self._send_packet(packet.Packet(packet.PING)) self.ping_loop_event.wait(timeout=self.ping_interval) self.logger.info('Exiting ping task')
python
def _ping_loop(self): """This background task sends a PING to the server at the requested interval. """ self.pong_received = True self.ping_loop_event.clear() while self.state == 'connected': if not self.pong_received: self.logger.info( 'PONG response has not been received, aborting') if self.ws: self.ws.close() self.queue.put(None) break self.pong_received = False self._send_packet(packet.Packet(packet.PING)) self.ping_loop_event.wait(timeout=self.ping_interval) self.logger.info('Exiting ping task')
[ "def", "_ping_loop", "(", "self", ")", ":", "self", ".", "pong_received", "=", "True", "self", ".", "ping_loop_event", ".", "clear", "(", ")", "while", "self", ".", "state", "==", "'connected'", ":", "if", "not", "self", ".", "pong_received", ":", "self"...
This background task sends a PING to the server at the requested interval.
[ "This", "background", "task", "sends", "a", "PING", "to", "the", "server", "at", "the", "requested", "interval", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/client.py#L483-L500
train
198,317
miguelgrinberg/python-engineio
engineio/client.py
Client._read_loop_polling
def _read_loop_polling(self): """Read packets by polling the Engine.IO server.""" while self.state == 'connected': self.logger.info( 'Sending polling GET request to ' + self.base_url) r = self._send_request( 'GET', self.base_url + self._get_url_timestamp()) if r is None: self.logger.warning( 'Connection refused by the server, aborting') self.queue.put(None) break if r.status_code != 200: self.logger.warning('Unexpected status code %s in server ' 'response, aborting', r.status_code) self.queue.put(None) break try: p = payload.Payload(encoded_payload=r.content) except ValueError: self.logger.warning( 'Unexpected packet from server, aborting') self.queue.put(None) break for pkt in p.packets: self._receive_packet(pkt) self.logger.info('Waiting for write loop task to end') self.write_loop_task.join() self.logger.info('Waiting for ping loop task to end') self.ping_loop_event.set() self.ping_loop_task.join() if self.state == 'connected': self._trigger_event('disconnect', run_async=False) try: connected_clients.remove(self) except ValueError: # pragma: no cover pass self._reset() self.logger.info('Exiting read loop task')
python
def _read_loop_polling(self): """Read packets by polling the Engine.IO server.""" while self.state == 'connected': self.logger.info( 'Sending polling GET request to ' + self.base_url) r = self._send_request( 'GET', self.base_url + self._get_url_timestamp()) if r is None: self.logger.warning( 'Connection refused by the server, aborting') self.queue.put(None) break if r.status_code != 200: self.logger.warning('Unexpected status code %s in server ' 'response, aborting', r.status_code) self.queue.put(None) break try: p = payload.Payload(encoded_payload=r.content) except ValueError: self.logger.warning( 'Unexpected packet from server, aborting') self.queue.put(None) break for pkt in p.packets: self._receive_packet(pkt) self.logger.info('Waiting for write loop task to end') self.write_loop_task.join() self.logger.info('Waiting for ping loop task to end') self.ping_loop_event.set() self.ping_loop_task.join() if self.state == 'connected': self._trigger_event('disconnect', run_async=False) try: connected_clients.remove(self) except ValueError: # pragma: no cover pass self._reset() self.logger.info('Exiting read loop task')
[ "def", "_read_loop_polling", "(", "self", ")", ":", "while", "self", ".", "state", "==", "'connected'", ":", "self", ".", "logger", ".", "info", "(", "'Sending polling GET request to '", "+", "self", ".", "base_url", ")", "r", "=", "self", ".", "_send_reques...
Read packets by polling the Engine.IO server.
[ "Read", "packets", "by", "polling", "the", "Engine", ".", "IO", "server", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/client.py#L502-L541
train
198,318
miguelgrinberg/python-engineio
engineio/client.py
Client._read_loop_websocket
def _read_loop_websocket(self): """Read packets from the Engine.IO WebSocket connection.""" while self.state == 'connected': p = None try: p = self.ws.recv() except websocket.WebSocketConnectionClosedException: self.logger.warning( 'WebSocket connection was closed, aborting') self.queue.put(None) break except Exception as e: self.logger.info( 'Unexpected error "%s", aborting', str(e)) self.queue.put(None) break if isinstance(p, six.text_type): # pragma: no cover p = p.encode('utf-8') pkt = packet.Packet(encoded_packet=p) self._receive_packet(pkt) self.logger.info('Waiting for write loop task to end') self.write_loop_task.join() self.logger.info('Waiting for ping loop task to end') self.ping_loop_event.set() self.ping_loop_task.join() if self.state == 'connected': self._trigger_event('disconnect', run_async=False) try: connected_clients.remove(self) except ValueError: # pragma: no cover pass self._reset() self.logger.info('Exiting read loop task')
python
def _read_loop_websocket(self): """Read packets from the Engine.IO WebSocket connection.""" while self.state == 'connected': p = None try: p = self.ws.recv() except websocket.WebSocketConnectionClosedException: self.logger.warning( 'WebSocket connection was closed, aborting') self.queue.put(None) break except Exception as e: self.logger.info( 'Unexpected error "%s", aborting', str(e)) self.queue.put(None) break if isinstance(p, six.text_type): # pragma: no cover p = p.encode('utf-8') pkt = packet.Packet(encoded_packet=p) self._receive_packet(pkt) self.logger.info('Waiting for write loop task to end') self.write_loop_task.join() self.logger.info('Waiting for ping loop task to end') self.ping_loop_event.set() self.ping_loop_task.join() if self.state == 'connected': self._trigger_event('disconnect', run_async=False) try: connected_clients.remove(self) except ValueError: # pragma: no cover pass self._reset() self.logger.info('Exiting read loop task')
[ "def", "_read_loop_websocket", "(", "self", ")", ":", "while", "self", ".", "state", "==", "'connected'", ":", "p", "=", "None", "try", ":", "p", "=", "self", ".", "ws", ".", "recv", "(", ")", "except", "websocket", ".", "WebSocketConnectionClosedException...
Read packets from the Engine.IO WebSocket connection.
[ "Read", "packets", "from", "the", "Engine", ".", "IO", "WebSocket", "connection", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/client.py#L543-L576
train
198,319
miguelgrinberg/python-engineio
engineio/server.py
Server._upgrades
def _upgrades(self, sid, transport): """Return the list of possible upgrades for a client connection.""" if not self.allow_upgrades or self._get_socket(sid).upgraded or \ self._async['websocket'] is None or transport == 'websocket': return [] return ['websocket']
python
def _upgrades(self, sid, transport): """Return the list of possible upgrades for a client connection.""" if not self.allow_upgrades or self._get_socket(sid).upgraded or \ self._async['websocket'] is None or transport == 'websocket': return [] return ['websocket']
[ "def", "_upgrades", "(", "self", ",", "sid", ",", "transport", ")", ":", "if", "not", "self", ".", "allow_upgrades", "or", "self", ".", "_get_socket", "(", "sid", ")", ".", "upgraded", "or", "self", ".", "_async", "[", "'websocket'", "]", "is", "None",...
Return the list of possible upgrades for a client connection.
[ "Return", "the", "list", "of", "possible", "upgrades", "for", "a", "client", "connection", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/server.py#L490-L495
train
198,320
miguelgrinberg/python-engineio
engineio/server.py
Server._get_socket
def _get_socket(self, sid): """Return the socket object for a given session.""" try: s = self.sockets[sid] except KeyError: raise KeyError('Session not found') if s.closed: del self.sockets[sid] raise KeyError('Session is disconnected') return s
python
def _get_socket(self, sid): """Return the socket object for a given session.""" try: s = self.sockets[sid] except KeyError: raise KeyError('Session not found') if s.closed: del self.sockets[sid] raise KeyError('Session is disconnected') return s
[ "def", "_get_socket", "(", "self", ",", "sid", ")", ":", "try", ":", "s", "=", "self", ".", "sockets", "[", "sid", "]", "except", "KeyError", ":", "raise", "KeyError", "(", "'Session not found'", ")", "if", "s", ".", "closed", ":", "del", "self", "."...
Return the socket object for a given session.
[ "Return", "the", "socket", "object", "for", "a", "given", "session", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/server.py#L513-L522
train
198,321
miguelgrinberg/python-engineio
engineio/server.py
Server._ok
def _ok(self, packets=None, headers=None, b64=False): """Generate a successful HTTP response.""" if packets is not None: if headers is None: headers = [] if b64: headers += [('Content-Type', 'text/plain; charset=UTF-8')] else: headers += [('Content-Type', 'application/octet-stream')] return {'status': '200 OK', 'headers': headers, 'response': payload.Payload(packets=packets).encode(b64)} else: return {'status': '200 OK', 'headers': [('Content-Type', 'text/plain')], 'response': b'OK'}
python
def _ok(self, packets=None, headers=None, b64=False): """Generate a successful HTTP response.""" if packets is not None: if headers is None: headers = [] if b64: headers += [('Content-Type', 'text/plain; charset=UTF-8')] else: headers += [('Content-Type', 'application/octet-stream')] return {'status': '200 OK', 'headers': headers, 'response': payload.Payload(packets=packets).encode(b64)} else: return {'status': '200 OK', 'headers': [('Content-Type', 'text/plain')], 'response': b'OK'}
[ "def", "_ok", "(", "self", ",", "packets", "=", "None", ",", "headers", "=", "None", ",", "b64", "=", "False", ")", ":", "if", "packets", "is", "not", "None", ":", "if", "headers", "is", "None", ":", "headers", "=", "[", "]", "if", "b64", ":", ...
Generate a successful HTTP response.
[ "Generate", "a", "successful", "HTTP", "response", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/server.py#L524-L539
train
198,322
miguelgrinberg/python-engineio
engineio/server.py
Server._cors_headers
def _cors_headers(self, environ): """Return the cross-origin-resource-sharing headers.""" if isinstance(self.cors_allowed_origins, six.string_types): if self.cors_allowed_origins == '*': allowed_origins = None else: allowed_origins = [self.cors_allowed_origins] else: allowed_origins = self.cors_allowed_origins if allowed_origins is not None and \ environ.get('HTTP_ORIGIN', '') not in allowed_origins: return [] if 'HTTP_ORIGIN' in environ: headers = [('Access-Control-Allow-Origin', environ['HTTP_ORIGIN'])] else: headers = [('Access-Control-Allow-Origin', '*')] if environ['REQUEST_METHOD'] == 'OPTIONS': headers += [('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')] if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ: headers += [('Access-Control-Allow-Headers', environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])] if self.cors_credentials: headers += [('Access-Control-Allow-Credentials', 'true')] return headers
python
def _cors_headers(self, environ): """Return the cross-origin-resource-sharing headers.""" if isinstance(self.cors_allowed_origins, six.string_types): if self.cors_allowed_origins == '*': allowed_origins = None else: allowed_origins = [self.cors_allowed_origins] else: allowed_origins = self.cors_allowed_origins if allowed_origins is not None and \ environ.get('HTTP_ORIGIN', '') not in allowed_origins: return [] if 'HTTP_ORIGIN' in environ: headers = [('Access-Control-Allow-Origin', environ['HTTP_ORIGIN'])] else: headers = [('Access-Control-Allow-Origin', '*')] if environ['REQUEST_METHOD'] == 'OPTIONS': headers += [('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')] if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ: headers += [('Access-Control-Allow-Headers', environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])] if self.cors_credentials: headers += [('Access-Control-Allow-Credentials', 'true')] return headers
[ "def", "_cors_headers", "(", "self", ",", "environ", ")", ":", "if", "isinstance", "(", "self", ".", "cors_allowed_origins", ",", "six", ".", "string_types", ")", ":", "if", "self", ".", "cors_allowed_origins", "==", "'*'", ":", "allowed_origins", "=", "None...
Return the cross-origin-resource-sharing headers.
[ "Return", "the", "cross", "-", "origin", "-", "resource", "-", "sharing", "headers", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/server.py#L559-L582
train
198,323
miguelgrinberg/python-engineio
engineio/server.py
Server._gzip
def _gzip(self, response): """Apply gzip compression to a response.""" bytesio = six.BytesIO() with gzip.GzipFile(fileobj=bytesio, mode='w') as gz: gz.write(response) return bytesio.getvalue()
python
def _gzip(self, response): """Apply gzip compression to a response.""" bytesio = six.BytesIO() with gzip.GzipFile(fileobj=bytesio, mode='w') as gz: gz.write(response) return bytesio.getvalue()
[ "def", "_gzip", "(", "self", ",", "response", ")", ":", "bytesio", "=", "six", ".", "BytesIO", "(", ")", "with", "gzip", ".", "GzipFile", "(", "fileobj", "=", "bytesio", ",", "mode", "=", "'w'", ")", "as", "gz", ":", "gz", ".", "write", "(", "res...
Apply gzip compression to a response.
[ "Apply", "gzip", "compression", "to", "a", "response", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/server.py#L584-L589
train
198,324
miguelgrinberg/python-engineio
engineio/async_drivers/gevent_uwsgi.py
uWSGIWebSocket.close
def close(self): """Disconnects uWSGI from the client.""" uwsgi.disconnect() if self._req_ctx is None: # better kill it here in case wait() is not called again self._select_greenlet.kill() self._event.set()
python
def close(self): """Disconnects uWSGI from the client.""" uwsgi.disconnect() if self._req_ctx is None: # better kill it here in case wait() is not called again self._select_greenlet.kill() self._event.set()
[ "def", "close", "(", "self", ")", ":", "uwsgi", ".", "disconnect", "(", ")", "if", "self", ".", "_req_ctx", "is", "None", ":", "# better kill it here in case wait() is not called again", "self", ".", "_select_greenlet", ".", "kill", "(", ")", "self", ".", "_ev...
Disconnects uWSGI from the client.
[ "Disconnects", "uWSGI", "from", "the", "client", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/async_drivers/gevent_uwsgi.py#L67-L73
train
198,325
miguelgrinberg/python-engineio
engineio/async_drivers/gevent_uwsgi.py
uWSGIWebSocket._send
def _send(self, msg): """Transmits message either in binary or UTF-8 text mode, depending on its type.""" if isinstance(msg, six.binary_type): method = uwsgi.websocket_send_binary else: method = uwsgi.websocket_send if self._req_ctx is not None: method(msg, request_context=self._req_ctx) else: method(msg)
python
def _send(self, msg): """Transmits message either in binary or UTF-8 text mode, depending on its type.""" if isinstance(msg, six.binary_type): method = uwsgi.websocket_send_binary else: method = uwsgi.websocket_send if self._req_ctx is not None: method(msg, request_context=self._req_ctx) else: method(msg)
[ "def", "_send", "(", "self", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "six", ".", "binary_type", ")", ":", "method", "=", "uwsgi", ".", "websocket_send_binary", "else", ":", "method", "=", "uwsgi", ".", "websocket_send", "if", "self", ...
Transmits message either in binary or UTF-8 text mode, depending on its type.
[ "Transmits", "message", "either", "in", "binary", "or", "UTF", "-", "8", "text", "mode", "depending", "on", "its", "type", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/async_drivers/gevent_uwsgi.py#L75-L85
train
198,326
miguelgrinberg/python-engineio
engineio/async_drivers/gevent_uwsgi.py
uWSGIWebSocket._decode_received
def _decode_received(self, msg): """Returns either bytes or str, depending on message type.""" if not isinstance(msg, six.binary_type): # already decoded - do nothing return msg # only decode from utf-8 if message is not binary data type = six.byte2int(msg[0:1]) if type >= 48: # no binary return msg.decode('utf-8') # binary message, don't try to decode return msg
python
def _decode_received(self, msg): """Returns either bytes or str, depending on message type.""" if not isinstance(msg, six.binary_type): # already decoded - do nothing return msg # only decode from utf-8 if message is not binary data type = six.byte2int(msg[0:1]) if type >= 48: # no binary return msg.decode('utf-8') # binary message, don't try to decode return msg
[ "def", "_decode_received", "(", "self", ",", "msg", ")", ":", "if", "not", "isinstance", "(", "msg", ",", "six", ".", "binary_type", ")", ":", "# already decoded - do nothing", "return", "msg", "# only decode from utf-8 if message is not binary data", "type", "=", "...
Returns either bytes or str, depending on message type.
[ "Returns", "either", "bytes", "or", "str", "depending", "on", "message", "type", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/async_drivers/gevent_uwsgi.py#L87-L97
train
198,327
miguelgrinberg/python-engineio
engineio/async_drivers/gevent_uwsgi.py
uWSGIWebSocket.send
def send(self, msg): """Queues a message for sending. Real transmission is done in wait method. Sends directly if uWSGI version is new enough.""" if self._req_ctx is not None: self._send(msg) else: self._send_queue.put(msg) self._event.set()
python
def send(self, msg): """Queues a message for sending. Real transmission is done in wait method. Sends directly if uWSGI version is new enough.""" if self._req_ctx is not None: self._send(msg) else: self._send_queue.put(msg) self._event.set()
[ "def", "send", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "_req_ctx", "is", "not", "None", ":", "self", ".", "_send", "(", "msg", ")", "else", ":", "self", ".", "_send_queue", ".", "put", "(", "msg", ")", "self", ".", "_event", ".", ...
Queues a message for sending. Real transmission is done in wait method. Sends directly if uWSGI version is new enough.
[ "Queues", "a", "message", "for", "sending", ".", "Real", "transmission", "is", "done", "in", "wait", "method", ".", "Sends", "directly", "if", "uWSGI", "version", "is", "new", "enough", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/async_drivers/gevent_uwsgi.py#L99-L107
train
198,328
miguelgrinberg/python-engineio
engineio/asyncio_server.py
AsyncServer.attach
def attach(self, app, engineio_path='engine.io'): """Attach the Engine.IO server to an application.""" engineio_path = engineio_path.strip('/') self._async['create_route'](app, self, '/{}/'.format(engineio_path))
python
def attach(self, app, engineio_path='engine.io'): """Attach the Engine.IO server to an application.""" engineio_path = engineio_path.strip('/') self._async['create_route'](app, self, '/{}/'.format(engineio_path))
[ "def", "attach", "(", "self", ",", "app", ",", "engineio_path", "=", "'engine.io'", ")", ":", "engineio_path", "=", "engineio_path", ".", "strip", "(", "'/'", ")", "self", ".", "_async", "[", "'create_route'", "]", "(", "app", ",", "self", ",", "'/{}/'",...
Attach the Engine.IO server to an application.
[ "Attach", "the", "Engine", ".", "IO", "server", "to", "an", "application", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_server.py#L61-L64
train
198,329
miguelgrinberg/python-engineio
engineio/socket.py
Socket.handle_get_request
def handle_get_request(self, environ, start_response): """Handle a long-polling GET request from the client.""" connections = [ s.strip() for s in environ.get('HTTP_CONNECTION', '').lower().split(',')] transport = environ.get('HTTP_UPGRADE', '').lower() if 'upgrade' in connections and transport in self.upgrade_protocols: self.server.logger.info('%s: Received request to upgrade to %s', self.sid, transport) return getattr(self, '_upgrade_' + transport)(environ, start_response) try: packets = self.poll() except exceptions.QueueEmpty: exc = sys.exc_info() self.close(wait=False) six.reraise(*exc) return packets
python
def handle_get_request(self, environ, start_response): """Handle a long-polling GET request from the client.""" connections = [ s.strip() for s in environ.get('HTTP_CONNECTION', '').lower().split(',')] transport = environ.get('HTTP_UPGRADE', '').lower() if 'upgrade' in connections and transport in self.upgrade_protocols: self.server.logger.info('%s: Received request to upgrade to %s', self.sid, transport) return getattr(self, '_upgrade_' + transport)(environ, start_response) try: packets = self.poll() except exceptions.QueueEmpty: exc = sys.exc_info() self.close(wait=False) six.reraise(*exc) return packets
[ "def", "handle_get_request", "(", "self", ",", "environ", ",", "start_response", ")", ":", "connections", "=", "[", "s", ".", "strip", "(", ")", "for", "s", "in", "environ", ".", "get", "(", "'HTTP_CONNECTION'", ",", "''", ")", ".", "lower", "(", ")", ...
Handle a long-polling GET request from the client.
[ "Handle", "a", "long", "-", "polling", "GET", "request", "from", "the", "client", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/socket.py#L96-L113
train
198,330
miguelgrinberg/python-engineio
engineio/socket.py
Socket.close
def close(self, wait=True, abort=False): """Close the socket connection.""" if not self.closed and not self.closing: self.closing = True self.server._trigger_event('disconnect', self.sid, run_async=False) if not abort: self.send(packet.Packet(packet.CLOSE)) self.closed = True self.queue.put(None) if wait: self.queue.join()
python
def close(self, wait=True, abort=False): """Close the socket connection.""" if not self.closed and not self.closing: self.closing = True self.server._trigger_event('disconnect', self.sid, run_async=False) if not abort: self.send(packet.Packet(packet.CLOSE)) self.closed = True self.queue.put(None) if wait: self.queue.join()
[ "def", "close", "(", "self", ",", "wait", "=", "True", ",", "abort", "=", "False", ")", ":", "if", "not", "self", ".", "closed", "and", "not", "self", ".", "closing", ":", "self", ".", "closing", "=", "True", "self", ".", "server", ".", "_trigger_e...
Close the socket connection.
[ "Close", "the", "socket", "connection", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/socket.py#L126-L136
train
198,331
miguelgrinberg/python-engineio
engineio/asyncio_client.py
AsyncClient.connect
async def connect(self, url, headers={}, transports=None, engineio_path='engine.io'): """Connect to an Engine.IO server. :param url: The URL of the Engine.IO server. It can include custom query string parameters if required by the server. :param headers: A dictionary with custom headers to send with the connection request. :param transports: The list of allowed transports. Valid transports are ``'polling'`` and ``'websocket'``. If not given, the polling transport is connected first, then an upgrade to websocket is attempted. :param engineio_path: The endpoint where the Engine.IO server is installed. The default value is appropriate for most cases. Note: this method is a coroutine. Example usage:: eio = engineio.Client() await eio.connect('http://localhost:5000') """ if self.state != 'disconnected': raise ValueError('Client is not in a disconnected state') valid_transports = ['polling', 'websocket'] if transports is not None: if isinstance(transports, six.text_type): transports = [transports] transports = [transport for transport in transports if transport in valid_transports] if not transports: raise ValueError('No valid transports provided') self.transports = transports or valid_transports self.queue = self.create_queue() return await getattr(self, '_connect_' + self.transports[0])( url, headers, engineio_path)
python
async def connect(self, url, headers={}, transports=None, engineio_path='engine.io'): """Connect to an Engine.IO server. :param url: The URL of the Engine.IO server. It can include custom query string parameters if required by the server. :param headers: A dictionary with custom headers to send with the connection request. :param transports: The list of allowed transports. Valid transports are ``'polling'`` and ``'websocket'``. If not given, the polling transport is connected first, then an upgrade to websocket is attempted. :param engineio_path: The endpoint where the Engine.IO server is installed. The default value is appropriate for most cases. Note: this method is a coroutine. Example usage:: eio = engineio.Client() await eio.connect('http://localhost:5000') """ if self.state != 'disconnected': raise ValueError('Client is not in a disconnected state') valid_transports = ['polling', 'websocket'] if transports is not None: if isinstance(transports, six.text_type): transports = [transports] transports = [transport for transport in transports if transport in valid_transports] if not transports: raise ValueError('No valid transports provided') self.transports = transports or valid_transports self.queue = self.create_queue() return await getattr(self, '_connect_' + self.transports[0])( url, headers, engineio_path)
[ "async", "def", "connect", "(", "self", ",", "url", ",", "headers", "=", "{", "}", ",", "transports", "=", "None", ",", "engineio_path", "=", "'engine.io'", ")", ":", "if", "self", ".", "state", "!=", "'disconnected'", ":", "raise", "ValueError", "(", ...
Connect to an Engine.IO server. :param url: The URL of the Engine.IO server. It can include custom query string parameters if required by the server. :param headers: A dictionary with custom headers to send with the connection request. :param transports: The list of allowed transports. Valid transports are ``'polling'`` and ``'websocket'``. If not given, the polling transport is connected first, then an upgrade to websocket is attempted. :param engineio_path: The endpoint where the Engine.IO server is installed. The default value is appropriate for most cases. Note: this method is a coroutine. Example usage:: eio = engineio.Client() await eio.connect('http://localhost:5000')
[ "Connect", "to", "an", "Engine", ".", "IO", "server", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_client.py#L37-L73
train
198,332
miguelgrinberg/python-engineio
engineio/asyncio_client.py
AsyncClient._connect_polling
async def _connect_polling(self, url, headers, engineio_path): """Establish a long-polling connection to the Engine.IO server.""" if aiohttp is None: # pragma: no cover self.logger.error('aiohttp not installed -- cannot make HTTP ' 'requests!') return self.base_url = self._get_engineio_url(url, engineio_path, 'polling') self.logger.info('Attempting polling connection to ' + self.base_url) r = await self._send_request( 'GET', self.base_url + self._get_url_timestamp(), headers=headers) if r is None: self._reset() raise exceptions.ConnectionError( 'Connection refused by the server') if r.status != 200: raise exceptions.ConnectionError( 'Unexpected status code {} in server response'.format( r.status)) try: p = payload.Payload(encoded_payload=await r.read()) except ValueError: six.raise_from(exceptions.ConnectionError( 'Unexpected response from server'), None) open_packet = p.packets[0] if open_packet.packet_type != packet.OPEN: raise exceptions.ConnectionError( 'OPEN packet not returned by server') self.logger.info( 'Polling connection accepted with ' + str(open_packet.data)) self.sid = open_packet.data['sid'] self.upgrades = open_packet.data['upgrades'] self.ping_interval = open_packet.data['pingInterval'] / 1000.0 self.ping_timeout = open_packet.data['pingTimeout'] / 1000.0 self.current_transport = 'polling' self.base_url += '&sid=' + self.sid self.state = 'connected' client.connected_clients.append(self) await self._trigger_event('connect', run_async=False) for pkt in p.packets[1:]: await self._receive_packet(pkt) if 'websocket' in self.upgrades and 'websocket' in self.transports: # attempt to upgrade to websocket if await self._connect_websocket(url, headers, engineio_path): # upgrade to websocket succeeded, we're done here return self.ping_loop_task = self.start_background_task(self._ping_loop) self.write_loop_task = self.start_background_task(self._write_loop) self.read_loop_task = self.start_background_task( self._read_loop_polling)
python
async def _connect_polling(self, url, headers, engineio_path): """Establish a long-polling connection to the Engine.IO server.""" if aiohttp is None: # pragma: no cover self.logger.error('aiohttp not installed -- cannot make HTTP ' 'requests!') return self.base_url = self._get_engineio_url(url, engineio_path, 'polling') self.logger.info('Attempting polling connection to ' + self.base_url) r = await self._send_request( 'GET', self.base_url + self._get_url_timestamp(), headers=headers) if r is None: self._reset() raise exceptions.ConnectionError( 'Connection refused by the server') if r.status != 200: raise exceptions.ConnectionError( 'Unexpected status code {} in server response'.format( r.status)) try: p = payload.Payload(encoded_payload=await r.read()) except ValueError: six.raise_from(exceptions.ConnectionError( 'Unexpected response from server'), None) open_packet = p.packets[0] if open_packet.packet_type != packet.OPEN: raise exceptions.ConnectionError( 'OPEN packet not returned by server') self.logger.info( 'Polling connection accepted with ' + str(open_packet.data)) self.sid = open_packet.data['sid'] self.upgrades = open_packet.data['upgrades'] self.ping_interval = open_packet.data['pingInterval'] / 1000.0 self.ping_timeout = open_packet.data['pingTimeout'] / 1000.0 self.current_transport = 'polling' self.base_url += '&sid=' + self.sid self.state = 'connected' client.connected_clients.append(self) await self._trigger_event('connect', run_async=False) for pkt in p.packets[1:]: await self._receive_packet(pkt) if 'websocket' in self.upgrades and 'websocket' in self.transports: # attempt to upgrade to websocket if await self._connect_websocket(url, headers, engineio_path): # upgrade to websocket succeeded, we're done here return self.ping_loop_task = self.start_background_task(self._ping_loop) self.write_loop_task = self.start_background_task(self._write_loop) self.read_loop_task = self.start_background_task( self._read_loop_polling)
[ "async", "def", "_connect_polling", "(", "self", ",", "url", ",", "headers", ",", "engineio_path", ")", ":", "if", "aiohttp", "is", "None", ":", "# pragma: no cover", "self", ".", "logger", ".", "error", "(", "'aiohttp not installed -- cannot make HTTP '", "'reque...
Establish a long-polling connection to the Engine.IO server.
[ "Establish", "a", "long", "-", "polling", "connection", "to", "the", "Engine", ".", "IO", "server", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_client.py#L166-L218
train
198,333
miguelgrinberg/python-engineio
engineio/asyncio_client.py
AsyncClient._receive_packet
async def _receive_packet(self, pkt): """Handle incoming packets from the server.""" packet_name = packet.packet_names[pkt.packet_type] \ if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN' self.logger.info( 'Received packet %s data %s', packet_name, pkt.data if not isinstance(pkt.data, bytes) else '<binary>') if pkt.packet_type == packet.MESSAGE: await self._trigger_event('message', pkt.data, run_async=True) elif pkt.packet_type == packet.PONG: self.pong_received = True elif pkt.packet_type == packet.NOOP: pass else: self.logger.error('Received unexpected packet of type %s', pkt.packet_type)
python
async def _receive_packet(self, pkt): """Handle incoming packets from the server.""" packet_name = packet.packet_names[pkt.packet_type] \ if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN' self.logger.info( 'Received packet %s data %s', packet_name, pkt.data if not isinstance(pkt.data, bytes) else '<binary>') if pkt.packet_type == packet.MESSAGE: await self._trigger_event('message', pkt.data, run_async=True) elif pkt.packet_type == packet.PONG: self.pong_received = True elif pkt.packet_type == packet.NOOP: pass else: self.logger.error('Received unexpected packet of type %s', pkt.packet_type)
[ "async", "def", "_receive_packet", "(", "self", ",", "pkt", ")", ":", "packet_name", "=", "packet", ".", "packet_names", "[", "pkt", ".", "packet_type", "]", "if", "pkt", ".", "packet_type", "<", "len", "(", "packet", ".", "packet_names", ")", "else", "'...
Handle incoming packets from the server.
[ "Handle", "incoming", "packets", "from", "the", "server", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_client.py#L321-L336
train
198,334
miguelgrinberg/python-engineio
engineio/asyncio_client.py
AsyncClient._send_packet
async def _send_packet(self, pkt): """Queue a packet to be sent to the server.""" if self.state != 'connected': return await self.queue.put(pkt) self.logger.info( 'Sending packet %s data %s', packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
python
async def _send_packet(self, pkt): """Queue a packet to be sent to the server.""" if self.state != 'connected': return await self.queue.put(pkt) self.logger.info( 'Sending packet %s data %s', packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
[ "async", "def", "_send_packet", "(", "self", ",", "pkt", ")", ":", "if", "self", ".", "state", "!=", "'connected'", ":", "return", "await", "self", ".", "queue", ".", "put", "(", "pkt", ")", "self", ".", "logger", ".", "info", "(", "'Sending packet %s ...
Queue a packet to be sent to the server.
[ "Queue", "a", "packet", "to", "be", "sent", "to", "the", "server", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_client.py#L338-L346
train
198,335
miguelgrinberg/python-engineio
engineio/payload.py
Payload.encode
def encode(self, b64=False): """Encode the payload for transmission.""" encoded_payload = b'' for pkt in self.packets: encoded_packet = pkt.encode(b64=b64) packet_len = len(encoded_packet) if b64: encoded_payload += str(packet_len).encode('utf-8') + b':' + \ encoded_packet else: binary_len = b'' while packet_len != 0: binary_len = six.int2byte(packet_len % 10) + binary_len packet_len = int(packet_len / 10) if not pkt.binary: encoded_payload += b'\0' else: encoded_payload += b'\1' encoded_payload += binary_len + b'\xff' + encoded_packet return encoded_payload
python
def encode(self, b64=False): """Encode the payload for transmission.""" encoded_payload = b'' for pkt in self.packets: encoded_packet = pkt.encode(b64=b64) packet_len = len(encoded_packet) if b64: encoded_payload += str(packet_len).encode('utf-8') + b':' + \ encoded_packet else: binary_len = b'' while packet_len != 0: binary_len = six.int2byte(packet_len % 10) + binary_len packet_len = int(packet_len / 10) if not pkt.binary: encoded_payload += b'\0' else: encoded_payload += b'\1' encoded_payload += binary_len + b'\xff' + encoded_packet return encoded_payload
[ "def", "encode", "(", "self", ",", "b64", "=", "False", ")", ":", "encoded_payload", "=", "b''", "for", "pkt", "in", "self", ".", "packets", ":", "encoded_packet", "=", "pkt", ".", "encode", "(", "b64", "=", "b64", ")", "packet_len", "=", "len", "(",...
Encode the payload for transmission.
[ "Encode", "the", "payload", "for", "transmission", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/payload.py#L13-L32
train
198,336
miguelgrinberg/python-engineio
engineio/payload.py
Payload.decode
def decode(self, encoded_payload): """Decode a transmitted payload.""" self.packets = [] while encoded_payload: if six.byte2int(encoded_payload[0:1]) <= 1: packet_len = 0 i = 1 while six.byte2int(encoded_payload[i:i + 1]) != 255: packet_len = packet_len * 10 + six.byte2int( encoded_payload[i:i + 1]) i += 1 self.packets.append(packet.Packet( encoded_packet=encoded_payload[i + 1:i + 1 + packet_len])) else: i = encoded_payload.find(b':') if i == -1: raise ValueError('invalid payload') # extracting the packet out of the payload is extremely # inefficient, because the payload needs to be treated as # binary, but the non-binary packets have to be parsed as # unicode. Luckily this complication only applies to long # polling, as the websocket transport sends packets # individually wrapped. packet_len = int(encoded_payload[0:i]) pkt = encoded_payload.decode('utf-8', errors='ignore')[ i + 1: i + 1 + packet_len].encode('utf-8') self.packets.append(packet.Packet(encoded_packet=pkt)) # the engine.io protocol sends the packet length in # utf-8 characters, but we need it in bytes to be able to # jump to the next packet in the payload packet_len = len(pkt) encoded_payload = encoded_payload[i + 1 + packet_len:]
python
def decode(self, encoded_payload): """Decode a transmitted payload.""" self.packets = [] while encoded_payload: if six.byte2int(encoded_payload[0:1]) <= 1: packet_len = 0 i = 1 while six.byte2int(encoded_payload[i:i + 1]) != 255: packet_len = packet_len * 10 + six.byte2int( encoded_payload[i:i + 1]) i += 1 self.packets.append(packet.Packet( encoded_packet=encoded_payload[i + 1:i + 1 + packet_len])) else: i = encoded_payload.find(b':') if i == -1: raise ValueError('invalid payload') # extracting the packet out of the payload is extremely # inefficient, because the payload needs to be treated as # binary, but the non-binary packets have to be parsed as # unicode. Luckily this complication only applies to long # polling, as the websocket transport sends packets # individually wrapped. packet_len = int(encoded_payload[0:i]) pkt = encoded_payload.decode('utf-8', errors='ignore')[ i + 1: i + 1 + packet_len].encode('utf-8') self.packets.append(packet.Packet(encoded_packet=pkt)) # the engine.io protocol sends the packet length in # utf-8 characters, but we need it in bytes to be able to # jump to the next packet in the payload packet_len = len(pkt) encoded_payload = encoded_payload[i + 1 + packet_len:]
[ "def", "decode", "(", "self", ",", "encoded_payload", ")", ":", "self", ".", "packets", "=", "[", "]", "while", "encoded_payload", ":", "if", "six", ".", "byte2int", "(", "encoded_payload", "[", "0", ":", "1", "]", ")", "<=", "1", ":", "packet_len", ...
Decode a transmitted payload.
[ "Decode", "a", "transmitted", "payload", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/payload.py#L34-L67
train
198,337
miguelgrinberg/python-engineio
engineio/asyncio_socket.py
AsyncSocket.receive
async def receive(self, pkt): """Receive packet from the client.""" self.server.logger.info('%s: Received packet %s data %s', self.sid, packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>') if pkt.packet_type == packet.PING: self.last_ping = time.time() await self.send(packet.Packet(packet.PONG, pkt.data)) elif pkt.packet_type == packet.MESSAGE: await self.server._trigger_event( 'message', self.sid, pkt.data, run_async=self.server.async_handlers) elif pkt.packet_type == packet.UPGRADE: await self.send(packet.Packet(packet.NOOP)) elif pkt.packet_type == packet.CLOSE: await self.close(wait=False, abort=True) else: raise exceptions.UnknownPacketError()
python
async def receive(self, pkt): """Receive packet from the client.""" self.server.logger.info('%s: Received packet %s data %s', self.sid, packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>') if pkt.packet_type == packet.PING: self.last_ping = time.time() await self.send(packet.Packet(packet.PONG, pkt.data)) elif pkt.packet_type == packet.MESSAGE: await self.server._trigger_event( 'message', self.sid, pkt.data, run_async=self.server.async_handlers) elif pkt.packet_type == packet.UPGRADE: await self.send(packet.Packet(packet.NOOP)) elif pkt.packet_type == packet.CLOSE: await self.close(wait=False, abort=True) else: raise exceptions.UnknownPacketError()
[ "async", "def", "receive", "(", "self", ",", "pkt", ")", ":", "self", ".", "server", ".", "logger", ".", "info", "(", "'%s: Received packet %s data %s'", ",", "self", ".", "sid", ",", "packet", ".", "packet_names", "[", "pkt", ".", "packet_type", "]", ",...
Receive packet from the client.
[ "Receive", "packet", "from", "the", "client", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_socket.py#L30-L48
train
198,338
miguelgrinberg/python-engineio
engineio/asyncio_socket.py
AsyncSocket.check_ping_timeout
async def check_ping_timeout(self): """Make sure the client is still sending pings. This helps detect disconnections for long-polling clients. """ if self.closed: raise exceptions.SocketIsClosedError() if time.time() - self.last_ping > self.server.ping_interval + 5: self.server.logger.info('%s: Client is gone, closing socket', self.sid) # Passing abort=False here will cause close() to write a # CLOSE packet. This has the effect of updating half-open sockets # to their correct state of disconnected await self.close(wait=False, abort=False) return False return True
python
async def check_ping_timeout(self): """Make sure the client is still sending pings. This helps detect disconnections for long-polling clients. """ if self.closed: raise exceptions.SocketIsClosedError() if time.time() - self.last_ping > self.server.ping_interval + 5: self.server.logger.info('%s: Client is gone, closing socket', self.sid) # Passing abort=False here will cause close() to write a # CLOSE packet. This has the effect of updating half-open sockets # to their correct state of disconnected await self.close(wait=False, abort=False) return False return True
[ "async", "def", "check_ping_timeout", "(", "self", ")", ":", "if", "self", ".", "closed", ":", "raise", "exceptions", ".", "SocketIsClosedError", "(", ")", "if", "time", ".", "time", "(", ")", "-", "self", ".", "last_ping", ">", "self", ".", "server", ...
Make sure the client is still sending pings. This helps detect disconnections for long-polling clients.
[ "Make", "sure", "the", "client", "is", "still", "sending", "pings", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_socket.py#L50-L65
train
198,339
miguelgrinberg/python-engineio
engineio/asyncio_socket.py
AsyncSocket.send
async def send(self, pkt): """Send a packet to the client.""" if not await self.check_ping_timeout(): return if self.upgrading: self.packet_backlog.append(pkt) else: await self.queue.put(pkt) self.server.logger.info('%s: Sending packet %s data %s', self.sid, packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
python
async def send(self, pkt): """Send a packet to the client.""" if not await self.check_ping_timeout(): return if self.upgrading: self.packet_backlog.append(pkt) else: await self.queue.put(pkt) self.server.logger.info('%s: Sending packet %s data %s', self.sid, packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
[ "async", "def", "send", "(", "self", ",", "pkt", ")", ":", "if", "not", "await", "self", ".", "check_ping_timeout", "(", ")", ":", "return", "if", "self", ".", "upgrading", ":", "self", ".", "packet_backlog", ".", "append", "(", "pkt", ")", "else", "...
Send a packet to the client.
[ "Send", "a", "packet", "to", "the", "client", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_socket.py#L67-L78
train
198,340
miguelgrinberg/python-engineio
engineio/asyncio_socket.py
AsyncSocket.handle_post_request
async def handle_post_request(self, environ): """Handle a long-polling POST request from the client.""" length = int(environ.get('CONTENT_LENGTH', '0')) if length > self.server.max_http_buffer_size: raise exceptions.ContentTooLongError() else: body = await environ['wsgi.input'].read(length) p = payload.Payload(encoded_payload=body) for pkt in p.packets: await self.receive(pkt)
python
async def handle_post_request(self, environ): """Handle a long-polling POST request from the client.""" length = int(environ.get('CONTENT_LENGTH', '0')) if length > self.server.max_http_buffer_size: raise exceptions.ContentTooLongError() else: body = await environ['wsgi.input'].read(length) p = payload.Payload(encoded_payload=body) for pkt in p.packets: await self.receive(pkt)
[ "async", "def", "handle_post_request", "(", "self", ",", "environ", ")", ":", "length", "=", "int", "(", "environ", ".", "get", "(", "'CONTENT_LENGTH'", ",", "'0'", ")", ")", "if", "length", ">", "self", ".", "server", ".", "max_http_buffer_size", ":", "...
Handle a long-polling POST request from the client.
[ "Handle", "a", "long", "-", "polling", "POST", "request", "from", "the", "client", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_socket.py#L98-L107
train
198,341
miguelgrinberg/python-engineio
engineio/asyncio_socket.py
AsyncSocket._upgrade_websocket
async def _upgrade_websocket(self, environ): """Upgrade the connection from polling to websocket.""" if self.upgraded: raise IOError('Socket has been upgraded already') if self.server._async['websocket'] is None: # the selected async mode does not support websocket return self.server._bad_request() ws = self.server._async['websocket'](self._websocket_handler) return await ws(environ)
python
async def _upgrade_websocket(self, environ): """Upgrade the connection from polling to websocket.""" if self.upgraded: raise IOError('Socket has been upgraded already') if self.server._async['websocket'] is None: # the selected async mode does not support websocket return self.server._bad_request() ws = self.server._async['websocket'](self._websocket_handler) return await ws(environ)
[ "async", "def", "_upgrade_websocket", "(", "self", ",", "environ", ")", ":", "if", "self", ".", "upgraded", ":", "raise", "IOError", "(", "'Socket has been upgraded already'", ")", "if", "self", ".", "server", ".", "_async", "[", "'websocket'", "]", "is", "N...
Upgrade the connection from polling to websocket.
[ "Upgrade", "the", "connection", "from", "polling", "to", "websocket", "." ]
261fd67103cb5d9a44369415748e66fdf62de6fb
https://github.com/miguelgrinberg/python-engineio/blob/261fd67103cb5d9a44369415748e66fdf62de6fb/engineio/asyncio_socket.py#L120-L128
train
198,342
bitshares/python-bitshares
bitsharesapi/exceptions.py
decodeRPCErrorMsg
def decodeRPCErrorMsg(e): """ Helper function to decode the raised Exception and give it a python Exception class """ found = re.search( ( "(10 assert_exception: Assert Exception\n|" "3030000 tx_missing_posting_auth)" ".*: (.*)\n" ), str(e), flags=re.M, ) if found: return found.group(2).strip() else: return str(e)
python
def decodeRPCErrorMsg(e): """ Helper function to decode the raised Exception and give it a python Exception class """ found = re.search( ( "(10 assert_exception: Assert Exception\n|" "3030000 tx_missing_posting_auth)" ".*: (.*)\n" ), str(e), flags=re.M, ) if found: return found.group(2).strip() else: return str(e)
[ "def", "decodeRPCErrorMsg", "(", "e", ")", ":", "found", "=", "re", ".", "search", "(", "(", "\"(10 assert_exception: Assert Exception\\n|\"", "\"3030000 tx_missing_posting_auth)\"", "\".*: (.*)\\n\"", ")", ",", "str", "(", "e", ")", ",", "flags", "=", "re", ".", ...
Helper function to decode the raised Exception and give it a python Exception class
[ "Helper", "function", "to", "decode", "the", "raised", "Exception", "and", "give", "it", "a", "python", "Exception", "class" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesapi/exceptions.py#L7-L23
train
198,343
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.transfer
def transfer(self, to, amount, asset, memo="", account=None, **kwargs): """ Transfer an asset to another account. :param str to: Recipient :param float amount: Amount to transfer :param str asset: Asset to transfer :param str memo: (optional) Memo, may begin with `#` for encrypted messaging :param str account: (optional) the source account for the transfer if not ``default_account`` """ from .memo import Memo if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) amount = Amount(amount, asset, blockchain_instance=self) to = Account(to, blockchain_instance=self) memoObj = Memo(from_account=account, to_account=to, blockchain_instance=self) op = operations.Transfer( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "from": account["id"], "to": to["id"], "amount": {"amount": int(amount), "asset_id": amount.asset["id"]}, "memo": memoObj.encrypt(memo), "prefix": self.prefix, } ) return self.finalizeOp(op, account, "active", **kwargs)
python
def transfer(self, to, amount, asset, memo="", account=None, **kwargs): """ Transfer an asset to another account. :param str to: Recipient :param float amount: Amount to transfer :param str asset: Asset to transfer :param str memo: (optional) Memo, may begin with `#` for encrypted messaging :param str account: (optional) the source account for the transfer if not ``default_account`` """ from .memo import Memo if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) amount = Amount(amount, asset, blockchain_instance=self) to = Account(to, blockchain_instance=self) memoObj = Memo(from_account=account, to_account=to, blockchain_instance=self) op = operations.Transfer( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "from": account["id"], "to": to["id"], "amount": {"amount": int(amount), "asset_id": amount.asset["id"]}, "memo": memoObj.encrypt(memo), "prefix": self.prefix, } ) return self.finalizeOp(op, account, "active", **kwargs)
[ "def", "transfer", "(", "self", ",", "to", ",", "amount", ",", "asset", ",", "memo", "=", "\"\"", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", ".", "memo", "import", "Memo", "if", "not", "account", ":", "if", "\"default_a...
Transfer an asset to another account. :param str to: Recipient :param float amount: Amount to transfer :param str asset: Asset to transfer :param str memo: (optional) Memo, may begin with `#` for encrypted messaging :param str account: (optional) the source account for the transfer if not ``default_account``
[ "Transfer", "an", "asset", "to", "another", "account", "." ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L128-L163
train
198,344
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.upgrade_account
def upgrade_account(self, account=None, **kwargs): """ Upgrade an account to Lifetime membership :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) op = operations.Account_upgrade( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account_to_upgrade": account["id"], "upgrade_to_lifetime_member": True, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
python
def upgrade_account(self, account=None, **kwargs): """ Upgrade an account to Lifetime membership :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) op = operations.Account_upgrade( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account_to_upgrade": account["id"], "upgrade_to_lifetime_member": True, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ "def", "upgrade_account", "(", "self", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ".", "config", "[", "\"default_acco...
Upgrade an account to Lifetime membership :param str account: (optional) the account to allow access to (defaults to ``default_account``)
[ "Upgrade", "an", "account", "to", "Lifetime", "membership" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L352-L372
train
198,345
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.allow
def allow( self, foreign, weight=None, permission="active", account=None, threshold=None, **kwargs ): """ Give additional access to an account by some other public key or account. :param str foreign: The foreign account that will obtain access :param int weight: (optional) The weight to use. If not define, the threshold will be used. If the weight is smaller than the threshold, additional signatures will be required. (defaults to threshold) :param str permission: (optional) The actual permission to modify (defaults to ``active``) :param str account: (optional) the account to allow access to (defaults to ``default_account``) :param int threshold: The threshold that needs to be reached by signatures to be able to interact """ from copy import deepcopy if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") if permission not in ["owner", "active"]: raise ValueError("Permission needs to be either 'owner', or 'active") account = Account(account, blockchain_instance=self) if not weight: weight = account[permission]["weight_threshold"] authority = deepcopy(account[permission]) try: pubkey = PublicKey(foreign, prefix=self.prefix) authority["key_auths"].append([str(pubkey), weight]) except Exception: try: foreign_account = Account(foreign, blockchain_instance=self) authority["account_auths"].append([foreign_account["id"], weight]) except Exception: raise ValueError("Unknown foreign account or invalid public key") if threshold: authority["weight_threshold"] = threshold self._test_weights_treshold(authority) op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], permission: authority, "extensions": {}, "prefix": self.prefix, } ) if permission == "owner": return self.finalizeOp(op, account["name"], "owner", **kwargs) else: return self.finalizeOp(op, account["name"], "active", **kwargs)
python
def allow( self, foreign, weight=None, permission="active", account=None, threshold=None, **kwargs ): """ Give additional access to an account by some other public key or account. :param str foreign: The foreign account that will obtain access :param int weight: (optional) The weight to use. If not define, the threshold will be used. If the weight is smaller than the threshold, additional signatures will be required. (defaults to threshold) :param str permission: (optional) The actual permission to modify (defaults to ``active``) :param str account: (optional) the account to allow access to (defaults to ``default_account``) :param int threshold: The threshold that needs to be reached by signatures to be able to interact """ from copy import deepcopy if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") if permission not in ["owner", "active"]: raise ValueError("Permission needs to be either 'owner', or 'active") account = Account(account, blockchain_instance=self) if not weight: weight = account[permission]["weight_threshold"] authority = deepcopy(account[permission]) try: pubkey = PublicKey(foreign, prefix=self.prefix) authority["key_auths"].append([str(pubkey), weight]) except Exception: try: foreign_account = Account(foreign, blockchain_instance=self) authority["account_auths"].append([foreign_account["id"], weight]) except Exception: raise ValueError("Unknown foreign account or invalid public key") if threshold: authority["weight_threshold"] = threshold self._test_weights_treshold(authority) op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], permission: authority, "extensions": {}, "prefix": self.prefix, } ) if permission == "owner": return self.finalizeOp(op, account["name"], "owner", **kwargs) else: return self.finalizeOp(op, account["name"], "active", **kwargs)
[ "def", "allow", "(", "self", ",", "foreign", ",", "weight", "=", "None", ",", "permission", "=", "\"active\"", ",", "account", "=", "None", ",", "threshold", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "copy", "import", "deepcopy", "if", ...
Give additional access to an account by some other public key or account. :param str foreign: The foreign account that will obtain access :param int weight: (optional) The weight to use. If not define, the threshold will be used. If the weight is smaller than the threshold, additional signatures will be required. (defaults to threshold) :param str permission: (optional) The actual permission to modify (defaults to ``active``) :param str account: (optional) the account to allow access to (defaults to ``default_account``) :param int threshold: The threshold that needs to be reached by signatures to be able to interact
[ "Give", "additional", "access", "to", "an", "account", "by", "some", "other", "public", "key", "or", "account", "." ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L391-L456
train
198,346
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.update_memo_key
def update_memo_key(self, key, account=None, **kwargs): """ Update an account's memo public key This method does **not** add any private keys to your wallet but merely changes the memo public key. :param str key: New memo public key :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") PublicKey(key, prefix=self.prefix) account = Account(account, blockchain_instance=self) account["options"]["memo_key"] = key op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": account["options"], "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
python
def update_memo_key(self, key, account=None, **kwargs): """ Update an account's memo public key This method does **not** add any private keys to your wallet but merely changes the memo public key. :param str key: New memo public key :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") PublicKey(key, prefix=self.prefix) account = Account(account, blockchain_instance=self) account["options"]["memo_key"] = key op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": account["options"], "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ "def", "update_memo_key", "(", "self", ",", "key", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ".", "config", "[", ...
Update an account's memo public key This method does **not** add any private keys to your wallet but merely changes the memo public key. :param str key: New memo public key :param str account: (optional) the account to allow access to (defaults to ``default_account``)
[ "Update", "an", "account", "s", "memo", "public", "key" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L541-L570
train
198,347
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.approveworker
def approveworker(self, workers, account=None, **kwargs): """ Approve a worker :param list workers: list of worker member name or id :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) options = account["options"] if not isinstance(workers, (list, set, tuple)): workers = {workers} for worker in workers: worker = Worker(worker, blockchain_instance=self) options["votes"].append(worker["vote_for"]) options["votes"] = list(set(options["votes"])) options["voting_account"] = "1.2.5" # Account("proxy-to-self")["id"] op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
python
def approveworker(self, workers, account=None, **kwargs): """ Approve a worker :param list workers: list of worker member name or id :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) options = account["options"] if not isinstance(workers, (list, set, tuple)): workers = {workers} for worker in workers: worker = Worker(worker, blockchain_instance=self) options["votes"].append(worker["vote_for"]) options["votes"] = list(set(options["votes"])) options["voting_account"] = "1.2.5" # Account("proxy-to-self")["id"] op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ "def", "approveworker", "(", "self", ",", "workers", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ".", "config", "[",...
Approve a worker :param list workers: list of worker member name or id :param str account: (optional) the account to allow access to (defaults to ``default_account``)
[ "Approve", "a", "worker" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L819-L852
train
198,348
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.set_proxy
def set_proxy(self, proxy_account, account=None, **kwargs): """ Set a specific proxy for account :param bitshares.account.Account proxy_account: Account to be proxied :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) proxy = Account(proxy_account, blockchain_instance=self) options = account["options"] options["voting_account"] = proxy["id"] op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
python
def set_proxy(self, proxy_account, account=None, **kwargs): """ Set a specific proxy for account :param bitshares.account.Account proxy_account: Account to be proxied :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) proxy = Account(proxy_account, blockchain_instance=self) options = account["options"] options["voting_account"] = proxy["id"] op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ "def", "set_proxy", "(", "self", ",", "proxy_account", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ".", "config", "[...
Set a specific proxy for account :param bitshares.account.Account proxy_account: Account to be proxied :param str account: (optional) the account to allow access to (defaults to ``default_account``)
[ "Set", "a", "specific", "proxy", "for", "account" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L895-L922
train
198,349
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.cancel
def cancel(self, orderNumbers, account=None, **kwargs): """ Cancels an order you have placed in a given market. Requires only the "orderNumbers". An order number takes the form ``1.7.xxx``. :param str orderNumbers: The Order Object ide of the form ``1.7.xxxx`` """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=False, blockchain_instance=self) if not isinstance(orderNumbers, (list, set, tuple)): orderNumbers = {orderNumbers} op = [] for order in orderNumbers: op.append( operations.Limit_order_cancel( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "fee_paying_account": account["id"], "order": order, "extensions": [], "prefix": self.prefix, } ) ) return self.finalizeOp(op, account["name"], "active", **kwargs)
python
def cancel(self, orderNumbers, account=None, **kwargs): """ Cancels an order you have placed in a given market. Requires only the "orderNumbers". An order number takes the form ``1.7.xxx``. :param str orderNumbers: The Order Object ide of the form ``1.7.xxxx`` """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=False, blockchain_instance=self) if not isinstance(orderNumbers, (list, set, tuple)): orderNumbers = {orderNumbers} op = [] for order in orderNumbers: op.append( operations.Limit_order_cancel( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "fee_paying_account": account["id"], "order": order, "extensions": [], "prefix": self.prefix, } ) ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ "def", "cancel", "(", "self", ",", "orderNumbers", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ".", "config", "[", ...
Cancels an order you have placed in a given market. Requires only the "orderNumbers". An order number takes the form ``1.7.xxx``. :param str orderNumbers: The Order Object ide of the form ``1.7.xxxx``
[ "Cancels", "an", "order", "you", "have", "placed", "in", "a", "given", "market", ".", "Requires", "only", "the", "orderNumbers", ".", "An", "order", "number", "takes", "the", "form", "1", ".", "7", ".", "xxx", "." ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L924-L955
train
198,350
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.vesting_balance_withdraw
def vesting_balance_withdraw(self, vesting_id, amount=None, account=None, **kwargs): """ Withdraw vesting balance :param str vesting_id: Id of the vesting object :param bitshares.amount.Amount Amount: to withdraw ("all" if not provided") :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) if not amount: obj = Vesting(vesting_id, blockchain_instance=self) amount = obj.claimable op = operations.Vesting_balance_withdraw( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "vesting_balance": vesting_id, "owner": account["id"], "amount": {"amount": int(amount), "asset_id": amount["asset"]["id"]}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active")
python
def vesting_balance_withdraw(self, vesting_id, amount=None, account=None, **kwargs): """ Withdraw vesting balance :param str vesting_id: Id of the vesting object :param bitshares.amount.Amount Amount: to withdraw ("all" if not provided") :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) if not amount: obj = Vesting(vesting_id, blockchain_instance=self) amount = obj.claimable op = operations.Vesting_balance_withdraw( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "vesting_balance": vesting_id, "owner": account["id"], "amount": {"amount": int(amount), "asset_id": amount["asset"]["id"]}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active")
[ "def", "vesting_balance_withdraw", "(", "self", ",", "vesting_id", ",", "amount", "=", "None", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "ac...
Withdraw vesting balance :param str vesting_id: Id of the vesting object :param bitshares.amount.Amount Amount: to withdraw ("all" if not provided") :param str account: (optional) the account to allow access to (defaults to ``default_account``)
[ "Withdraw", "vesting", "balance" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L957-L987
train
198,351
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.publish_price_feed
def publish_price_feed( self, symbol, settlement_price, cer=None, mssr=110, mcr=200, account=None ): """ Publish a price feed for a market-pegged asset :param str symbol: Symbol of the asset to publish feed for :param bitshares.price.Price settlement_price: Price for settlement :param bitshares.price.Price cer: Core exchange Rate (default ``settlement_price + 5%``) :param float mssr: Percentage for max short squeeze ratio (default: 110%) :param float mcr: Percentage for maintenance collateral ratio (default: 200%) :param str account: (optional) the account to allow access to (defaults to ``default_account``) .. note:: The ``account`` needs to be allowed to produce a price feed for ``symbol``. For witness produced feeds this means ``account`` is a witness account! """ assert mcr > 100 assert mssr > 100 assert isinstance( settlement_price, Price ), "settlement_price needs to be instance of `bitshares.price.Price`!" assert cer is None or isinstance( cer, Price ), "cer needs to be instance of `bitshares.price.Price`!" if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) asset = Asset(symbol, blockchain_instance=self, full=True) backing_asset = asset["bitasset_data"]["options"]["short_backing_asset"] assert ( asset["id"] == settlement_price["base"]["asset"]["id"] or asset["id"] == settlement_price["quote"]["asset"]["id"] ), "Price needs to contain the asset of the symbol you'd like to produce a feed for!" assert asset.is_bitasset, "Symbol needs to be a bitasset!" assert ( settlement_price["base"]["asset"]["id"] == backing_asset or settlement_price["quote"]["asset"]["id"] == backing_asset ), "The Price needs to be relative to the backing collateral!" settlement_price = settlement_price.as_base(symbol) if cer: cer = cer.as_base(symbol) if cer["quote"]["asset"]["id"] != "1.3.0": raise ValueError("CER must be defined against core asset '1.3.0'") else: if settlement_price["quote"]["asset"]["id"] != "1.3.0": raise ValueError( "CER must be manually provided because it relates to core asset '1.3.0'" ) cer = settlement_price.as_quote(symbol) * 0.95 op = operations.Asset_publish_feed( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "publisher": account["id"], "asset_id": asset["id"], "feed": { "settlement_price": settlement_price.as_base(symbol).json(), "core_exchange_rate": cer.as_base(symbol).json(), "maximum_short_squeeze_ratio": int(mssr * 10), "maintenance_collateral_ratio": int(mcr * 10), }, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active")
python
def publish_price_feed( self, symbol, settlement_price, cer=None, mssr=110, mcr=200, account=None ): """ Publish a price feed for a market-pegged asset :param str symbol: Symbol of the asset to publish feed for :param bitshares.price.Price settlement_price: Price for settlement :param bitshares.price.Price cer: Core exchange Rate (default ``settlement_price + 5%``) :param float mssr: Percentage for max short squeeze ratio (default: 110%) :param float mcr: Percentage for maintenance collateral ratio (default: 200%) :param str account: (optional) the account to allow access to (defaults to ``default_account``) .. note:: The ``account`` needs to be allowed to produce a price feed for ``symbol``. For witness produced feeds this means ``account`` is a witness account! """ assert mcr > 100 assert mssr > 100 assert isinstance( settlement_price, Price ), "settlement_price needs to be instance of `bitshares.price.Price`!" assert cer is None or isinstance( cer, Price ), "cer needs to be instance of `bitshares.price.Price`!" if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) asset = Asset(symbol, blockchain_instance=self, full=True) backing_asset = asset["bitasset_data"]["options"]["short_backing_asset"] assert ( asset["id"] == settlement_price["base"]["asset"]["id"] or asset["id"] == settlement_price["quote"]["asset"]["id"] ), "Price needs to contain the asset of the symbol you'd like to produce a feed for!" assert asset.is_bitasset, "Symbol needs to be a bitasset!" assert ( settlement_price["base"]["asset"]["id"] == backing_asset or settlement_price["quote"]["asset"]["id"] == backing_asset ), "The Price needs to be relative to the backing collateral!" settlement_price = settlement_price.as_base(symbol) if cer: cer = cer.as_base(symbol) if cer["quote"]["asset"]["id"] != "1.3.0": raise ValueError("CER must be defined against core asset '1.3.0'") else: if settlement_price["quote"]["asset"]["id"] != "1.3.0": raise ValueError( "CER must be manually provided because it relates to core asset '1.3.0'" ) cer = settlement_price.as_quote(symbol) * 0.95 op = operations.Asset_publish_feed( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "publisher": account["id"], "asset_id": asset["id"], "feed": { "settlement_price": settlement_price.as_base(symbol).json(), "core_exchange_rate": cer.as_base(symbol).json(), "maximum_short_squeeze_ratio": int(mssr * 10), "maintenance_collateral_ratio": int(mcr * 10), }, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active")
[ "def", "publish_price_feed", "(", "self", ",", "symbol", ",", "settlement_price", ",", "cer", "=", "None", ",", "mssr", "=", "110", ",", "mcr", "=", "200", ",", "account", "=", "None", ")", ":", "assert", "mcr", ">", "100", "assert", "mssr", ">", "10...
Publish a price feed for a market-pegged asset :param str symbol: Symbol of the asset to publish feed for :param bitshares.price.Price settlement_price: Price for settlement :param bitshares.price.Price cer: Core exchange Rate (default ``settlement_price + 5%``) :param float mssr: Percentage for max short squeeze ratio (default: 110%) :param float mcr: Percentage for maintenance collateral ratio (default: 200%) :param str account: (optional) the account to allow access to (defaults to ``default_account``) .. note:: The ``account`` needs to be allowed to produce a price feed for ``symbol``. For witness produced feeds this means ``account`` is a witness account!
[ "Publish", "a", "price", "feed", "for", "a", "market", "-", "pegged", "asset" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L989-L1062
train
198,352
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.update_witness
def update_witness(self, witness_identifier, url=None, key=None, **kwargs): """ Upgrade a witness account :param str witness_identifier: Identifier for the witness :param str url: New URL for the witness :param str key: Public Key for the signing """ witness = Witness(witness_identifier) account = witness.account op = operations.Witness_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "prefix": self.prefix, "witness": witness["id"], "witness_account": account["id"], "new_url": url, "new_signing_key": key, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
python
def update_witness(self, witness_identifier, url=None, key=None, **kwargs): """ Upgrade a witness account :param str witness_identifier: Identifier for the witness :param str url: New URL for the witness :param str key: Public Key for the signing """ witness = Witness(witness_identifier) account = witness.account op = operations.Witness_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "prefix": self.prefix, "witness": witness["id"], "witness_account": account["id"], "new_url": url, "new_signing_key": key, } ) return self.finalizeOp(op, account["name"], "active", **kwargs)
[ "def", "update_witness", "(", "self", ",", "witness_identifier", ",", "url", "=", "None", ",", "key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "witness", "=", "Witness", "(", "witness_identifier", ")", "account", "=", "witness", ".", "account", "o...
Upgrade a witness account :param str witness_identifier: Identifier for the witness :param str url: New URL for the witness :param str key: Public Key for the signing
[ "Upgrade", "a", "witness", "account" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L1106-L1125
train
198,353
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.create_worker
def create_worker( self, name, daily_pay, end, url="", begin=None, payment_type="vesting", pay_vesting_period_days=0, account=None, **kwargs ): """ Create a worker This removes the shares from the supply **Required** :param str name: Name of the worke :param bitshares.amount.Amount daily_pay: The amount to be paid daily :param datetime end: Date/time of end of the worker **Optional** :param str url: URL to read more about the worker :param datetime begin: Date/time of begin of the worker :param string payment_type: ["burn", "refund", "vesting"] (default: "vesting") :param int pay_vesting_period_days: Days of vesting (default: 0) :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ from bitsharesbase.transactions import timeformat assert isinstance(daily_pay, Amount) assert daily_pay["asset"]["id"] == "1.3.0" if not begin: begin = datetime.utcnow() + timedelta(seconds=30) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) if payment_type == "refund": initializer = [0, {}] elif payment_type == "vesting": initializer = [1, {"pay_vesting_period_days": pay_vesting_period_days}] elif payment_type == "burn": initializer = [2, {}] else: raise ValueError('payment_type not in ["burn", "refund", "vesting"]') op = operations.Worker_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "owner": account["id"], "work_begin_date": begin.strftime(timeformat), "work_end_date": end.strftime(timeformat), "daily_pay": int(daily_pay), "name": name, "url": url, "initializer": initializer, } ) return self.finalizeOp(op, account, "active", **kwargs)
python
def create_worker( self, name, daily_pay, end, url="", begin=None, payment_type="vesting", pay_vesting_period_days=0, account=None, **kwargs ): """ Create a worker This removes the shares from the supply **Required** :param str name: Name of the worke :param bitshares.amount.Amount daily_pay: The amount to be paid daily :param datetime end: Date/time of end of the worker **Optional** :param str url: URL to read more about the worker :param datetime begin: Date/time of begin of the worker :param string payment_type: ["burn", "refund", "vesting"] (default: "vesting") :param int pay_vesting_period_days: Days of vesting (default: 0) :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ from bitsharesbase.transactions import timeformat assert isinstance(daily_pay, Amount) assert daily_pay["asset"]["id"] == "1.3.0" if not begin: begin = datetime.utcnow() + timedelta(seconds=30) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) if payment_type == "refund": initializer = [0, {}] elif payment_type == "vesting": initializer = [1, {"pay_vesting_period_days": pay_vesting_period_days}] elif payment_type == "burn": initializer = [2, {}] else: raise ValueError('payment_type not in ["burn", "refund", "vesting"]') op = operations.Worker_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "owner": account["id"], "work_begin_date": begin.strftime(timeformat), "work_end_date": end.strftime(timeformat), "daily_pay": int(daily_pay), "name": name, "url": url, "initializer": initializer, } ) return self.finalizeOp(op, account, "active", **kwargs)
[ "def", "create_worker", "(", "self", ",", "name", ",", "daily_pay", ",", "end", ",", "url", "=", "\"\"", ",", "begin", "=", "None", ",", "payment_type", "=", "\"vesting\"", ",", "pay_vesting_period_days", "=", "0", ",", "account", "=", "None", ",", "*", ...
Create a worker This removes the shares from the supply **Required** :param str name: Name of the worke :param bitshares.amount.Amount daily_pay: The amount to be paid daily :param datetime end: Date/time of end of the worker **Optional** :param str url: URL to read more about the worker :param datetime begin: Date/time of begin of the worker :param string payment_type: ["burn", "refund", "vesting"] (default: "vesting") :param int pay_vesting_period_days: Days of vesting (default: 0) :param str account: (optional) the account to allow access to (defaults to ``default_account``)
[ "Create", "a", "worker" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L1156-L1223
train
198,354
bitshares/python-bitshares
bitshares/bitshares.py
BitShares.create_committee_member
def create_committee_member(self, url="", account=None, **kwargs): """ Create a committee member :param str url: URL to read more about the worker :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) op = operations.Committee_member_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "committee_member_account": account["id"], "url": url, } ) return self.finalizeOp(op, account, "active", **kwargs)
python
def create_committee_member(self, url="", account=None, **kwargs): """ Create a committee member :param str url: URL to read more about the worker :param str account: (optional) the account to allow access to (defaults to ``default_account``) """ if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) op = operations.Committee_member_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "committee_member_account": account["id"], "url": url, } ) return self.finalizeOp(op, account, "active", **kwargs)
[ "def", "create_committee_member", "(", "self", ",", "url", "=", "\"\"", ",", "account", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "config", ":", "account", "=", "self", ...
Create a committee member :param str url: URL to read more about the worker :param str account: (optional) the account to allow access to (defaults to ``default_account``)
[ "Create", "a", "committee", "member" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/bitshares.py#L1253-L1274
train
198,355
bitshares/python-bitshares
bitshares/notify.py
Notify.reset_subscriptions
def reset_subscriptions(self, accounts=[], markets=[], objects=[]): """Change the subscriptions of a running Notify instance """ self.websocket.reset_subscriptions( accounts, self.get_market_ids(markets), objects )
python
def reset_subscriptions(self, accounts=[], markets=[], objects=[]): """Change the subscriptions of a running Notify instance """ self.websocket.reset_subscriptions( accounts, self.get_market_ids(markets), objects )
[ "def", "reset_subscriptions", "(", "self", ",", "accounts", "=", "[", "]", ",", "markets", "=", "[", "]", ",", "objects", "=", "[", "]", ")", ":", "self", ".", "websocket", ".", "reset_subscriptions", "(", "accounts", ",", "self", ".", "get_market_ids", ...
Change the subscriptions of a running Notify instance
[ "Change", "the", "subscriptions", "of", "a", "running", "Notify", "instance" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/notify.py#L108-L113
train
198,356
bitshares/python-bitshares
bitshares/notify.py
Notify.process_market
def process_market(self, data): """ This method is used for post processing of market notifications. It will return instances of either * :class:`bitshares.price.Order` or * :class:`bitshares.price.FilledOrder` or * :class:`bitshares.price.UpdateCallOrder` Also possible are limit order updates (margin calls) """ for d in data: if not d: continue if isinstance(d, str): # Single order has been placed log.debug("Calling on_market with Order()") self.on_market(Order(d, blockchain_instance=self.blockchain)) continue elif isinstance(d, dict): d = [d] # Orders have been matched for p in d: if not isinstance(p, list): p = [p] for i in p: if isinstance(i, dict): if "pays" in i and "receives" in i: self.on_market( FilledOrder(i, blockchain_instance=self.blockchain) ) elif "for_sale" in i and "sell_price" in i: self.on_market( Order(i, blockchain_instance=self.blockchain) ) elif "collateral" in i and "call_price" in i: self.on_market( UpdateCallOrder(i, blockchain_instance=self.blockchain) ) else: if i: log.error("Unknown market update type: %s" % i)
python
def process_market(self, data): """ This method is used for post processing of market notifications. It will return instances of either * :class:`bitshares.price.Order` or * :class:`bitshares.price.FilledOrder` or * :class:`bitshares.price.UpdateCallOrder` Also possible are limit order updates (margin calls) """ for d in data: if not d: continue if isinstance(d, str): # Single order has been placed log.debug("Calling on_market with Order()") self.on_market(Order(d, blockchain_instance=self.blockchain)) continue elif isinstance(d, dict): d = [d] # Orders have been matched for p in d: if not isinstance(p, list): p = [p] for i in p: if isinstance(i, dict): if "pays" in i and "receives" in i: self.on_market( FilledOrder(i, blockchain_instance=self.blockchain) ) elif "for_sale" in i and "sell_price" in i: self.on_market( Order(i, blockchain_instance=self.blockchain) ) elif "collateral" in i and "call_price" in i: self.on_market( UpdateCallOrder(i, blockchain_instance=self.blockchain) ) else: if i: log.error("Unknown market update type: %s" % i)
[ "def", "process_market", "(", "self", ",", "data", ")", ":", "for", "d", "in", "data", ":", "if", "not", "d", ":", "continue", "if", "isinstance", "(", "d", ",", "str", ")", ":", "# Single order has been placed", "log", ".", "debug", "(", "\"Calling on_m...
This method is used for post processing of market notifications. It will return instances of either * :class:`bitshares.price.Order` or * :class:`bitshares.price.FilledOrder` or * :class:`bitshares.price.UpdateCallOrder` Also possible are limit order updates (margin calls)
[ "This", "method", "is", "used", "for", "post", "processing", "of", "market", "notifications", ".", "It", "will", "return", "instances", "of", "either" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/notify.py#L120-L162
train
198,357
bitshares/python-bitshares
bitshares/dex.py
Dex.returnFees
def returnFees(self): """ Returns a dictionary of all fees that apply through the network Example output: .. code-block:: js {'proposal_create': {'fee': 400000.0}, 'asset_publish_feed': {'fee': 1000.0}, 'account_create': {'basic_fee': 950000.0, 'price_per_kbyte': 20000.0, 'premium_fee': 40000000.0}, 'custom': {'fee': 20000.0}, 'asset_fund_fee_pool': {'fee': 20000.0}, 'override_transfer': {'fee': 400000.0}, 'fill_order': {}, 'asset_update': {'price_per_kbyte': 20000.0, 'fee': 200000.0}, 'asset_update_feed_producers': {'fee': 10000000.0}, 'assert': {'fee': 20000.0}, 'committee_member_create': {'fee': 100000000.0}} """ from bitsharesbase.operations import operations r = {} obj, base = self.blockchain.rpc.get_objects(["2.0.0", "1.3.0"]) fees = obj["parameters"]["current_fees"]["parameters"] scale = float(obj["parameters"]["current_fees"]["scale"]) for f in fees: op_name = "unknown %d" % f[0] for name in operations: if operations[name] == f[0]: op_name = name fs = f[1] for _type in fs: fs[_type] = float(fs[_type]) * scale / 1e4 / 10 ** base["precision"] r[op_name] = fs return r
python
def returnFees(self): """ Returns a dictionary of all fees that apply through the network Example output: .. code-block:: js {'proposal_create': {'fee': 400000.0}, 'asset_publish_feed': {'fee': 1000.0}, 'account_create': {'basic_fee': 950000.0, 'price_per_kbyte': 20000.0, 'premium_fee': 40000000.0}, 'custom': {'fee': 20000.0}, 'asset_fund_fee_pool': {'fee': 20000.0}, 'override_transfer': {'fee': 400000.0}, 'fill_order': {}, 'asset_update': {'price_per_kbyte': 20000.0, 'fee': 200000.0}, 'asset_update_feed_producers': {'fee': 10000000.0}, 'assert': {'fee': 20000.0}, 'committee_member_create': {'fee': 100000000.0}} """ from bitsharesbase.operations import operations r = {} obj, base = self.blockchain.rpc.get_objects(["2.0.0", "1.3.0"]) fees = obj["parameters"]["current_fees"]["parameters"] scale = float(obj["parameters"]["current_fees"]["scale"]) for f in fees: op_name = "unknown %d" % f[0] for name in operations: if operations[name] == f[0]: op_name = name fs = f[1] for _type in fs: fs[_type] = float(fs[_type]) * scale / 1e4 / 10 ** base["precision"] r[op_name] = fs return r
[ "def", "returnFees", "(", "self", ")", ":", "from", "bitsharesbase", ".", "operations", "import", "operations", "r", "=", "{", "}", "obj", ",", "base", "=", "self", ".", "blockchain", ".", "rpc", ".", "get_objects", "(", "[", "\"2.0.0\"", ",", "\"1.3.0\"...
Returns a dictionary of all fees that apply through the network Example output: .. code-block:: js {'proposal_create': {'fee': 400000.0}, 'asset_publish_feed': {'fee': 1000.0}, 'account_create': {'basic_fee': 950000.0, 'price_per_kbyte': 20000.0, 'premium_fee': 40000000.0}, 'custom': {'fee': 20000.0}, 'asset_fund_fee_pool': {'fee': 20000.0}, 'override_transfer': {'fee': 400000.0}, 'fill_order': {}, 'asset_update': {'price_per_kbyte': 20000.0, 'fee': 200000.0}, 'asset_update_feed_producers': {'fee': 10000000.0}, 'assert': {'fee': 20000.0}, 'committee_member_create': {'fee': 100000000.0}}
[ "Returns", "a", "dictionary", "of", "all", "fees", "that", "apply", "through", "the", "network" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/dex.py#L26-L61
train
198,358
bitshares/python-bitshares
bitshares/dex.py
Dex.close_debt_position
def close_debt_position(self, symbol, account=None): """ Close a debt position and reclaim the collateral :param str symbol: Symbol to close debt position for :raises ValueError: if symbol has no open call position """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) debts = self.list_debt_positions(account) if symbol not in debts: raise ValueError("No call position open for %s" % symbol) debt = debts[symbol] asset = debt["debt"]["asset"] collateral_asset = debt["collateral"]["asset"] op = operations.Call_order_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "delta_debt": { "amount": int(-float(debt["debt"]) * 10 ** asset["precision"]), "asset_id": asset["id"], }, "delta_collateral": { "amount": int( -float(debt["collateral"]) * 10 ** collateral_asset["precision"] ), "asset_id": collateral_asset["id"], }, "funding_account": account["id"], "extensions": [], } ) return self.blockchain.finalizeOp(op, account["name"], "active")
python
def close_debt_position(self, symbol, account=None): """ Close a debt position and reclaim the collateral :param str symbol: Symbol to close debt position for :raises ValueError: if symbol has no open call position """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) debts = self.list_debt_positions(account) if symbol not in debts: raise ValueError("No call position open for %s" % symbol) debt = debts[symbol] asset = debt["debt"]["asset"] collateral_asset = debt["collateral"]["asset"] op = operations.Call_order_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "delta_debt": { "amount": int(-float(debt["debt"]) * 10 ** asset["precision"]), "asset_id": asset["id"], }, "delta_collateral": { "amount": int( -float(debt["collateral"]) * 10 ** collateral_asset["precision"] ), "asset_id": collateral_asset["id"], }, "funding_account": account["id"], "extensions": [], } ) return self.blockchain.finalizeOp(op, account["name"], "active")
[ "def", "close_debt_position", "(", "self", ",", "symbol", ",", "account", "=", "None", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "blockchain", ".", "config", ":", "account", "=", "self", ".", "blockchain", ".", ...
Close a debt position and reclaim the collateral :param str symbol: Symbol to close debt position for :raises ValueError: if symbol has no open call position
[ "Close", "a", "debt", "position", "and", "reclaim", "the", "collateral" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/dex.py#L121-L156
train
198,359
bitshares/python-bitshares
bitshares/dex.py
Dex.adjust_debt
def adjust_debt( self, delta, new_collateral_ratio=None, account=None, target_collateral_ratio=None, ): """ Adjust the amount of debt for an asset :param Amount delta: Delta amount of the debt (-10 means reduce debt by 10, +10 means borrow another 10) :param float new_collateral_ratio: collateral ratio to maintain (optional, by default tries to maintain old ratio) :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) # We sell quote and pay with base symbol = delta["symbol"] asset = Asset(symbol, full=True, blockchain_instance=self.blockchain) if not asset.is_bitasset: raise ValueError("%s is not a bitasset!" % symbol) bitasset = asset["bitasset_data"] # Check minimum collateral ratio backing_asset_id = bitasset["options"]["short_backing_asset"] current_debts = self.list_debt_positions(account) if not new_collateral_ratio and symbol not in current_debts: new_collateral_ratio = ( bitasset["current_feed"]["maintenance_collateral_ratio"] / 1000 ) elif not new_collateral_ratio and symbol in current_debts: new_collateral_ratio = current_debts[symbol]["ratio"] # Derive Amount of Collateral collateral_asset = Asset(backing_asset_id, blockchain_instance=self.blockchain) settlement_price = Price( bitasset["current_feed"]["settlement_price"], blockchain_instance=self.blockchain, ) if symbol in current_debts: amount_of_collateral = ( (float(current_debts[symbol]["debt"]) + float(delta["amount"])) * new_collateral_ratio / float(settlement_price) ) amount_of_collateral -= float(current_debts[symbol]["collateral"]) else: amount_of_collateral = ( float(delta["amount"]) * new_collateral_ratio / float(settlement_price) ) # Verify that enough funds are available fundsNeeded = amount_of_collateral + float( self.returnFees()["call_order_update"]["fee"] ) fundsHave = account.balance(collateral_asset["symbol"]) or 0 if fundsHave <= fundsNeeded: raise ValueError( "Not enough funds available. Need %f %s, but only %f %s are available" % ( fundsNeeded, collateral_asset["symbol"], fundsHave, collateral_asset["symbol"], ) ) payload = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "delta_debt": { "amount": int(float(delta) * 10 ** asset["precision"]), "asset_id": asset["id"], }, "delta_collateral": { "amount": int( float(amount_of_collateral) * 10 ** collateral_asset["precision"] ), "asset_id": collateral_asset["id"], }, "funding_account": account["id"], "extensions": {}, } # Extension if target_collateral_ratio: payload["extensions"].update( dict(target_collateral_ratio=int(target_collateral_ratio * 100)) ) op = operations.Call_order_update(**payload) return self.blockchain.finalizeOp(op, account["name"], "active")
python
def adjust_debt( self, delta, new_collateral_ratio=None, account=None, target_collateral_ratio=None, ): """ Adjust the amount of debt for an asset :param Amount delta: Delta amount of the debt (-10 means reduce debt by 10, +10 means borrow another 10) :param float new_collateral_ratio: collateral ratio to maintain (optional, by default tries to maintain old ratio) :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) # We sell quote and pay with base symbol = delta["symbol"] asset = Asset(symbol, full=True, blockchain_instance=self.blockchain) if not asset.is_bitasset: raise ValueError("%s is not a bitasset!" % symbol) bitasset = asset["bitasset_data"] # Check minimum collateral ratio backing_asset_id = bitasset["options"]["short_backing_asset"] current_debts = self.list_debt_positions(account) if not new_collateral_ratio and symbol not in current_debts: new_collateral_ratio = ( bitasset["current_feed"]["maintenance_collateral_ratio"] / 1000 ) elif not new_collateral_ratio and symbol in current_debts: new_collateral_ratio = current_debts[symbol]["ratio"] # Derive Amount of Collateral collateral_asset = Asset(backing_asset_id, blockchain_instance=self.blockchain) settlement_price = Price( bitasset["current_feed"]["settlement_price"], blockchain_instance=self.blockchain, ) if symbol in current_debts: amount_of_collateral = ( (float(current_debts[symbol]["debt"]) + float(delta["amount"])) * new_collateral_ratio / float(settlement_price) ) amount_of_collateral -= float(current_debts[symbol]["collateral"]) else: amount_of_collateral = ( float(delta["amount"]) * new_collateral_ratio / float(settlement_price) ) # Verify that enough funds are available fundsNeeded = amount_of_collateral + float( self.returnFees()["call_order_update"]["fee"] ) fundsHave = account.balance(collateral_asset["symbol"]) or 0 if fundsHave <= fundsNeeded: raise ValueError( "Not enough funds available. Need %f %s, but only %f %s are available" % ( fundsNeeded, collateral_asset["symbol"], fundsHave, collateral_asset["symbol"], ) ) payload = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "delta_debt": { "amount": int(float(delta) * 10 ** asset["precision"]), "asset_id": asset["id"], }, "delta_collateral": { "amount": int( float(amount_of_collateral) * 10 ** collateral_asset["precision"] ), "asset_id": collateral_asset["id"], }, "funding_account": account["id"], "extensions": {}, } # Extension if target_collateral_ratio: payload["extensions"].update( dict(target_collateral_ratio=int(target_collateral_ratio * 100)) ) op = operations.Call_order_update(**payload) return self.blockchain.finalizeOp(op, account["name"], "active")
[ "def", "adjust_debt", "(", "self", ",", "delta", ",", "new_collateral_ratio", "=", "None", ",", "account", "=", "None", ",", "target_collateral_ratio", "=", "None", ",", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", ...
Adjust the amount of debt for an asset :param Amount delta: Delta amount of the debt (-10 means reduce debt by 10, +10 means borrow another 10) :param float new_collateral_ratio: collateral ratio to maintain (optional, by default tries to maintain old ratio) :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available
[ "Adjust", "the", "amount", "of", "debt", "for", "an", "asset" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/dex.py#L158-L260
train
198,360
bitshares/python-bitshares
bitshares/dex.py
Dex.adjust_collateral_ratio
def adjust_collateral_ratio( self, symbol, new_collateral_ratio, account=None, target_collateral_ratio=None ): """ Adjust the collataral ratio of a debt position :param Asset amount: Amount to borrow (denoted in 'asset') :param float new_collateral_ratio: desired collateral ratio :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) current_debts = self.list_debt_positions(account) if symbol not in current_debts: raise ValueError( "No Call position available to adjust! Please borrow first!" ) return self.adjust_debt( Amount(0, symbol), new_collateral_ratio, account, target_collateral_ratio=target_collateral_ratio, )
python
def adjust_collateral_ratio( self, symbol, new_collateral_ratio, account=None, target_collateral_ratio=None ): """ Adjust the collataral ratio of a debt position :param Asset amount: Amount to borrow (denoted in 'asset') :param float new_collateral_ratio: desired collateral ratio :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available """ if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) current_debts = self.list_debt_positions(account) if symbol not in current_debts: raise ValueError( "No Call position available to adjust! Please borrow first!" ) return self.adjust_debt( Amount(0, symbol), new_collateral_ratio, account, target_collateral_ratio=target_collateral_ratio, )
[ "def", "adjust_collateral_ratio", "(", "self", ",", "symbol", ",", "new_collateral_ratio", ",", "account", "=", "None", ",", "target_collateral_ratio", "=", "None", ")", ":", "if", "not", "account", ":", "if", "\"default_account\"", "in", "self", ".", "blockchai...
Adjust the collataral ratio of a debt position :param Asset amount: Amount to borrow (denoted in 'asset') :param float new_collateral_ratio: desired collateral ratio :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available
[ "Adjust", "the", "collataral", "ratio", "of", "a", "debt", "position" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitshares/dex.py#L262-L292
train
198,361
bitshares/python-bitshares
bitsharesbase/operationids.py
getOperationNameForId
def getOperationNameForId(i): """ Convert an operation id into the corresponding string """ for key in operations: if int(operations[key]) is int(i): return key return "Unknown Operation ID %d" % i
python
def getOperationNameForId(i): """ Convert an operation id into the corresponding string """ for key in operations: if int(operations[key]) is int(i): return key return "Unknown Operation ID %d" % i
[ "def", "getOperationNameForId", "(", "i", ")", ":", "for", "key", "in", "operations", ":", "if", "int", "(", "operations", "[", "key", "]", ")", "is", "int", "(", "i", ")", ":", "return", "key", "return", "\"Unknown Operation ID %d\"", "%", "i" ]
Convert an operation id into the corresponding string
[ "Convert", "an", "operation", "id", "into", "the", "corresponding", "string" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesbase/operationids.py#L62-L68
train
198,362
bitshares/python-bitshares
bitsharesbase/operationids.py
getOperationName
def getOperationName(id: str): """ This method returns the name representation of an operation given its value as used in the API """ if isinstance(id, str): # Some graphene chains (e.g. steem) do not encode the # operation_type as id but in its string form assert id in operations.keys(), "Unknown operation {}".format(id) return id elif isinstance(id, int): return getOperationNameForId(id) else: raise ValueError
python
def getOperationName(id: str): """ This method returns the name representation of an operation given its value as used in the API """ if isinstance(id, str): # Some graphene chains (e.g. steem) do not encode the # operation_type as id but in its string form assert id in operations.keys(), "Unknown operation {}".format(id) return id elif isinstance(id, int): return getOperationNameForId(id) else: raise ValueError
[ "def", "getOperationName", "(", "id", ":", "str", ")", ":", "if", "isinstance", "(", "id", ",", "str", ")", ":", "# Some graphene chains (e.g. steem) do not encode the", "# operation_type as id but in its string form", "assert", "id", "in", "operations", ".", "keys", ...
This method returns the name representation of an operation given its value as used in the API
[ "This", "method", "returns", "the", "name", "representation", "of", "an", "operation", "given", "its", "value", "as", "used", "in", "the", "API" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesbase/operationids.py#L71-L83
train
198,363
bitshares/python-bitshares
bitsharesapi/bitsharesnoderpc.py
BitSharesNodeRPC.get_account
def get_account(self, name, **kwargs): """ Get full account details from account name or id :param str name: Account name or account id """ if len(name.split(".")) == 3: return self.get_objects([name])[0] else: return self.get_account_by_name(name, **kwargs)
python
def get_account(self, name, **kwargs): """ Get full account details from account name or id :param str name: Account name or account id """ if len(name.split(".")) == 3: return self.get_objects([name])[0] else: return self.get_account_by_name(name, **kwargs)
[ "def", "get_account", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "name", ".", "split", "(", "\".\"", ")", ")", "==", "3", ":", "return", "self", ".", "get_objects", "(", "[", "name", "]", ")", "[", "0", "]", ...
Get full account details from account name or id :param str name: Account name or account id
[ "Get", "full", "account", "details", "from", "account", "name", "or", "id" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesapi/bitsharesnoderpc.py#L43-L51
train
198,364
bitshares/python-bitshares
bitsharesapi/bitsharesnoderpc.py
BitSharesNodeRPC.get_asset
def get_asset(self, name, **kwargs): """ Get full asset from name of id :param str name: Symbol name or asset id (e.g. 1.3.0) """ if len(name.split(".")) == 3: return self.get_objects([name], **kwargs)[0] else: return self.lookup_asset_symbols([name], **kwargs)[0]
python
def get_asset(self, name, **kwargs): """ Get full asset from name of id :param str name: Symbol name or asset id (e.g. 1.3.0) """ if len(name.split(".")) == 3: return self.get_objects([name], **kwargs)[0] else: return self.lookup_asset_symbols([name], **kwargs)[0]
[ "def", "get_asset", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "name", ".", "split", "(", "\".\"", ")", ")", "==", "3", ":", "return", "self", ".", "get_objects", "(", "[", "name", "]", ",", "*", "*", "kwargs...
Get full asset from name of id :param str name: Symbol name or asset id (e.g. 1.3.0)
[ "Get", "full", "asset", "from", "name", "of", "id" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesapi/bitsharesnoderpc.py#L53-L61
train
198,365
bitshares/python-bitshares
bitsharesapi/websocket.py
BitSharesWebsocket.process_notice
def process_notice(self, notice): """ This method is called on notices that need processing. Here, we call ``on_object`` and ``on_account`` slots. """ id = notice["id"] _a, _b, _ = id.split(".") if id in self.subscription_objects: self.on_object(notice) elif ".".join([_a, _b, "x"]) in self.subscription_objects: self.on_object(notice) elif id[:4] == "2.6.": # Treat account updates separately self.on_account(notice)
python
def process_notice(self, notice): """ This method is called on notices that need processing. Here, we call ``on_object`` and ``on_account`` slots. """ id = notice["id"] _a, _b, _ = id.split(".") if id in self.subscription_objects: self.on_object(notice) elif ".".join([_a, _b, "x"]) in self.subscription_objects: self.on_object(notice) elif id[:4] == "2.6.": # Treat account updates separately self.on_account(notice)
[ "def", "process_notice", "(", "self", ",", "notice", ")", ":", "id", "=", "notice", "[", "\"id\"", "]", "_a", ",", "_b", ",", "_", "=", "id", ".", "split", "(", "\".\"", ")", "if", "id", "in", "self", ".", "subscription_objects", ":", "self", ".", ...
This method is called on notices that need processing. Here, we call ``on_object`` and ``on_account`` slots.
[ "This", "method", "is", "called", "on", "notices", "that", "need", "processing", ".", "Here", "we", "call", "on_object", "and", "on_account", "slots", "." ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesapi/websocket.py#L213-L229
train
198,366
bitshares/python-bitshares
bitsharesapi/websocket.py
BitSharesWebsocket.close
def close(self, *args, **kwargs): """ Closes the websocket connection and waits for the ping thread to close """ self.run_event.set() self.ws.close() if self.keepalive and self.keepalive.is_alive(): self.keepalive.join()
python
def close(self, *args, **kwargs): """ Closes the websocket connection and waits for the ping thread to close """ self.run_event.set() self.ws.close() if self.keepalive and self.keepalive.is_alive(): self.keepalive.join()
[ "def", "close", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "run_event", ".", "set", "(", ")", "self", ".", "ws", ".", "close", "(", ")", "if", "self", ".", "keepalive", "and", "self", ".", "keepalive", ".", "...
Closes the websocket connection and waits for the ping thread to close
[ "Closes", "the", "websocket", "connection", "and", "waits", "for", "the", "ping", "thread", "to", "close" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesapi/websocket.py#L330-L337
train
198,367
bitshares/python-bitshares
bitsharesapi/websocket.py
BitSharesWebsocket.rpcexec
def rpcexec(self, payload): """ Execute a call by sending the payload :param dict payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises RPCError: if the server returns an error """ log.debug(json.dumps(payload)) self.ws.send(json.dumps(payload, ensure_ascii=False).encode("utf8"))
python
def rpcexec(self, payload): """ Execute a call by sending the payload :param dict payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises RPCError: if the server returns an error """ log.debug(json.dumps(payload)) self.ws.send(json.dumps(payload, ensure_ascii=False).encode("utf8"))
[ "def", "rpcexec", "(", "self", ",", "payload", ")", ":", "log", ".", "debug", "(", "json", ".", "dumps", "(", "payload", ")", ")", "self", ".", "ws", ".", "send", "(", "json", ".", "dumps", "(", "payload", ",", "ensure_ascii", "=", "False", ")", ...
Execute a call by sending the payload :param dict payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises RPCError: if the server returns an error
[ "Execute", "a", "call", "by", "sending", "the", "payload" ]
8a3b5954a6abcaaff7c6a5c41d910e58eea3142f
https://github.com/bitshares/python-bitshares/blob/8a3b5954a6abcaaff7c6a5c41d910e58eea3142f/bitsharesapi/websocket.py#L346-L354
train
198,368
fastai/fastprogress
fastprogress/fastprogress.py
text2html_table
def text2html_table(items): "Put the texts in `items` in an HTML table." html_code = f"""<table border="1" class="dataframe">\n""" html_code += f""" <thead>\n <tr style="text-align: left;">\n""" for i in items[0]: html_code += f" <th>{i}</th>\n" html_code += f" </tr>\n </thead>\n <tbody>\n" for line in items[1:]: html_code += " <tr>\n" for i in line: html_code += f" <td>{i}</td>\n" html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code
python
def text2html_table(items): "Put the texts in `items` in an HTML table." html_code = f"""<table border="1" class="dataframe">\n""" html_code += f""" <thead>\n <tr style="text-align: left;">\n""" for i in items[0]: html_code += f" <th>{i}</th>\n" html_code += f" </tr>\n </thead>\n <tbody>\n" for line in items[1:]: html_code += " <tr>\n" for i in line: html_code += f" <td>{i}</td>\n" html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code
[ "def", "text2html_table", "(", "items", ")", ":", "html_code", "=", "f\"\"\"<table border=\"1\" class=\"dataframe\">\\n\"\"\"", "html_code", "+=", "f\"\"\" <thead>\\n <tr style=\"text-align: left;\">\\n\"\"\"", "for", "i", "in", "items", "[", "0", "]", ":", "html_code", ...
Put the texts in `items` in an HTML table.
[ "Put", "the", "texts", "in", "items", "in", "an", "HTML", "table", "." ]
7eed926b830690d231663d9c03017bacafd0c2e5
https://github.com/fastai/fastprogress/blob/7eed926b830690d231663d9c03017bacafd0c2e5/fastprogress/fastprogress.py#L143-L154
train
198,369
TeamHG-Memex/tensorboard_logger
tensorboard_logger/tensorboard_logger.py
Logger.log_value
def log_value(self, name, value, step=None): """Log new value for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (float): this is a real number to be logged as a scalar. step (int): non-negative integer used for visualization: you can log several different variables on one step, but should not log different values of the same variable on the same step (this is not checked). """ if isinstance(value, six.string_types): raise TypeError('"value" should be a number, got {}' .format(type(value))) value = float(value) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._scalar_summary(tf_name, value, step) self._log_summary(tf_name, summary, value, step=step)
python
def log_value(self, name, value, step=None): """Log new value for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (float): this is a real number to be logged as a scalar. step (int): non-negative integer used for visualization: you can log several different variables on one step, but should not log different values of the same variable on the same step (this is not checked). """ if isinstance(value, six.string_types): raise TypeError('"value" should be a number, got {}' .format(type(value))) value = float(value) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._scalar_summary(tf_name, value, step) self._log_summary(tf_name, summary, value, step=step)
[ "def", "log_value", "(", "self", ",", "name", ",", "value", ",", "step", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'\"value\" should be a number, got {}'", ".", "format", ...
Log new value for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (float): this is a real number to be logged as a scalar. step (int): non-negative integer used for visualization: you can log several different variables on one step, but should not log different values of the same variable on the same step (this is not checked).
[ "Log", "new", "value", "for", "given", "name", "on", "given", "step", "." ]
93968344a471532530f035622118693845f32649
https://github.com/TeamHG-Memex/tensorboard_logger/blob/93968344a471532530f035622118693845f32649/tensorboard_logger/tensorboard_logger.py#L71-L92
train
198,370
TeamHG-Memex/tensorboard_logger
tensorboard_logger/tensorboard_logger.py
Logger.log_histogram
def log_histogram(self, name, value, step=None): """Log a histogram for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (tuple or list): either list of numbers to be summarized as a histogram, or a tuple of bin_edges and bincounts that directly define a histogram. step (int): non-negative integer used for visualization """ if isinstance(value, six.string_types): raise TypeError('"value" should be a number, got {}' .format(type(value))) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._histogram_summary(tf_name, value, step=step) self._log_summary(tf_name, summary, value, step=step)
python
def log_histogram(self, name, value, step=None): """Log a histogram for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (tuple or list): either list of numbers to be summarized as a histogram, or a tuple of bin_edges and bincounts that directly define a histogram. step (int): non-negative integer used for visualization """ if isinstance(value, six.string_types): raise TypeError('"value" should be a number, got {}' .format(type(value))) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._histogram_summary(tf_name, value, step=step) self._log_summary(tf_name, summary, value, step=step)
[ "def", "log_histogram", "(", "self", ",", "name", ",", "value", ",", "step", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'\"value\" should be a number, got {}'", ".", "format...
Log a histogram for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (tuple or list): either list of numbers to be summarized as a histogram, or a tuple of bin_edges and bincounts that directly define a histogram. step (int): non-negative integer used for visualization
[ "Log", "a", "histogram", "for", "given", "name", "on", "given", "step", "." ]
93968344a471532530f035622118693845f32649
https://github.com/TeamHG-Memex/tensorboard_logger/blob/93968344a471532530f035622118693845f32649/tensorboard_logger/tensorboard_logger.py#L94-L113
train
198,371
TeamHG-Memex/tensorboard_logger
tensorboard_logger/tensorboard_logger.py
Logger.log_images
def log_images(self, name, images, step=None): """Log new images for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). images (list): list of images to visualize step (int): non-negative integer used for visualization """ if isinstance(images, six.string_types): raise TypeError('"images" should be a list of ndarrays, got {}' .format(type(images))) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._image_summary(tf_name, images, step=step) self._log_summary(tf_name, summary, images, step=step)
python
def log_images(self, name, images, step=None): """Log new images for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). images (list): list of images to visualize step (int): non-negative integer used for visualization """ if isinstance(images, six.string_types): raise TypeError('"images" should be a list of ndarrays, got {}' .format(type(images))) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._image_summary(tf_name, images, step=step) self._log_summary(tf_name, summary, images, step=step)
[ "def", "log_images", "(", "self", ",", "name", ",", "images", ",", "step", "=", "None", ")", ":", "if", "isinstance", "(", "images", ",", "six", ".", "string_types", ")", ":", "raise", "TypeError", "(", "'\"images\" should be a list of ndarrays, got {}'", ".",...
Log new images for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). images (list): list of images to visualize step (int): non-negative integer used for visualization
[ "Log", "new", "images", "for", "given", "name", "on", "given", "step", "." ]
93968344a471532530f035622118693845f32649
https://github.com/TeamHG-Memex/tensorboard_logger/blob/93968344a471532530f035622118693845f32649/tensorboard_logger/tensorboard_logger.py#L115-L132
train
198,372
TeamHG-Memex/tensorboard_logger
tensorboard_logger/tensorboard_logger.py
Logger._image_summary
def _image_summary(self, tf_name, images, step=None): """ Log a list of images. References: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/04-utils/tensorboard/logger.py#L22 Example: >>> tf_name = 'foo' >>> value = ([0, 1, 2, 3, 4, 5], [1, 20, 10, 22, 11]) >>> self = Logger(None, is_dummy=True) >>> images = [np.random.rand(10, 10), np.random.rand(10, 10)] >>> summary = self._image_summary(tf_name, images, step=None) >>> assert len(summary.value) == 2 >>> assert summary.value[0].image.width == 10 """ img_summaries = [] for i, img in enumerate(images): # Write the image to a string try: s = StringIO() except: s = BytesIO() scipy.misc.toimage(img).save(s, format="png") # Create an Image object img_sum = summary_pb2.Summary.Image( encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1] ) # Create a Summary value img_value = summary_pb2.Summary.Value(tag='{}/{}'.format(tf_name, i), image=img_sum) img_summaries.append(img_value) summary = summary_pb2.Summary() summary.value.add(tag=tf_name, image=img_sum) summary = summary_pb2.Summary(value=img_summaries) return summary
python
def _image_summary(self, tf_name, images, step=None): """ Log a list of images. References: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/04-utils/tensorboard/logger.py#L22 Example: >>> tf_name = 'foo' >>> value = ([0, 1, 2, 3, 4, 5], [1, 20, 10, 22, 11]) >>> self = Logger(None, is_dummy=True) >>> images = [np.random.rand(10, 10), np.random.rand(10, 10)] >>> summary = self._image_summary(tf_name, images, step=None) >>> assert len(summary.value) == 2 >>> assert summary.value[0].image.width == 10 """ img_summaries = [] for i, img in enumerate(images): # Write the image to a string try: s = StringIO() except: s = BytesIO() scipy.misc.toimage(img).save(s, format="png") # Create an Image object img_sum = summary_pb2.Summary.Image( encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1] ) # Create a Summary value img_value = summary_pb2.Summary.Value(tag='{}/{}'.format(tf_name, i), image=img_sum) img_summaries.append(img_value) summary = summary_pb2.Summary() summary.value.add(tag=tf_name, image=img_sum) summary = summary_pb2.Summary(value=img_summaries) return summary
[ "def", "_image_summary", "(", "self", ",", "tf_name", ",", "images", ",", "step", "=", "None", ")", ":", "img_summaries", "=", "[", "]", "for", "i", ",", "img", "in", "enumerate", "(", "images", ")", ":", "# Write the image to a string", "try", ":", "s",...
Log a list of images. References: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/04-utils/tensorboard/logger.py#L22 Example: >>> tf_name = 'foo' >>> value = ([0, 1, 2, 3, 4, 5], [1, 20, 10, 22, 11]) >>> self = Logger(None, is_dummy=True) >>> images = [np.random.rand(10, 10), np.random.rand(10, 10)] >>> summary = self._image_summary(tf_name, images, step=None) >>> assert len(summary.value) == 2 >>> assert summary.value[0].image.width == 10
[ "Log", "a", "list", "of", "images", "." ]
93968344a471532530f035622118693845f32649
https://github.com/TeamHG-Memex/tensorboard_logger/blob/93968344a471532530f035622118693845f32649/tensorboard_logger/tensorboard_logger.py#L134-L173
train
198,373
olofk/edalize
edalize/edatool.py
jinja_filter_param_value_str
def jinja_filter_param_value_str(value, str_quote_style="", bool_is_str=False): """ Convert a parameter value to string suitable to be passed to an EDA tool Rules: - Booleans are represented as 0/1 or "true"/"false" depending on the bool_is_str argument - Strings are either passed through or enclosed in the characters specified in str_quote_style (e.g. '"' or '\\"') - Everything else (including int, float, etc.) are converted using the str() function. """ if (type(value) == bool) and not bool_is_str: if (value) == True: return '1' else: return '0' elif type(value) == str or ((type(value) == bool) and bool_is_str): return str_quote_style + str(value) + str_quote_style else: return str(value)
python
def jinja_filter_param_value_str(value, str_quote_style="", bool_is_str=False): """ Convert a parameter value to string suitable to be passed to an EDA tool Rules: - Booleans are represented as 0/1 or "true"/"false" depending on the bool_is_str argument - Strings are either passed through or enclosed in the characters specified in str_quote_style (e.g. '"' or '\\"') - Everything else (including int, float, etc.) are converted using the str() function. """ if (type(value) == bool) and not bool_is_str: if (value) == True: return '1' else: return '0' elif type(value) == str or ((type(value) == bool) and bool_is_str): return str_quote_style + str(value) + str_quote_style else: return str(value)
[ "def", "jinja_filter_param_value_str", "(", "value", ",", "str_quote_style", "=", "\"\"", ",", "bool_is_str", "=", "False", ")", ":", "if", "(", "type", "(", "value", ")", "==", "bool", ")", "and", "not", "bool_is_str", ":", "if", "(", "value", ")", "=="...
Convert a parameter value to string suitable to be passed to an EDA tool Rules: - Booleans are represented as 0/1 or "true"/"false" depending on the bool_is_str argument - Strings are either passed through or enclosed in the characters specified in str_quote_style (e.g. '"' or '\\"') - Everything else (including int, float, etc.) are converted using the str() function.
[ "Convert", "a", "parameter", "value", "to", "string", "suitable", "to", "be", "passed", "to", "an", "EDA", "tool" ]
3f087d27323765ba656790d8d0cef8c433c70f2f
https://github.com/olofk/edalize/blob/3f087d27323765ba656790d8d0cef8c433c70f2f/edalize/edatool.py#L12-L31
train
198,374
olofk/edalize
edalize/edatool.py
Edatool.render_template
def render_template(self, template_file, target_file, template_vars = {}): """ Render a Jinja2 template for the backend The template file is expected in the directory templates/BACKEND_NAME. """ template_dir = str(self.__class__.__name__).lower() template = self.jinja_env.get_template(os.path.join(template_dir, template_file)) file_path = os.path.join(self.work_root, target_file) with open(file_path, 'w') as f: f.write(template.render(template_vars))
python
def render_template(self, template_file, target_file, template_vars = {}): """ Render a Jinja2 template for the backend The template file is expected in the directory templates/BACKEND_NAME. """ template_dir = str(self.__class__.__name__).lower() template = self.jinja_env.get_template(os.path.join(template_dir, template_file)) file_path = os.path.join(self.work_root, target_file) with open(file_path, 'w') as f: f.write(template.render(template_vars))
[ "def", "render_template", "(", "self", ",", "template_file", ",", "target_file", ",", "template_vars", "=", "{", "}", ")", ":", "template_dir", "=", "str", "(", "self", ".", "__class__", ".", "__name__", ")", ".", "lower", "(", ")", "template", "=", "sel...
Render a Jinja2 template for the backend The template file is expected in the directory templates/BACKEND_NAME.
[ "Render", "a", "Jinja2", "template", "for", "the", "backend" ]
3f087d27323765ba656790d8d0cef8c433c70f2f
https://github.com/olofk/edalize/blob/3f087d27323765ba656790d8d0cef8c433c70f2f/edalize/edatool.py#L228-L238
train
198,375
python-xlib/python-xlib
Xlib/ext/nvcontrol.py
query_target_count
def query_target_count(self, target): """Return the target count""" reply = NVCtrlQueryTargetCountReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_type=target.type()) return int(reply._data.get('count'))
python
def query_target_count(self, target): """Return the target count""" reply = NVCtrlQueryTargetCountReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_type=target.type()) return int(reply._data.get('count'))
[ "def", "query_target_count", "(", "self", ",", "target", ")", ":", "reply", "=", "NVCtrlQueryTargetCountReplyRequest", "(", "display", "=", "self", ".", "display", ",", "opcode", "=", "self", ".", "display", ".", "get_extension_major", "(", "extname", ")", ","...
Return the target count
[ "Return", "the", "target", "count" ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L30-L35
train
198,376
python-xlib/python-xlib
Xlib/ext/nvcontrol.py
query_int_attribute
def query_int_attribute(self, target, display_mask, attr): """Return the value of an integer attribute""" reply = NVCtrlQueryAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return int(reply._data.get('value'))
python
def query_int_attribute(self, target, display_mask, attr): """Return the value of an integer attribute""" reply = NVCtrlQueryAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return int(reply._data.get('value'))
[ "def", "query_int_attribute", "(", "self", ",", "target", ",", "display_mask", ",", "attr", ")", ":", "reply", "=", "NVCtrlQueryAttributeReplyRequest", "(", "display", "=", "self", ".", "display", ",", "opcode", "=", "self", ".", "display", ".", "get_extension...
Return the value of an integer attribute
[ "Return", "the", "value", "of", "an", "integer", "attribute" ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L38-L48
train
198,377
python-xlib/python-xlib
Xlib/ext/nvcontrol.py
set_int_attribute
def set_int_attribute(self, target, display_mask, attr, value): """Set the value of an integer attribute""" reply = NVCtrlSetAttributeAndGetStatusReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr, value=value) return reply._data.get('flags') != 0
python
def set_int_attribute(self, target, display_mask, attr, value): """Set the value of an integer attribute""" reply = NVCtrlSetAttributeAndGetStatusReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr, value=value) return reply._data.get('flags') != 0
[ "def", "set_int_attribute", "(", "self", ",", "target", ",", "display_mask", ",", "attr", ",", "value", ")", ":", "reply", "=", "NVCtrlSetAttributeAndGetStatusReplyRequest", "(", "display", "=", "self", ".", "display", ",", "opcode", "=", "self", ".", "display...
Set the value of an integer attribute
[ "Set", "the", "value", "of", "an", "integer", "attribute" ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L51-L60
train
198,378
python-xlib/python-xlib
Xlib/ext/nvcontrol.py
query_string_attribute
def query_string_attribute(self, target, display_mask, attr): """Return the value of a string attribute""" reply = NVCtrlQueryStringAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return str(reply._data.get('string')).strip('\0')
python
def query_string_attribute(self, target, display_mask, attr): """Return the value of a string attribute""" reply = NVCtrlQueryStringAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return str(reply._data.get('string')).strip('\0')
[ "def", "query_string_attribute", "(", "self", ",", "target", ",", "display_mask", ",", "attr", ")", ":", "reply", "=", "NVCtrlQueryStringAttributeReplyRequest", "(", "display", "=", "self", ".", "display", ",", "opcode", "=", "self", ".", "display", ".", "get_...
Return the value of a string attribute
[ "Return", "the", "value", "of", "a", "string", "attribute" ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L63-L73
train
198,379
python-xlib/python-xlib
Xlib/ext/nvcontrol.py
query_binary_data
def query_binary_data(self, target, display_mask, attr): """Return binary data""" reply = NVCtrlQueryBinaryDataReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return reply._data.get('data')
python
def query_binary_data(self, target, display_mask, attr): """Return binary data""" reply = NVCtrlQueryBinaryDataReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return reply._data.get('data')
[ "def", "query_binary_data", "(", "self", ",", "target", ",", "display_mask", ",", "attr", ")", ":", "reply", "=", "NVCtrlQueryBinaryDataReplyRequest", "(", "display", "=", "self", ".", "display", ",", "opcode", "=", "self", ".", "display", ".", "get_extension_...
Return binary data
[ "Return", "binary", "data" ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L89-L99
train
198,380
python-xlib/python-xlib
Xlib/ext/nvcontrol.py
_displaystr2num
def _displaystr2num(st): """Return a display number from a string""" num = None for s, n in [('DFP-', 16), ('TV-', 8), ('CRT-', 0)]: if st.startswith(s): try: curnum = int(st[len(s):]) if 0 <= curnum <= 7: num = n + curnum break except Exception: pass if num is not None: return num else: raise ValueError('Unrecognised display name: ' + st)
python
def _displaystr2num(st): """Return a display number from a string""" num = None for s, n in [('DFP-', 16), ('TV-', 8), ('CRT-', 0)]: if st.startswith(s): try: curnum = int(st[len(s):]) if 0 <= curnum <= 7: num = n + curnum break except Exception: pass if num is not None: return num else: raise ValueError('Unrecognised display name: ' + st)
[ "def", "_displaystr2num", "(", "st", ")", ":", "num", "=", "None", "for", "s", ",", "n", "in", "[", "(", "'DFP-'", ",", "16", ")", ",", "(", "'TV-'", ",", "8", ")", ",", "(", "'CRT-'", ",", "0", ")", "]", ":", "if", "st", ".", "startswith", ...
Return a display number from a string
[ "Return", "a", "display", "number", "from", "a", "string" ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/ext/nvcontrol.py#L312-L327
train
198,381
python-xlib/python-xlib
Xlib/display.py
Display.keycode_to_keysym
def keycode_to_keysym(self, keycode, index): """Convert a keycode to a keysym, looking in entry index. Normally index 0 is unshifted, 1 is shifted, 2 is alt grid, and 3 is shift+alt grid. If that key entry is not bound, X.NoSymbol is returned.""" try: return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol
python
def keycode_to_keysym(self, keycode, index): """Convert a keycode to a keysym, looking in entry index. Normally index 0 is unshifted, 1 is shifted, 2 is alt grid, and 3 is shift+alt grid. If that key entry is not bound, X.NoSymbol is returned.""" try: return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol
[ "def", "keycode_to_keysym", "(", "self", ",", "keycode", ",", "index", ")", ":", "try", ":", "return", "self", ".", "_keymap_codes", "[", "keycode", "]", "[", "index", "]", "except", "IndexError", ":", "return", "X", ".", "NoSymbol" ]
Convert a keycode to a keysym, looking in entry index. Normally index 0 is unshifted, 1 is shifted, 2 is alt grid, and 3 is shift+alt grid. If that key entry is not bound, X.NoSymbol is returned.
[ "Convert", "a", "keycode", "to", "a", "keysym", "looking", "in", "entry", "index", ".", "Normally", "index", "0", "is", "unshifted", "1", "is", "shifted", "2", "is", "alt", "grid", "and", "3", "is", "shift", "+", "alt", "grid", ".", "If", "that", "ke...
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L366-L374
train
198,382
python-xlib/python-xlib
Xlib/display.py
Display.refresh_keyboard_mapping
def refresh_keyboard_mapping(self, evt): """This method should be called once when a MappingNotify event is received, to update the keymap cache. evt should be the event object.""" if isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a MappingNotify event')
python
def refresh_keyboard_mapping(self, evt): """This method should be called once when a MappingNotify event is received, to update the keymap cache. evt should be the event object.""" if isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a MappingNotify event')
[ "def", "refresh_keyboard_mapping", "(", "self", ",", "evt", ")", ":", "if", "isinstance", "(", "evt", ",", "event", ".", "MappingNotify", ")", ":", "if", "evt", ".", "request", "==", "X", ".", "MappingKeyboard", ":", "self", ".", "_update_keymap", "(", "...
This method should be called once when a MappingNotify event is received, to update the keymap cache. evt should be the event object.
[ "This", "method", "should", "be", "called", "once", "when", "a", "MappingNotify", "event", "is", "received", "to", "update", "the", "keymap", "cache", ".", "evt", "should", "be", "the", "event", "object", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L396-L404
train
198,383
python-xlib/python-xlib
Xlib/display.py
Display._update_keymap
def _update_keymap(self, first_keycode, count): """Internal function, called to refresh the keymap cache. """ # Delete all sym->code maps for the changed codes lastcode = first_keycode + count for keysym, codes in self._keymap_syms.items(): i = 0 while i < len(codes): code = codes[i][1] if code >= first_keycode and code < lastcode: del codes[i] else: i = i + 1 # Get the new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map with the new map self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code map code = first_keycode for syms in keysyms: index = 0 for sym in syms: if sym != X.NoSymbol: if sym in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] = [(index, code)] index = index + 1 code = code + 1
python
def _update_keymap(self, first_keycode, count): """Internal function, called to refresh the keymap cache. """ # Delete all sym->code maps for the changed codes lastcode = first_keycode + count for keysym, codes in self._keymap_syms.items(): i = 0 while i < len(codes): code = codes[i][1] if code >= first_keycode and code < lastcode: del codes[i] else: i = i + 1 # Get the new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map with the new map self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code map code = first_keycode for syms in keysyms: index = 0 for sym in syms: if sym != X.NoSymbol: if sym in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] = [(index, code)] index = index + 1 code = code + 1
[ "def", "_update_keymap", "(", "self", ",", "first_keycode", ",", "count", ")", ":", "# Delete all sym->code maps for the changed codes", "lastcode", "=", "first_keycode", "+", "count", "for", "keysym", ",", "codes", "in", "self", ".", "_keymap_syms", ".", "items", ...
Internal function, called to refresh the keymap cache.
[ "Internal", "function", "called", "to", "refresh", "the", "keymap", "cache", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L406-L442
train
198,384
python-xlib/python-xlib
Xlib/display.py
Display.lookup_string
def lookup_string(self, keysym): """Return a string corresponding to KEYSYM, or None if no reasonable translation is found. """ s = self.keysym_translations.get(keysym) if s is not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym)
python
def lookup_string(self, keysym): """Return a string corresponding to KEYSYM, or None if no reasonable translation is found. """ s = self.keysym_translations.get(keysym) if s is not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym)
[ "def", "lookup_string", "(", "self", ",", "keysym", ")", ":", "s", "=", "self", ".", "keysym_translations", ".", "get", "(", "keysym", ")", "if", "s", "is", "not", "None", ":", "return", "s", "import", "Xlib", ".", "XK", "return", "Xlib", ".", "XK", ...
Return a string corresponding to KEYSYM, or None if no reasonable translation is found.
[ "Return", "a", "string", "corresponding", "to", "KEYSYM", "or", "None", "if", "no", "reasonable", "translation", "is", "found", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L448-L457
train
198,385
python-xlib/python-xlib
Xlib/display.py
Display.rebind_string
def rebind_string(self, keysym, newstring): """Change the translation of KEYSYM to NEWSTRING. If NEWSTRING is None, remove old translation if any. """ if newstring is None: try: del self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym] = newstring
python
def rebind_string(self, keysym, newstring): """Change the translation of KEYSYM to NEWSTRING. If NEWSTRING is None, remove old translation if any. """ if newstring is None: try: del self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym] = newstring
[ "def", "rebind_string", "(", "self", ",", "keysym", ",", "newstring", ")", ":", "if", "newstring", "is", "None", ":", "try", ":", "del", "self", ".", "keysym_translations", "[", "keysym", "]", "except", "KeyError", ":", "pass", "else", ":", "self", ".", ...
Change the translation of KEYSYM to NEWSTRING. If NEWSTRING is None, remove old translation if any.
[ "Change", "the", "translation", "of", "KEYSYM", "to", "NEWSTRING", ".", "If", "NEWSTRING", "is", "None", "remove", "old", "translation", "if", "any", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L459-L469
train
198,386
python-xlib/python-xlib
Xlib/display.py
Display.intern_atom
def intern_atom(self, name, only_if_exists = 0): """Intern the string name, returning its atom number. If only_if_exists is true and the atom does not already exist, it will not be created and X.NONE is returned.""" r = request.InternAtom(display = self.display, name = name, only_if_exists = only_if_exists) return r.atom
python
def intern_atom(self, name, only_if_exists = 0): """Intern the string name, returning its atom number. If only_if_exists is true and the atom does not already exist, it will not be created and X.NONE is returned.""" r = request.InternAtom(display = self.display, name = name, only_if_exists = only_if_exists) return r.atom
[ "def", "intern_atom", "(", "self", ",", "name", ",", "only_if_exists", "=", "0", ")", ":", "r", "=", "request", ".", "InternAtom", "(", "display", "=", "self", ".", "display", ",", "name", "=", "name", ",", "only_if_exists", "=", "only_if_exists", ")", ...
Intern the string name, returning its atom number. If only_if_exists is true and the atom does not already exist, it will not be created and X.NONE is returned.
[ "Intern", "the", "string", "name", "returning", "its", "atom", "number", ".", "If", "only_if_exists", "is", "true", "and", "the", "atom", "does", "not", "already", "exist", "it", "will", "not", "be", "created", "and", "X", ".", "NONE", "is", "returned", ...
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L476-L483
train
198,387
python-xlib/python-xlib
Xlib/display.py
Display.get_atom_name
def get_atom_name(self, atom): """Look up the name of atom, returning it as a string. Will raise BadAtom if atom does not exist.""" r = request.GetAtomName(display = self.display, atom = atom) return r.name
python
def get_atom_name(self, atom): """Look up the name of atom, returning it as a string. Will raise BadAtom if atom does not exist.""" r = request.GetAtomName(display = self.display, atom = atom) return r.name
[ "def", "get_atom_name", "(", "self", ",", "atom", ")", ":", "r", "=", "request", ".", "GetAtomName", "(", "display", "=", "self", ".", "display", ",", "atom", "=", "atom", ")", "return", "r", ".", "name" ]
Look up the name of atom, returning it as a string. Will raise BadAtom if atom does not exist.
[ "Look", "up", "the", "name", "of", "atom", "returning", "it", "as", "a", "string", ".", "Will", "raise", "BadAtom", "if", "atom", "does", "not", "exist", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L490-L495
train
198,388
python-xlib/python-xlib
Xlib/display.py
Display.allow_events
def allow_events(self, mode, time, onerror = None): """Release some queued events. mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a timestamp or X.CurrentTime.""" request.AllowEvents(display = self.display, onerror = onerror, mode = mode, time = time)
python
def allow_events(self, mode, time, onerror = None): """Release some queued events. mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a timestamp or X.CurrentTime.""" request.AllowEvents(display = self.display, onerror = onerror, mode = mode, time = time)
[ "def", "allow_events", "(", "self", ",", "mode", ",", "time", ",", "onerror", "=", "None", ")", ":", "request", ".", "AllowEvents", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ",", "mode", "=", "mode", ",", "time", "=...
Release some queued events. mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a timestamp or X.CurrentTime.
[ "Release", "some", "queued", "events", ".", "mode", "should", "be", "one", "of", "X", ".", "AsyncPointer", "X", ".", "SyncPointer", "X", ".", "AsyncKeyboard", "X", ".", "SyncKeyboard", "X", ".", "ReplayPointer", "X", ".", "ReplayKeyboard", "X", ".", "Async...
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L542-L550
train
198,389
python-xlib/python-xlib
Xlib/display.py
Display.grab_server
def grab_server(self, onerror = None): """Disable processing of requests on all other client connections until the server is ungrabbed. Server grabbing should be avoided as much as possible.""" request.GrabServer(display = self.display, onerror = onerror)
python
def grab_server(self, onerror = None): """Disable processing of requests on all other client connections until the server is ungrabbed. Server grabbing should be avoided as much as possible.""" request.GrabServer(display = self.display, onerror = onerror)
[ "def", "grab_server", "(", "self", ",", "onerror", "=", "None", ")", ":", "request", ".", "GrabServer", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ")" ]
Disable processing of requests on all other client connections until the server is ungrabbed. Server grabbing should be avoided as much as possible.
[ "Disable", "processing", "of", "requests", "on", "all", "other", "client", "connections", "until", "the", "server", "is", "ungrabbed", ".", "Server", "grabbing", "should", "be", "avoided", "as", "much", "as", "possible", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L552-L557
train
198,390
python-xlib/python-xlib
Xlib/display.py
Display.ungrab_server
def ungrab_server(self, onerror = None): """Release the server if it was previously grabbed by this client.""" request.UngrabServer(display = self.display, onerror = onerror)
python
def ungrab_server(self, onerror = None): """Release the server if it was previously grabbed by this client.""" request.UngrabServer(display = self.display, onerror = onerror)
[ "def", "ungrab_server", "(", "self", ",", "onerror", "=", "None", ")", ":", "request", ".", "UngrabServer", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ")" ]
Release the server if it was previously grabbed by this client.
[ "Release", "the", "server", "if", "it", "was", "previously", "grabbed", "by", "this", "client", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L559-L562
train
198,391
python-xlib/python-xlib
Xlib/display.py
Display.query_keymap
def query_keymap(self): """Return a bit vector for the logical state of the keyboard, where each bit set to 1 indicates that the corresponding key is currently pressed down. The vector is represented as a list of 32 integers. List item N contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N.""" r = request.QueryKeymap(display = self.display) return r.map
python
def query_keymap(self): """Return a bit vector for the logical state of the keyboard, where each bit set to 1 indicates that the corresponding key is currently pressed down. The vector is represented as a list of 32 integers. List item N contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N.""" r = request.QueryKeymap(display = self.display) return r.map
[ "def", "query_keymap", "(", "self", ")", ":", "r", "=", "request", ".", "QueryKeymap", "(", "display", "=", "self", ".", "display", ")", "return", "r", ".", "map" ]
Return a bit vector for the logical state of the keyboard, where each bit set to 1 indicates that the corresponding key is currently pressed down. The vector is represented as a list of 32 integers. List item N contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N.
[ "Return", "a", "bit", "vector", "for", "the", "logical", "state", "of", "the", "keyboard", "where", "each", "bit", "set", "to", "1", "indicates", "that", "the", "corresponding", "key", "is", "currently", "pressed", "down", ".", "The", "vector", "is", "repr...
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L609-L616
train
198,392
python-xlib/python-xlib
Xlib/display.py
Display.open_font
def open_font(self, name): """Open the font identifed by the pattern name and return its font object. If name does not match any font, None is returned.""" fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror = ec, fid = fid, name = name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None else: cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner = 1)
python
def open_font(self, name): """Open the font identifed by the pattern name and return its font object. If name does not match any font, None is returned.""" fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror = ec, fid = fid, name = name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None else: cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner = 1)
[ "def", "open_font", "(", "self", ",", "name", ")", ":", "fid", "=", "self", ".", "display", ".", "allocate_resource_id", "(", ")", "ec", "=", "error", ".", "CatchError", "(", "error", ".", "BadName", ")", "request", ".", "OpenFont", "(", "display", "="...
Open the font identifed by the pattern name and return its font object. If name does not match any font, None is returned.
[ "Open", "the", "font", "identifed", "by", "the", "pattern", "name", "and", "return", "its", "font", "object", ".", "If", "name", "does", "not", "match", "any", "font", "None", "is", "returned", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L618-L635
train
198,393
python-xlib/python-xlib
Xlib/display.py
Display.list_fonts
def list_fonts(self, pattern, max_names): """Return a list of font names matching pattern. No more than max_names will be returned.""" r = request.ListFonts(display = self.display, max_names = max_names, pattern = pattern) return r.fonts
python
def list_fonts(self, pattern, max_names): """Return a list of font names matching pattern. No more than max_names will be returned.""" r = request.ListFonts(display = self.display, max_names = max_names, pattern = pattern) return r.fonts
[ "def", "list_fonts", "(", "self", ",", "pattern", ",", "max_names", ")", ":", "r", "=", "request", ".", "ListFonts", "(", "display", "=", "self", ".", "display", ",", "max_names", "=", "max_names", ",", "pattern", "=", "pattern", ")", "return", "r", "....
Return a list of font names matching pattern. No more than max_names will be returned.
[ "Return", "a", "list", "of", "font", "names", "matching", "pattern", ".", "No", "more", "than", "max_names", "will", "be", "returned", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L637-L643
train
198,394
python-xlib/python-xlib
Xlib/display.py
Display.set_font_path
def set_font_path(self, path, onerror = None): """Set the font path to path, which should be a list of strings. If path is empty, the default font path of the server will be restored.""" request.SetFontPath(display = self.display, onerror = onerror, path = path)
python
def set_font_path(self, path, onerror = None): """Set the font path to path, which should be a list of strings. If path is empty, the default font path of the server will be restored.""" request.SetFontPath(display = self.display, onerror = onerror, path = path)
[ "def", "set_font_path", "(", "self", ",", "path", ",", "onerror", "=", "None", ")", ":", "request", ".", "SetFontPath", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ",", "path", "=", "path", ")" ]
Set the font path to path, which should be a list of strings. If path is empty, the default font path of the server will be restored.
[ "Set", "the", "font", "path", "to", "path", "which", "should", "be", "a", "list", "of", "strings", ".", "If", "path", "is", "empty", "the", "default", "font", "path", "of", "the", "server", "will", "be", "restored", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L678-L684
train
198,395
python-xlib/python-xlib
Xlib/display.py
Display.get_font_path
def get_font_path(self): """Return the current font path as a list of strings.""" r = request.GetFontPath(display = self.display) return r.paths
python
def get_font_path(self): """Return the current font path as a list of strings.""" r = request.GetFontPath(display = self.display) return r.paths
[ "def", "get_font_path", "(", "self", ")", ":", "r", "=", "request", ".", "GetFontPath", "(", "display", "=", "self", ".", "display", ")", "return", "r", ".", "paths" ]
Return the current font path as a list of strings.
[ "Return", "the", "current", "font", "path", "as", "a", "list", "of", "strings", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L686-L689
train
198,396
python-xlib/python-xlib
Xlib/display.py
Display.list_extensions
def list_extensions(self): """Return a list of all the extensions provided by the server.""" r = request.ListExtensions(display = self.display) return r.names
python
def list_extensions(self): """Return a list of all the extensions provided by the server.""" r = request.ListExtensions(display = self.display) return r.names
[ "def", "list_extensions", "(", "self", ")", ":", "r", "=", "request", ".", "ListExtensions", "(", "display", "=", "self", ".", "display", ")", "return", "r", ".", "names" ]
Return a list of all the extensions provided by the server.
[ "Return", "a", "list", "of", "all", "the", "extensions", "provided", "by", "the", "server", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L710-L713
train
198,397
python-xlib/python-xlib
Xlib/display.py
Display.get_keyboard_mapping
def get_keyboard_mapping(self, first_keycode, count): """Return the current keyboard mapping as a list of tuples, starting at first_keycount and no more than count.""" r = request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode, count = count) return r.keysyms
python
def get_keyboard_mapping(self, first_keycode, count): """Return the current keyboard mapping as a list of tuples, starting at first_keycount and no more than count.""" r = request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode, count = count) return r.keysyms
[ "def", "get_keyboard_mapping", "(", "self", ",", "first_keycode", ",", "count", ")", ":", "r", "=", "request", ".", "GetKeyboardMapping", "(", "display", "=", "self", ".", "display", ",", "first_keycode", "=", "first_keycode", ",", "count", "=", "count", ")"...
Return the current keyboard mapping as a list of tuples, starting at first_keycount and no more than count.
[ "Return", "the", "current", "keyboard", "mapping", "as", "a", "list", "of", "tuples", "starting", "at", "first_keycount", "and", "no", "more", "than", "count", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L724-L730
train
198,398
python-xlib/python-xlib
Xlib/display.py
Display.change_hosts
def change_hosts(self, mode, host_family, host, onerror = None): """mode is either X.HostInsert or X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a list of bytes. For the Internet family, it should be the four bytes of an IPv4 address.""" request.ChangeHosts(display = self.display, onerror = onerror, mode = mode, host_family = host_family, host = host)
python
def change_hosts(self, mode, host_family, host, onerror = None): """mode is either X.HostInsert or X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a list of bytes. For the Internet family, it should be the four bytes of an IPv4 address.""" request.ChangeHosts(display = self.display, onerror = onerror, mode = mode, host_family = host_family, host = host)
[ "def", "change_hosts", "(", "self", ",", "mode", ",", "host_family", ",", "host", ",", "onerror", "=", "None", ")", ":", "request", ".", "ChangeHosts", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ",", "mode", "=", "mode...
mode is either X.HostInsert or X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a list of bytes. For the Internet family, it should be the four bytes of an IPv4 address.
[ "mode", "is", "either", "X", ".", "HostInsert", "or", "X", ".", "HostDelete", ".", "host_family", "is", "one", "of", "X", ".", "FamilyInternet", "X", ".", "FamilyDECnet", "or", "X", ".", "FamilyChaos", "." ]
8901e831737e79fe5645f48089d70e1d1046d2f2
https://github.com/python-xlib/python-xlib/blob/8901e831737e79fe5645f48089d70e1d1046d2f2/Xlib/display.py#L850-L860
train
198,399