text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _as_json_dumps(self, indent: str=' ', **kwargs) -> str: """ Convert to a stringified json object. This is the same as _as_json with the exception that it isn'...
return json.dumps(self, default=self._default, indent=indent, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]: """ Return a json array as a list :param value: array :return: array with JsonObj instances removed "...
return [e._as_dict if isinstance(e, JsonObj) else e for e in value]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _as_dict(self) -> Dict[str, JsonTypes]: """ Convert a JsonObj into a straight dictionary :return: dictionary that cooresponds to the json object """
return {k: v._as_dict if isinstance(v, JsonObj) else self.__as_list(v) if isinstance(v, list) else v for k, v in self.__dict__.items()}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def max_entries(self): """ Removes the maximum entry limit """
self._debug_log.info('Removing maximum entries restriction') self._log_entries(deque(self._log_entries))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def main(dimension, iterations): """ Main function to execute gbest GC PSO algorithm. """
objective_function = minimize(functions.sphere) stopping_condition = max_iterations(iterations) (solution, metrics) = optimize(objective_function=objective_function, domain=Domain(-5.12, 5.12, dimension), stopping_condition=stopping_cond...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def read_chunks(self): """Read chunks from the HTTP client"""
if self.reading_chunks and self.got_chunk: # we got on the fast-path and directly read from the buffer. # if we continue to recurse, this is going to blow up the stack. # so instead return # # NOTE: This actually is unnecessary as long as tornado gua...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _chunk_length(self, data): """Received the chunk length"""
assert data[-2:] == "\r\n", "CRLF" length = data[:-2].split(';')[0] # cut off optional length paramters length = int(length.strip(), 16) # length is in hex if length: logger.debug('Got chunk length: %d', length) self.httpstream.read_bytes(length + 2, self._chu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _chunk_data(self, data): """Received chunk data"""
assert data[-2:] == "\r\n", "CRLF" if self.gzip_decompressor: if not self.gzip_header_seen: assert data[:2] == '\x1f\x8b', "gzip header" self.gzip_header_seen = True self.process_input_buffer += self.gzip_decompressor.decompress(data[:-2]) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_stdin_event(self, fd, events): """Eventhandler for stdin"""
assert fd == self.fd_stdin if events & self.ioloop.ERROR: # An error at the end is expected since tornado maps HUP to ERROR logger.debug('Error on stdin') # ensure pipe is closed if not self.process.stdin.closed: self.process.stdin.close...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_stdout_event(self, fd, events): """Eventhandler for stdout"""
assert fd == self.fd_stdout if events & self.ioloop.READ: # got data ready to read data = '' # Now basically we have two cases: either the client supports # HTTP/1.1 in which case we can stream the answer in chunked mode # in HTTP/1.0 we ne...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _handle_stderr_event(self, fd, events): """Eventhandler for stderr"""
assert fd == self.fd_stderr if events & self.ioloop.READ: # got data ready if not self.headers_sent: payload = self.process.stderr.read() data = 'HTTP/1.1 500 Internal Server Error\r\nDate: %s\r\nContent-Length: %d\r\n\r\n' % (get_date_header()...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _graceful_finish(self): """Detect if process has closed pipes and we can finish"""
if not self.process.stdout.closed or not self.process.stderr.closed: return # stdout/stderr still open if not self.process.stdin.closed: self.process.stdin.close() if self.number_of_8k_chunks_sent > 0: logger.debug('Sent %d * 8k chunks', self.number_of_8k_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _genTimeoutList(self, const): """ Generates a dict of the valid timeout values for the given `const`. The `const` value may change for different versions or ...
result = {} for v in range(128): x = v & 0x0F y = (v >> 4) & 0x07 if not y or (y and x > 7): result[const * x * 2**y] = v self._log and self._log.debug("Timeout list: %s", result) return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def findConnectedDevices(self): """ Find all the devices on the serial buss and store the results in a class member object. """
tmpTimeout = self._serial.timeout self._serial.timeout = 0.01 for dev in range(128): device = self._getDeviceID(dev) if device is not None and int(device) not in self._deviceConfig: config = self._deviceConfig.setdefault(int(device), {}) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setCompactProtocol(self): """ Set the compact protocol. """
self._compact = True self._serial.write(bytes(self._BAUD_DETECT)) self._log and self._log.debug("Compact protocol has been set.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setPololuProtocol(self): """ Set the pololu protocol. """
self._compact = False self._log and self._log.debug("Pololu protocol has been set.")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _writeData(self, command, device, params=()): """ Write the data to the device. :Parameters: command : `int` The command to write to the device. device : `in...
sequence = [] if self._compact: sequence.append(command | 0x80) else: sequence.append(self._BAUD_DETECT) sequence.append(device) sequence.append(command) for param in params: sequence.append(param) if self._crc: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getFirmwareVersion(self, device): """ Get the firmware version. :Parameters: device : `int` The device is the integer number of the hardware devices ID and ...
cmd = self._COMMAND.get('get-fw-version') self._writeData(cmd, device) try: result = self._serial.read(size=1) result = int(result) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=True) raise e ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getError(self, device, message): """ Get the error message or value stored in the Qik hardware. :Parameters: device : `int` The device is the integer number...
cmd = self._COMMAND.get('get-error') self._writeData(cmd, device) result = [] bits = [] try: num = self._serial.read(size=1) num = ord(num) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=Tru...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getConfig(self, num, device): """ Low level method used for all get config commands. :Parameters: num : `int` Number that indicates the config option to get...
cmd = self._COMMAND.get('get-config') self._writeData(cmd, device, params=(num,)) try: result = self._serial.read(size=1) result = ord(result) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_info=True) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getPWMFrequency(self, device, message): """ Get the PWM frequency stored on the hardware device. :Parameters: device : `int` The device is the integer numbe...
result = self._getConfig(self.PWM_PARAM, device) freq, msg = self._CONFIG_PWM.get(result, (result, 'Invalid Frequency')) if message: result = msg else: result = freq return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _getSerialTimeout(self, device): """ Get the serial timeout stored on the hardware device. Caution, more that one value returned from the Qik can have the sa...
num = self._getConfig(self.SERIAL_TIMEOUT, device) if isinstance(num, int): x = num & 0x0F y = (num >> 4) & 0x07 result = self.DEFAULT_SERIAL_TIMEOUT * x * pow(2, y) else: result = num return result
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setConfig(self, num, value, device, message): """ Low level method used for all set config commands. :Parameters: num : `int` Number that indicates the conf...
cmd = self._COMMAND.get('set-config') self._writeData(cmd, device, params=(num, value, 0x55, 0x2A)) try: result = self._serial.read(size=1) result = ord(result) except serial.SerialException as e: self._log and self._log.error("Error: %s", e, exc_inf...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setSpeed(self, speed, motor, device): """ Set motor speed. This method takes into consideration the PWM frequency that the hardware is currently running at ...
reverse = False if speed < 0: speed = -speed reverse = True # 0 and 2 for Qik 2s9v1, 0, 2, and 4 for 2s12v10 if self._deviceConfig[device]['pwm'] in (0, 2, 4,) and speed > 127: speed = 127 if speed > 127: if speed > 255: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_key_names(self): """ Gets keys of all elements stored in this map. :return: a list with all map keys. """
names = [] for (k, _) in self.items(): names.append(k) return names
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def append(self, map): """ Appends new elements to this map. :param map: a map with elements to be added. """
if isinstance(map, dict): for (k, v) in map.items(): key = StringConverter.to_string(k) value = v self.put(key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_as_object(self, value): """ Sets a new value to map element :param value: a new element or map value. """
self.clear() map = MapConverter.to_map(value) self.append(map)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_string(self, key): """ Converts map element into a string or returns None if conversion is not possible. :param key: an index of element to g...
value = self.get(key) return StringConverter.to_nullable_string(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_string(self, key): """ Converts map element into a string or returns "" if conversion is not possible. :param key: an index of element to get. :return...
value = self.get(key) return StringConverter.to_string(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_string_with_default(self, key, default_value): """ Converts map element into a string or returns default value if conversion is not possible. :param k...
value = self.get(key) return StringConverter.to_string_with_default(value, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_boolean(self, key): """ Converts map element into a boolean or returns None if conversion is not possible :param key: an index of element to ...
value = self.get(key) return BooleanConverter.to_nullable_boolean(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_boolean(self, key): """ Converts map element into a boolean or returns false if conversion is not possible. :param key: an index of element to get. :r...
value = self.get(key) return BooleanConverter.to_boolean(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_boolean_with_default(self, key, default_value): """ Converts map element into a boolean or returns default value if conversion is not possible. :param...
value = self.get(key) return BooleanConverter.to_boolean_with_default(value, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_integer(self, key): """ Converts map element into an integer or returns None if conversion is not possible. :param key: an index of element t...
value = self.get(key) return IntegerConverter.to_nullable_integer(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_integer(self, key): """ Converts map element into an integer or returns 0 if conversion is not possible. :param key: an index of element to get. :retu...
value = self.get(key) return IntegerConverter.to_integer(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_integer_with_default(self, key, default_value): """ Converts map element into an integer or returns default value if conversion is not possible. :para...
value = self.get(key) return IntegerConverter.to_integer_with_default(value, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_float(self, key): """ Converts map element into a float or returns None if conversion is not possible. :param key: an index of element to get...
value = self.get(key) return FloatConverter.to_nullable_float(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_float(self, key): """ Converts map element into a float or returns 0 if conversion is not possible. :param key: an index of element to get. :return: f...
value = self.get(key) return FloatConverter.to_float(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_float_with_default(self, key, default_value): """ Converts map element into a float or returns default value if conversion is not possible. :param key...
value = self.get(key) return FloatConverter.to_float_with_default(value, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_datetime(self, key): """ Converts map element into a Date or returns None if conversion is not possible. :param key: an index of element to g...
value = self.get(key) return DateTimeConverter.to_nullable_datetime(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_datetime(self, key): """ Converts map element into a Date or returns the current date if conversion is not possible. :param key: an index of element t...
value = self.get(key) return DateTimeConverter.to_datetime(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_datetime_with_default(self, key, default_value): """ Converts map element into a Date or returns default value if conversion is not possible. :param k...
value = self.get(key) return DateTimeConverter.to_datetime_with_default(value, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns None...
value = self.get(key) return TypeConverter.to_nullable_type(value_type, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_type(self, key, value_type): """ Converts map element into a value defined by specied typecode. If conversion is not possible it returns default value...
value = self.get(key) return TypeConverter.to_type(value_type, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_type_with_default(self, key, value_type, default_value): """ Converts map element into a value defined by specied typecode. If conversion is not possi...
value = self.get(key) return TypeConverter.to_type_with_default(value_type, value, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_nullable_map(self, key): """ Converts map element into an AnyValueMap or returns None if conversion is not possible. :param key: a key of element to g...
value = self.get_as_object(key) return AnyValueMap.from_value(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_as_map_with_default(self, key, default_value): """ Converts map element into an AnyValueMap or returns default value if conversion is not possible. :para...
value = self.get_as_nullable_map(key) return MapConverter.to_map_with_default(value, default_value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open(url): """ Launches browser depending on os """
if sys.platform == 'win32': os.startfile(url) elif sys.platform == 'darwin': subprocess.Popen(['open', url]) else: try: subprocess.Popen(['xdg-open', url]) except OSError: import webbrowser webbrowser.open(url)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def print_arguments(): """ Decorator that provides the wrapped function with an attribute 'print_arguments' containing just those keyword arguments actually pass...
def decorator(function): def inner(*args, **kwargs): if args: print "Passed arguments:" for i in args: pp.pprint(i) print "Passed keyword arguments:" pp.pprint(kwargs) return function(*args, **kwargs) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_subservice(self, obj): """Add a sub-service object. :param obj: stackinabox.services.StackInABoxService instance :raises: RouteAlreadyRegisteredError if ...
# ensure there is not already a sub-service if self.obj is not None: raise RouteAlreadyRegisteredError( 'Service Router ({0} - {1}): Route {2} already has a ' 'sub-service handler' .format(id(self), self.service_name, self.uri)) # war...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_uris(self, new_uri): """Update all URIS. :param new_uri: URI to switch to and update the matching :returns: n/a Note: This overwrites any existing URI...
self.uri = new_uri # if there is a sub-service, update it too if self.obj: self.obj.base_url = '{0}/{1}'.format(self.uri, self.service_name)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_method(self, method, fn): """Register an HTTP method and handler function. :param method: string, HTTP verb :param fn: python function handling the ...
# ensure the HTTP verb is not already registered if method not in self.methods.keys(): logger.debug('Service Router ({0} - {1}): Adding method {2} on ' 'route {3}' .format(id(self), self.service_name, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def validate_regex(regex, sub_service): """Is the regex valid for StackInABox routing? :param regex: Python regex object to match the URI :param sub_service: boo...
# The regex generated by stackinabox starts with ^ # and ends with $. Enforce that the provided regex does the same. if regex.pattern.startswith('^') is False: logger.debug('StackInABoxService: Pattern must start with ^') raise InvalidRouteRegexError('Pattern must start...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_service_regex(base_url, service_url, sub_service): """Get the regex for a given service. :param base_url: string - Base URI :param service_url: string - ...
# if the specified service_url is already a regex # then just use. Otherwise create what we need if StackInABoxService.is_regex(service_url): logger.debug('StackInABoxService: Received regex {0} for use...' .format(service_url.pattern)) # Valida...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def base_url(self, value): """Set the Base URI value. :param value: the new URI to use for the Base URI """
logger.debug('StackInABoxService ({0}:{1}) Updating Base URL ' 'from {2} to {3}' .format(self.__id, self.name, self.__base_url, value)) self.__base_url = value for k,...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset the service to its' initial state."""
logger.debug('StackInABoxService ({0}): Reset' .format(self.__id, self.name)) self.base_url = '/{0}'.format(self.name) logger.debug('StackInABoxService ({0}): Hosting Service {1}' .format(self.__id, self.name))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def try_handle_route(self, route_uri, method, request, uri, headers): """Try to handle the supplied request on the specified routing URI. :param route_uri: strin...
uri_path = route_uri if '?' in uri: logger.debug('StackInABoxService ({0}:{1}): Found query string ' 'removing for match operation.' .format(self.__id, self.name)) uri_path, uri_qs = uri.split('?') logger.debug('Stack...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sub_request(self, method, request, uri, headers): """Handle the supplied sub-service request on the specified routing URI. :param method: string - HTTP Verb ...
logger.debug('StackInABoxService ({0}:{1}): Sub-Request Received ' '{2} - {3}' .format(self.__id, self.name, method, uri)) return self.request(method, request, uri, headers)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_route(self, uri, sub_service): """Create the route for the URI. :param uri: string - URI to be routed :param sub_service: boolean - is the URI for a s...
if uri not in self.routes.keys(): logger.debug('Service ({0}): Creating routes' .format(self.name)) self.routes[uri] = { 'regex': StackInABoxService.get_service_regex(self.base_url, ur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(self, method, uri, call_back): """Register a class instance function to handle a request. :param method: string - HTTP Verb :param uri: string - URI...
found = False self.create_route(uri, False) self.routes[uri]['handlers'].register_method(method, call_back)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register_subservice(self, uri, service): """Register a class instance to handle a URI. :param uri: string - URI for the request :param service: StackInABoxSe...
found = False self.create_route(uri, True) self.routes[uri]['handlers'].set_subservice(service)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def pullup(self, pin, enabled): """Turn on the pull-up resistor for the specified pin if enabled is True, otherwise turn off the pull-up resistor. """
self._validate_channel(pin) if enabled: self.gppu[int(pin/8)] |= 1 << (int(pin%8)) else: self.gppu[int(pin/8)] &= ~(1 << (int(pin%8))) self._write_gppu()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_gpio(self, gpio=None): """Write the specified byte value to the GPIO registor. If no value specified the current buffered value will be written. """
if gpio is not None: self.gpio = gpio self.i2c.write_list(self.GPIO, self.gpio)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_iodir(self, iodir=None): """Write the specified byte value to the IODIR registor. If no value specified the current buffered value will be written. ""...
if iodir is not None: self.iodir = iodir self.i2c.write_list(self.IODIR, self.iodir)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _write_gppu(self, gppu=None): """Write the specified byte value to the GPPU registor. If no value specified the current buffered value will be written. """
if gppu is not None: self.gppu = gppu self.i2c.write_list(self.GPPU, self.gppu)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getJson(url): """Download json and return simplejson object"""
site = urllib2.urlopen(url, timeout=300) return json.load(site)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getWeb(url, isFeed): """Download url and parse it with lxml. If "isFeed" is True returns lxml.etree else, returns lxml.html """
socket.setdefaulttimeout(300) loadedWeb = urllib2.build_opener() loadedWeb.addheaders = getHeaders() if isFeed: web = etree.parse(loadedWeb.open(url)) else: web = html.parse(loadedWeb.open(url)) return web
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rmSelf(f): """f -> function. Decorator, removes first argument from f parameters. """
def new_f(*args, **kwargs): newArgs = args[1:] result = f(*newArgs, **kwargs) return result return new_f
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __builder_connect_pending_signals(self): """Called internally to actually make the internal Gtk.Builder instance connect all signals found in controllers con...
class _MultiHandlersProxy (object): def __init__(self, funcs): self.funcs = funcs def __call__(self, *args, **kwargs): # according to gtk documentation, the return value of # a signal is the return value of the last executed # handler ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _builder_connect_signals(self, _dict): """Called by controllers which want to autoconnect their handlers with signals declared in internal Gtk.Builder. This ...
assert not self.builder_connected, "Gtk.Builder not already connected" if _dict and not self.builder_pending_callbacks: # this is the first call, book the builder connection for # later gtk loop GLib.idle_add(self.__builder_connect_pending_signals) for n, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def __extract_autoWidgets(self): """Extract autoWidgets map if needed, out of the glade specifications and gtk builder"""
if self.__autoWidgets_calculated: return if self._builder is not None: for wid in self._builder.get_objects(): # General workaround for issue # https://bugzilla.gnome.org/show_bug.cgi?id=607492 try: name = Gtk.Buildable.ge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def clef_error_check(func_to_decorate): """Return JSON decoded response from API call. Handle errors when bad response encountered."""
def wrapper(*args, **kwargs): try: response = func_to_decorate(*args, **kwargs) except requests.exceptions.RequestException: raise ConnectionError( 'Clef encountered a network connectivity problem. Are you sure you are connected to the Internet?' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def raise_right_error(response): """Raise appropriate error when bad response received."""
if response.status_code == 200: return if response.status_code == 500: raise ServerError('Clef servers are down.') if response.status_code == 403: message = response.json().get('error') error_class = MESSAGE_TO_ERROR_MAP[message] if error_class == InvalidOAuthTokenEr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _call(self, method, url, params): """Return response from Clef API call."""
request_params = {} if method == 'GET': request_params['params'] = params elif method == 'POST': request_params['data'] = params response = requests.request(method, url, **request_params) return response
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_login_information(self, code=None): """Return Clef user info after exchanging code for OAuth token."""
# do the handshake to get token access_token = self._get_access_token(code) # make request with token to get user details return self._get_user_info(access_token)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_user_info(self, access_token): """Return Clef user info."""
info_response = self._call('GET', self.info_url, params={'access_token': access_token}) user_info = info_response.get('info') return user_info
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_logout_information(self, logout_token): """Return Clef user info after exchanging logout token."""
data = dict(logout_token=logout_token, app_id=self.app_id, app_secret=self.app_secret) logout_response = self._call('POST', self.logout_url, params=data) clef_user_id = logout_response.get('clef_id') return clef_user_id
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_observing_method(self, prop_names, method): """ Remove dynamic notifications. *method* a callable that was registered with :meth:`observe`. *prop_name...
for prop_name in prop_names: if prop_name in self.__PROP_TO_METHS: # exact match self.__PROP_TO_METHS[prop_name].remove(method) del self.__PAT_METH_TO_KWARGS[(prop_name, method)] elif method in self.__METH_TO_PAT: # found a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_observing_method(self, prop_name, method): """ Returns `True` if the given method was previously added as an observing method, either dynamically or via d...
if (prop_name, method) in self.__PAT_METH_TO_KWARGS: return True if method in self.__METH_TO_PAT: pat = self.__METH_TO_PAT[method] if fnmatch.fnmatch(prop_name, pat): return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_data(self, column, value, role): """Set the data for the given column to value The default implementation returns False :param column: the column to set ...
if role == QtCore.Qt.EditRole or role == QtCore.Qt.DisplayRole: self._list[column] = value return True else: return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_model(self, model): """Set the model the item belongs to A TreeItem can only belong to one model. :param model: the model the item belongs to :type model...
self._model = model for c in self.childItems: c.set_model(model)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_child(self, child): """Add child to children of this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None...
child.set_model(self._model) if self._model: row = len(self.childItems) parentindex = self._model.index_of_item(self) self._model.insertRow(row, child, parentindex) else: self.childItems.append(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_child(self, child): """Remove the child from this TreeItem :param child: the child TreeItem :type child: :class:`TreeItem` :returns: None :rtype: None...
child.set_model(None) if self._model: row = self.childItems.index(child) parentindex = self._model.index_of_item(self) self._model.removeRow(row, parentindex) else: self.childItems.remove(child)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def column_count(self, ): """Return the number of columns that the children have If there are no children, return the column count of its own data. :returns: the...
if self.child_count(): return self.childItems[0]._data.column_count() else: return self._data.column_count() if self._data else 0
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def data(self, column, role): """Return the data for the column and role :param column: the data column :type column: int :param role: the data role :type role: ...
if self._data is not None and (column >= 0 or column < self._data.column_count()): return self._data.data(column, role)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_data(self, column, value, role): """Set the data of column to value :param column: the column to set :type column: int :param value: the value to set :pa...
if not self._data or column >= self._data.column_count(): return False return self._data.set_data(column, value, role)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_parent(self, parent): """Set the parent of the treeitem :param parent: parent treeitem :type parent: :class:`TreeItem` | None :returns: None :rtype: None...
if self._parent == parent: return if self._parent: self._parent.remove_child(self) self._parent = parent if parent: parent.add_child(self)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rowCount(self, parent): """Return the number of rows under the given parent. When the parent is valid return rowCount the number of children of parent. :para...
if parent.column() > 0: return 0 if not parent.isValid(): parentItem = self._root else: parentItem = parent.internalPointer() return parentItem.child_count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def columnCount(self, parent): """Return the number of columns for the children of the given parent. :param parent: the parent index :type parent: :class:`QtCore...
if parent.isValid(): return parent.internalPointer().column_count() else: return self._root.column_count()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setData(self, index, value, role=QtCore.Qt.EditRole): """Set the data of the given index to value :param index: the index to set :type index: :class:`QtCore....
if not index.isValid(): return False item = index.internalPointer() r = item.set_data(index.column(), value, role) if r: self.dataChanged.emit(index, index) return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def headerData(self, section, orientation, role): """Return the header data Will call :meth:`TreeItem.data` of the root :class:`TreeItem` with the given section ...
if orientation == QtCore.Qt.Horizontal: d = self._root.data(section, role) if d is None and role == QtCore.Qt.DisplayRole: return str(section+1) return d if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole: return str(se...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def insertRow(self, row, item, parent): """Insert a single item before the given row in the child items of the parent specified. :param row: the index where the ...
item.set_model(self) if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginInsertRows(parent, row, row) item._parent = parentitem if parentitem: parentitem.childItems.insert(row, item) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def removeRow(self, row, parent): """Remove row from parent :param row: the row index :type row: int :param parent: the parent index :type parent: :class:`QtCore...
if parent.isValid(): parentitem = parent.internalPointer() else: parentitem = self._root self.beginRemoveRows(parent, row, row) item = parentitem.childItems[row] item.set_model(None) item._parent = None del parentitem.childItems[row] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def flags(self, index): """Return the flags for the given index This will call :meth:`TreeItem.flags` for valid ones. :param index: the index to query :type inde...
if index.isValid(): item = index.internalPointer() return item.flags(index) else: super(TreeModel, self).flags(index)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def index_of_item(self, item): """Get the index for the given TreeItem :param item: the treeitem to query :type item: :class:`TreeItem` :returns: the index of th...
# root has an invalid index if item == self._root: return QtCore.QModelIndex() # find all parents to get their index parents = [item] i = item while True: parent = i.parent() # break if parent is root because we got all parents we need...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dict(self, var, default=NOTSET, cast=None, force=True): """Convenience method for casting to a dict Note: Casting """
return self._get(var, default=default, cast={str: cast}, force=force)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decimal(self, var, default=NOTSET, force=True): """Convenience method for casting to a decimal.Decimal Note: Casting """
return self._get(var, default=default, cast=Decimal, force=force)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def json(self, var, default=NOTSET, force=True): """Get environment variable, parsed as a json string"""
return self._get(var, default=default, cast=json.loads, force=force)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_selection(self): """Call selection changed in the beginning, so signals get emitted once Emit shot_taskfile_sel_changed signal and asset_taskfile_sel_ch...
si = self.shotverbrws.selected_indexes(0) if si: self.shot_ver_sel_changed(si[0]) else: self.shot_ver_sel_changed(QtCore.QModelIndex()) ai = self.assetverbrws.selected_indexes(0) if ai: self.asset_ver_sel_changed(ai[0]) else: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setup_releasetype_buttons(self, ): """Create a radio button for every releasetype :returns: None :rtype: None :raises: None """
# we insert the radiobuttons instead of adding them # because there is already a spacer in the layout to # keep the buttons to the left. To maintain the original order # we insert them all to position 0 but in reversed order for rt in reversed(self._releasetypes): rb...