output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementation may be replaced by an optimized version whe...
Make a summary of the following Python 3 code def _websocket_mask_python(mask, data): # type: (bytes, bytes) -> bytes """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask appl...
You are a Python code generator, capable of creating scripts from specifications.
Sets the class to use when the base class is instantiated.
Here you have a function in Python 3, explain what it does def configure(cls, impl, **kwargs): # type: (Any, **Any) -> None """Sets the class to use when the base class is instantiated. Keyword arguments will be saved and added to the arguments passed to the constructor. This can be us...
As a Python code composer, you craft elegant and concise scripts.
def configured_class(cls): # type: () -> type """Returns the currently configured class.""" base = cls.configurable_base() # Manually mangle the private name to see whether this base # has been configured (and not another base higher in the # hierarchy). if base._...
Create a Python 3 function to return the currently configured class.
As a Python code composer, you craft elegant and concise scripts.
Returns the old value of the named argument without replacing it.
Explain what the following Python 3 code does def get_old_value(self, args, kwargs, default=None): # type: (List[Any], Dict[str, Any], Any) -> Any """Returns the old value of the named argument without replacing it. Returns ``default`` if the argument is not present. """ if self...
You are a Python code generator, capable of creating scripts from specifications.
def replace(self, new_value, args, kwargs): # type: (Any, List[Any], Dict[str, Any]) -> Tuple[Any, List[Any], Dict[str, Any]] """Replace the named argument in ``args, kwargs`` with ``new_value``. Returns ``(old_value, args, kwargs)``. The returned ``args`` and ``kwargs`` objects may no...
Write a Python 3 script for replacing the named argument in args with new_value.
As a Python code translator, you convert algorithms and pseudocode into Python.
def popup(self): """ Show the notification from code. This will initialize and activate if needed. Notes ------ This does NOT block. Callbacks should be used to handle click events or the `show` state should be observed to know when it is closed. ...
Implement a function in Python 3 to show the notification from code.
You are a Python code analyst, evaluating scripts for potential improvements.
Create the underlying toast.
Can you generate the documentation for the following Python 3 function def create_widget(self): d = self.declaration if d.text: Toast.makeText(self.get_context(), d.text, 1).then(self.on_make_toast) self.made_toast = True else: self....
You are a Python code architect, reviewing and designing scalable and efficient code
Initialize the AndroidToast widget.
Can you tell what is the following Python 3 function doing def init_widget(self): if not self.toast: return super(AndroidToast, self).init_widget() d = self.declaration if not self.made_toast: #: Set it to LONG self.toast.setDuration(1) if d.g...
You are a Python code generator, capable of creating scripts from specifications.
def init_layout(self): """ If a view is given show it """ super(AndroidToast, self).init_layout() if not self.made_toast: for view in self.child_widgets(): self.toast.setView(view) break
Implement a Python 3 function for initializing the layout of the toast.
As a Python code analyst, you investigate and solve complex coding mysteries
Overwrite the view of the child
Explain what the following Python 3 code does def child_added(self, child): view = child.widget if view is not None: self.toast.setView(view)
As a Python code composer, you craft elegant and concise scripts.
Using Toast. makeToast returns async so we have to initialize it
Can you tell what is the following Python 3 function doing def on_make_toast(self, ref): d = self.declaration self.toast = Toast(__id__=ref) self.init_widget()
You are a Python code analyst, evaluating scripts for potential improvements.
Keep calling. show until the duration dt expires.
How would you explain what the following Python 3 function does def _refresh_show(self, dt): d = self.declaration if dt <= 0: #: Done, hide d.show = False elif d.show: #: If user didn't cancel it, keep it alive self.toast.show() t = mi...
As a python code expert, you are capable of creating scripts from specifications.
Create the underlying dialog.
Explain what the following Python 3 code does def create_widget(self): d = self.declaration self.dialog = Dialog(self.get_context(), d.style)
As a python code expert, you are capable of creating scripts from specifications.
def init_widget(self): """ Set the listeners """ w = self.dialog # Listen for events w.setOnDismissListener(w.getId()) w.onDismiss.connect(self.on_dismiss) w.setOnCancelListener(w.getId()) w.onCancel.connect(self.on_cancel) super(AndroidDialog, sel...
How would you implement a function in Python 3 that initializes the dialog widget.
You are a Python code analyst, evaluating scripts for potential improvements.
Initialize the layout of the dialog.
Can you generate the documentation for the following Python 3 function def init_layout(self): super(AndroidDialog, self).init_layout() #: Set the content for view in self.child_widgets(): self.dialog.setContentView(view) break #: Show it if needed d = se...
As a Python code translator, you convert algorithms and pseudocode into Python.
Overwrite the content view of the given child.
Can you generate the documentation for the following Python 3 function def child_added(self, child): view = child.widget if view is not None: self.dialog.setContentView(view)
You are a Python code analyst, evaluating scripts for potential improvements.
A reimplemented destructor that cancels the dialog before destroying.
Make a summary of the following Python 3 code def destroy(self): dialog = self.dialog if dialog: #: Clear the dismiss listener #: (or we get an error during the callback) dialog.setOnDismissListener(None) dialog.dismiss() del self.dialog ...
You are a Python code analyst, evaluating scripts for potential improvements.
def start(cls, callback, provider='gps', min_time=1000, min_distance=0): """ Convenience method that checks and requests permission if necessary and if successful calls the callback with a populated `Location` instance on updates. Note you must have the permissions in your manifest or ...
Implement a Python 3 function for starting a new instance of LocationManager.
You are a Python code analyst, evaluating scripts for potential improvements.
Stops location updates if currently updating.
How would you explain what the following Python 3 function does def stop(cls): manager = LocationManager.instance() if manager: for l in manager.listeners: manager.removeUpdates(l) manager.listeners = []
You are a Python code architect, reviewing and designing scalable and efficient code
def check_permission(cls, fine=True): """ Returns a future that returns a boolean indicating if permission is currently granted or denied. If permission is denied, you can request using `LocationManager.request_permission()` below. """ app = AndroidApplication.instance() ...
Implement a function in Python 3 to return a future that returns a boolean indicating if permission is currently granted or denied.
You are a Python code generator, capable of creating scripts from specifications.
Requests permission and returns an async result that returns a boolean indicating if the permission was granted or denied.
Given the following Python 3 function, write the documentation def request_permission(cls, fine=True): app = AndroidApplication.instance() permission = (cls.ACCESS_FINE_PERMISSION if fine else cls.ACCESS_COARSE_PERMISSION) f = app.create_future() def on_result(perm...
As a python code expert, you are capable of creating scripts from specifications.
Create the underlying widget.
Here you have a function in Python 3, explain what it does def create_widget(self): d = self.declaration self.widget = WebView(self.get_context(), None, d.style)
As a Python code composer, you craft elegant and concise scripts.
Initialize the underlying webview.
Can you generate the documentation for the following Python 3 function def init_widget(self): # Create and init the client c = self.client = BridgedWebViewClient() c.setWebView(self.widget, c.getId()) c.onLoadResource.connect(self.on_load_resource) c.onPageFinished.connect(self.o...
You are a Python code architect, reviewing and designing scalable and efficient code
Destroy the client and the widget.
Here you have a function in Python 3, explain what it does def destroy(self): if self.client: #: Stop listening self.client.setWebView(self.widget, None) del self.client super(AndroidWebView, self).destroy()
As a Python code translator, you convert algorithms and pseudocode into Python.
def init_widget(self): """ Bind the on property to the checked state """ super(UiKitSlider, self).init_widget() d = self.declaration if d.min: self.set_min(d.min) if d.max: self.set_max(d.max) if d.progress: self.set_progress(d.progres...
Create a Python 3 function to bind the on property to the checked state
You are a Python code generator, capable of creating scripts from specifications.
Update the progress of the check button.
How would you explain what the following Python 3 function does def on_checked_changed(self, value): #: Since iOS decides to call this like 100 times for each defer it d = self.declaration with self.widget.setValue.suppressed(): d.progress = int(value)
As a Python code composer, you craft elegant and concise scripts.
def init_layout(self): """ Set the checked state after all children have been populated. """ super(AndroidRadioGroup, self).init_layout() d = self.declaration w = self.widget if d.checked: self.set_checked(d.checked) else: ...
Implement a function in Python 3 to initialize the radio group.
As a Python code composer, you craft elegant and concise scripts.
Called when a checked attribute is changed in the group.
Explain what the following Python 3 code does def on_checked_changed(self, group, checked_id): d = self.declaration if checked_id < 0: with self.widget.clearCheck.suppressed(): d.checked = None return else: for c in self.children(): ...
You are a Python code architect, reviewing and designing scalable and efficient code
def set_checked(self, checked): """ Properly check the correct radio button. """ if not checked: self.widget.clearCheck() else: #: Checked is a reference to the radio declaration #: so we need to get the ID of it rb = checked.proxy.widget ...
Write a Python 3 function for setting the radio button to be checked.
You are a Python code analyst, evaluating scripts for potential improvements.
Initialize on the first call to the widget.
Can you generate the documentation for the following Python 3 function def init_widget(self): #: Add a ActivityLifecycleListener to update the application state activity = self.widget activity.addActivityLifecycleListener(activity.getId()) activity.onActivityLifecycleChanged.connect( ...
As a python code expert, you are capable of creating scripts from specifications.
Return a future that resolves with the result of the permission RUKnce.
Given the following Python 3 function, write the documentation def has_permission(self, permission): f = self.create_future() #: Old versions of android did permissions at install time if self.api_level < 23: f.set_result(True) return f def on_result(allowed): ...
You are a Python code architect, reviewing and designing scalable and efficient code
def request_permissions(self, permissions): """ Return a future that resolves with the results of the permission requests """ f = self.create_future() #: Old versions of android did permissions at install time if self.api_level < 23: f.set_result({p...
Can you implement a function in Python 3 that requests the permissions of the specified set of permissions.
You are a Python code analyst, evaluating scripts for potential improvements.
def show_toast(self, msg, long=True): """ Show a toast message for the given duration. This is an android specific api. Parameters ----------- msg: str Text to display in the toast message long: bool Display for a long or short (system defined) du...
Implement a Python 3 function for showing a toast message for the given duration.
As a Python code composer, you craft elegant and concise scripts.
Fire the back_pressed event with a dictionary with a handled key that evaluates to True and return a boolean that is True if the back hardware button is pressed AttributeNames is not set to any value that evaluates to True.
Here you have a function in Python 3, explain what it does def on_back_pressed(self): try: event = {'handled': False} self.back_pressed(event) return bool(event.get('handled', False)) except Exception as e: #: Must return a boolean or we will cause android...
As a python code expert, you are capable of creating scripts from specifications.
Handles a screen configuration change.
Can you generate the documentation for the following Python 3 function def on_configuration_changed(self, config): self.width = config['width'] self.height = config['height'] self.orientation = ('square', 'portrait', 'landscape')[ config['orientation']]
You are a Python code analyst, evaluating scripts for potential improvements.
def show_view(self): """ Show the current `app.view`. This will fade out the previous with the new view. """ if not self.build_info: def on_build_info(info): """ Make sure the build info is ready before we display the view ...
Create a Python 3 function to show the current view. This will fade out the previous view. This will fade out the new view.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _on_permission_result(self, code, perms, results): """ Handles a permission request result by passing it to the handler with the given code. """ #: Get the handler for this request handler = self._permission_requests.get(code, None) if handler is not None: ...
Implement a function in Python 3 to handle a permission request result by passing it to the appropriate handler with the given code.
As a python code expert, you are capable of creating scripts from specifications.
def _observe_keep_screen_on(self, change): """ Sets or clears the flag to keep the screen on. """ def set_screen_on(window): from .android_window import Window window = Window(__id__=window) if self.keep_screen_on: window.addFlags(Win...
Write a Python 3 function for setting or clears the flag to keep the screen on.
You are a Python code architect, reviewing and designing scalable and efficient code
Load all plugin toolkit widgets into the ANDROID_FACTORIES dictionary.
How would you explain what the following Python 3 function does def load_plugin_factories(self): for plugin in self.get_plugins(group='enaml_native_android_factories'): get_factories = plugin.load() PLUGIN_FACTORIES = get_factories() factories.ANDROID_FACTORIES.update(PLUGIN_...
You are a Python code architect, reviewing and designing scalable and efficient code
Initialize the widget and bind the on property to the checked state
Make a summary of the following Python 3 code def init_widget(self): super(UiKitEditText, self).init_widget() #: Init font properties etc... self.init_text() d = self.declaration if d.placeholder: self.set_placeholder(d.placeholder) if d.input_type != 'text'...
You are a Python code analyst, evaluating scripts for potential improvements.
Update the text field of the resource entry.
Can you generate a brief explanation for the following Python 3 code def on_value_changed(self, text): d = self.declaration with self.widget.get_member('text').suppressed(self.widget): d.text = text
As a python code expert, you are capable of creating scripts from specifications.
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = DatePicker(self.get_context(), None, d.style or "@attr/datePickerStyle")
Implement a Python 3 function for creating the underlying widget.
As a Python code composer, you craft elegant and concise scripts.
def init_widget(self): """ Initialize the underlying widget. """ d = self.declaration w = self.widget date = d.date w.init(date.year, date.month-1, date.day, w.getId()) super(AndroidDatePicker, self).init_widget() w.onDateChanged.connect(self.on_date_chan...
Can you implement a function in Python 3 that initializes the underlying widget.
As a Python code composer, you craft elegant and concise scripts.
def imports(): """ Install the import hook to load python extensions from app's lib folder during the context of this block. This method is preferred as it's faster than using install. """ from .core.import_hooks import ExtensionImporter importer = ExtensionImporter() sys.meta_path....
Write a Python 3 function for installing the import hook to load python extensions from app s lib folder during the context of this block.
You are a Python code architect, reviewing and designing scalable and efficient code
def install(): """ Install the import hook to load extensions from the app Lib folder. Like imports but leaves it in the meta_path, thus it is slower. """ from .core.import_hooks import ExtensionImporter importer = ExtensionImporter() sys.meta_path.append(importer)
Write a Python 3 function that can install the import hook to load extensions from the app Lib folder.
As a Python code translator, you convert algorithms and pseudocode into Python.
def source_from_cache(path): """Given the path to a .pyc. file, return the path to its .py file. The .pyc file does not need to exist; this simply returns the path to the .py file calculated to correspond to the .pyc file. If path does not conform to PEP 3147/488 format, ValueError will be raised. If ...
Implement a Python 3 function for giving the path to a. pyc. file return the path to its. py file.
As a python code expert, you are capable of creating scripts from specifications.
def init_request(self): """ Init the native request using the okhttp3.Request.Builder """ #: Build the request builder = Request.Builder() builder.url(self.url) #: Set any headers for k, v in self.headers.items(): builder.addHeader(k, v) #: Get the ...
How would you implement a function in Python 3 that initializes the native request based on the method and content type.
As a python code expert, you are capable of creating scripts from specifications.
Default body for the resource.
Explain what the following Python 3 code does def _default_body(self): if not self.data: return "" if self.content_type == 'application/json': import json return json.dumps(self.data) elif self.content_type == 'application/x-www-form-urlencoded': i...
As a Python code analyst, you investigate and solve complex coding mysteries
def on_finish(self): """ Called regardless of success or failure """ r = self.response r.request_time = time.time() - self.start_time if self.callback: self.callback(r)
Can you write a function in Python 3 where it calls regardless of success or failure
As a Python code translator, you convert algorithms and pseudocode into Python.
def _fetch(self, request): """ Fetch using the OkHttpClient """ client = self.client #: Dispatch the async call call = Call(__id__=client.newCall(request.request)) call.enqueue(request.handler) #: Save the call reference request.call = call
How would you code a function in Python 3 to fetch the request using the OkHttpClient
You are a Python code architect, reviewing and designing scalable and efficient code
Create the underlying widget.
Can you generate the documentation for the following Python 3 function def create_widget(self): d = self.declaration self.widget = CheckBox(self.get_context(), None, d.style or "@attr/checkboxStyle")
As a Python code composer, you craft elegant and concise scripts.
Fetch the given url and fire the callback when ready.
Here you have a function in Python 3, explain what it does def fetch(self, url, callback=None, raise_error=True, **kwargs): app = BridgedApplication.instance() f = app.create_future() #: Set callback for when response is in if callback is not None: f.then(callback) ...
You are a Python code architect, reviewing and designing scalable and efficient code
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = GridLayout(self.get_context(), None, d.style)
Create a Python 3 function to create the underlying widget.
You are a Python code analyst, evaluating scripts for potential improvements.
Create the underlying widget.
Can you generate a brief explanation for the following Python 3 code def create_widget(self): d = self.declaration self.widget = Switch(self.get_context(), None, d.style or '@attr/switchStyle')
You are a Python code analyst, evaluating scripts for potential improvements.
def init_widget(self): """ Initialize the underlying widget. """ super(AndroidSwitch, self).init_widget() d = self.declaration self.set_show_text(d.show_text) if d.split_track: self.set_split_track(d.split_track) if d.text_off: self.set_te...
Write a Python 3 script for initializing the underlying widget.
You are a Python code generator, capable of creating scripts from specifications.
Load the object defined by the plugin entry point
Can you generate a brief explanation for the following Python 3 code def load(self): print("[DEBUG] Loading plugin {} from {}".format(self.name, self.source)) import pydoc path, attr = self.source.split(":") module = pydoc.locate(p...
You are a Python code analyst, evaluating scripts for potential improvements.
def _default_plugins(self): """ Get entry points to load any plugins installed. The build process should create an "entry_points.json" file with all of the data from the installed entry points. """ plugins = {} try: with open('entry_points.json') as ...
Can you write a function in Python 3 where it gets entry points to load any plugins installed.
You are a Python code analyst, evaluating scripts for potential improvements.
Start the application s main event loop using either twisted or tornado.
Make a summary of the following Python 3 code def start(self): #: Schedule a load view if given and remote debugging is not active #: the remote debugging init call this after dev connection is ready if self.load_view and self.dev != "remote": self.deferred_call(self.load_view, self)...
As a Python code translator, you convert algorithms and pseudocode into Python.
def timed_call(self, ms, callback, *args, **kwargs): """ Invoke a callable on the main event loop thread at a specified time in the future. Parameters ---------- ms : int The time to delay, in milliseconds, before executing the callable. callback...
Create a Python 3 function to invoke a callable on the main event loop thread at some time in milliseconds.
As a Python code translator, you convert algorithms and pseudocode into Python.
Add a callback to invoke when the current event loop is done.
Make a summary of the following Python 3 code def add_done_callback(self, future, callback): if future is None: raise bridge.BridgeReferenceError( "Tried to add a callback to a nonexistent Future. " "Make sure you pass the `returns` argument to your JavaMethod") ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def get_view(self): """ Get the root view to display. Make sure it is properly initialized. """ view = self.view if not view.is_initialized: view.initialize() if not view.proxy_is_active: view.activate_proxy() return view.proxy.wid...
Write a Python 3 function that can get the root view to display. Make sure it is properly initialized.
As a python code expert, you are capable of creating scripts from specifications.
def send_event(self, name, *args, **kwargs): """ Send an event to the native handler. This call is queued and batched. Parameters ---------- name : str The event name to be processed by MainActivity.processMessages. *args: args The arguments requ...
Create a Python 3 function to send an event to the native handler.
As a Python code analyst, you investigate and solve complex coding mysteries
Send the events over the bridge.
Can you generate the documentation for the following Python 3 function def _bridge_send(self, now=False): if len(self._bridge_queue): if self.debug: print("======== Py --> Native ======") for event in self._bridge_queue: print(event) ...
As a Python code composer, you craft elegant and concise scripts.
Process events from the native implementation.
Here you have a function in Python 3, explain what it does def process_events(self, data): events = bridge.loads(data) if self.debug: print("======== Py <-- Native ======") for event in events: print(event) print("===========================") ...
As a python code expert, you are capable of creating scripts from specifications.
When we get an event from the bridge we handle it by invoking the handler and sending back the result.
Explain what the following Python 3 code does def handle_event(self, event): result_id, ptr, method, args = event[1] obj = None result = None try: obj, handler = bridge.get_handler(ptr, method) result = handler(*[v for t, v in args]) except bridge.BridgeRe...
As a Python code composer, you craft elegant and concise scripts.
def handle_error(self, callback): """ Called when an error occurs in an event loop callback. By default, sets the error view. """ self.loop.log_error(callback) msg = "\n".join([ "Exception in callback %r"%callback, traceback.format_exc() ]...
Can you implement a function in Python 3 that calls when an error occurs in an event loop callback.
As a python code expert, you are capable of creating scripts from specifications.
Start a client that attempts to connect to the dev server alid
How would you explain what the following Python 3 function does def start_dev_session(self): try: from .dev import DevServerSession session = DevServerSession.initialize(host=self.dev) session.start() #: Save a reference self._dev_session = session ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def load_plugin_widgets(self): """ Pull widgets added via plugins using the `enaml_native_widgets` entry point. The entry point function must return a dictionary of Widget declarations to add to the core api. def install(): from charts.widgets.chart_view import BarChart, L...
Implement a Python 3 function for loading widgets added via plugins using the enaml_native_widgets entry point.
You are a Python code generator, capable of creating scripts from specifications.
def for_action(cls, action, callback, single_shot=True): """ Create a BroadcastReceiver that is invoked when the given action is received. Parameters ---------- action: String Action to receive callback: Callable Callback to invoke when t...
Write a Python 3 script to create a BroadcastReceiver that is invoked when the given action is received.
You are a Python code architect, reviewing and designing scalable and efficient code
Return the latest measurement for the given class.
Can you tell what is the following Python 3 function doing def get(self, measurement_class): name = Measurement.name_from_class(measurement_class) return self._construct_measurement(name)
You are a Python code architect, reviewing and designing scalable and efficient code
def add_source(self, source): """Add a vehicle data source to the instance. The Vehicle instance will be set as the callback of the source, and the source will be started if it is startable. (i.e. it has a ``start()`` method). """ if source is not None: self....
Write a Python 3 function that can add a vehicle data source to the instance.
As a Python code composer, you craft elegant and concise scripts.
Add a vehicle data sink to the instance.
Explain what the following Python 3 code does def add_sink(self, sink): if sink is not None: self.sinks.add(sink) if hasattr(sink, 'start'): sink.start()
You are a Python code architect, reviewing and designing scalable and efficient code
def register(self, measurement_class, callback): """Call the ``callback`` with any new values of ``measurement_class`` received. """ self.callbacks[Measurement.name_from_class(measurement_class) ].add(callback)
Create a Python 3 function to register a callback for any new values of measurement_class received.
You are a Python code analyst, evaluating scripts for potential improvements.
Unregister a callback for a specific measurement class.
Can you generate the documentation for the following Python 3 function def unregister(self, measurement_class, callback): self.callbacks[Measurement.name_from_class(measurement_class) ].remove(callback)
You are a Python code analyst, evaluating scripts for potential improvements.
Send a request via the USB control request endpoint rather than as abulk transfer.
Can you tell what is the following Python 3 function doing def _send_complex_request(self, request): self.device.ctrl_transfer(0x40, self.COMPLEX_CONTROL_COMMAND, 0, 0, self.streamer.serialize_for_stream(request))
As a Python code translator, you convert algorithms and pseudocode into Python.
def out_endpoint(self): """Open a reference to the USB device's only OUT endpoint. This method assumes that the USB device configuration has already been set. """ if getattr(self, '_out_endpoint', None) is None: config = self.device.get_active_configuration() inte...
Create a Python 3 function for opening a reference to the USB device s only OUT endpoint. This method returns None if the USB device configuration has already been set.
You are a Python code architect, reviewing and designing scalable and efficient code
Block the thread and wait for the response to arrive from the VI.
Explain what the following Python 3 code does def wait_for_responses(self): self.thread.join(self.COMMAND_RESPONSE_TIMEOUT_S) self.running = False return self.responses
As a Python code composer, you craft elegant and concise scripts.
Block and wait for responses to this object s original request or None if no responses were received before the timeout.
Can you generate the documentation for the following Python 3 function def handle_responses(self): while self.running: try: response = self.queue.get( timeout=self.COMMAND_RESPONSE_TIMEOUT_S) if self._response_matches_request(response): ...
As a Python code composer, you craft elegant and concise scripts.
Return true if the response is to a diagnostic request and the bus id mode match.
Make a summary of the following Python 3 code def _response_matches_request(self, response): # Accept success/failure command responses if super(DiagnosticResponseReceiver, self)._response_matches_request(response): return True if ('bus' in self.diagnostic_request an...
As a python code expert, you are capable of creating scripts from specifications.
def complex_request(self, request, wait_for_first_response=True): """Send a compound command request to the interface over the normal data channel. request - A dict storing the request to send to the VI. It will be serialized to the currently selected output format. wait_for...
Create a Python 3 function for sending a compound command request to the interface over the normal data channel.
You are a Python code analyst, evaluating scripts for potential improvements.
def create_diagnostic_request(self, message_id, mode, bus=None, pid=None, frequency=None, payload=None, wait_for_ack=True, wait_for_first_response=False, decoded_type=None): """Send a new diagnostic message request to the VI Required: message_id - The message ID (arbitr...
Create a Python 3 function for creating a new diagnostic message request to the VI and returns it.
As a Python code translator, you convert algorithms and pseudocode into Python.
def set_passthrough(self, bus, enabled): """Control the status of CAN message passthrough for a bus. Returns True if the command was successful. """ request = { "command": "passthrough", "bus": bus, "enabled": enabled } return self._ch...
Write a Python 3 script to control the status of a CAN message passthrough for a bus. Returns True if the command was successful.
You are a Python code generator, capable of creating scripts from specifications.
def set_payload_format(self, payload_format): """Set the payload format for messages sent to and from the VI. Returns True if the command was successful. """ request = { "command": "payload_format", "format": payload_format } status = self._check_...
How would you code a function in Python 3 to set the payload format for messages sent to and from the VI. Returns True if the command was successful.
You are a Python code generator, capable of creating scripts from specifications.
def rtc_configuration(self, unix_time): """Set the Unix time if RTC is supported on the device. Returns True if the command was successful. """ request = { "command": "rtc_configuration", "unix_time": unix_time } status = self._check_command_respo...
Create a Python 3 function to set the Unix time if RTC is supported on the device. Returns True if the command was successful.
As a Python code analyst, you investigate and solve complex coding mysteries
Send the modem_configuration command to the Cellular device to send data to. Returns True if the command was successful.
Explain what the following Python 3 code does def modem_configuration(self, host, port): request = { "command": "modem_configuration", "host": host, "port": port } status = self._check_command_response_status(request) return status
As a Python code analyst, you investigate and solve complex coding mysteries
def set_acceptance_filter_bypass(self, bus, bypass): """Control the status of CAN acceptance filter for a bus. Returns True if the command was successful. """ request = { "command": "af_bypass", "bus": bus, "bypass": bypass } return se...
Write a Python 3 function for controlling the status of CAN acceptance filter for a bus.
As a Python code composer, you craft elegant and concise scripts.
Request for SD Mount status if available.
How would you explain what the following Python 3 function does def sd_mount_status(self): request = { "command": "sd_mount_status" } responses = self.complex_request(request) result = None if len(responses) > 0: result = responses[0].get('status') ...
As a Python code composer, you craft elegant and concise scripts.
def write(self, **kwargs): """Serialize a raw or translated write request and send it to the VI, following the OpenXC message format. """ if 'id' in kwargs and 'data' in kwargs: result = self.write_raw(kwargs['id'], kwargs['data'], bus=kwargs.get('bus', No...
Implement a function in Python 3 to serialize a raw or translated write request and send it to the VI
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a translated write request to the VI.
Explain what the following Python 3 code does def write_translated(self, name, value, event=None): data = {'name': name} if value is not None: data['value'] = self._massage_write_value(value) if event is not None: data['event'] = self._massage_write_value(event); ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Send a raw write request to the VI.
Can you generate a brief explanation for the following Python 3 code def write_raw(self, message_id, data, bus=None, frame_format=None): if not isinstance(message_id, numbers.Number): try: message_id = int(message_id, 0) except ValueError: raise ValueError...
As a Python code analyst, you investigate and solve complex coding mysteries
Convert string values from command - line arguments into first - order boolean and float objects if applicable.
Explain what the following Python 3 code does def _massage_write_value(cls, value): if not isinstance(value, numbers.Number): if value == "true": value = True elif value == "false": value = False elif value[0] == '"' and value[-1] == '"': ...
You are a Python code generator, capable of creating scripts from specifications.
Confirm the validitiy of a given dict as an OpenXC message.
Can you generate the documentation for the following Python 3 function def _validate(cls, message): valid = False if(('name' in message and 'value' in message) or ('id' in message and 'data' in message)): valid = True return valid
You are a Python code generator, capable of creating scripts from specifications.
def value(self, new_value): """Set the value of this measurement. Raises: AttributeError: if the new value isn't of the correct units. """ if self.unit != units.Undefined and new_value.unit != self.unit: raise AttributeError("%s must be in %s" % ( ...
Write a Python 3 script for setting the value of this measurement.
As a Python code analyst, you investigate and solve complex coding mysteries
Create a new Measurement subclass instance from a dictionary.
Can you generate a brief explanation for the following Python 3 code def from_dict(cls, data): args = [] if 'id' in data and 'data' in data: measurement_class = CanMessage args.append("Bus %s: 0x%x" % (data.get('bus', '?'), data['id'])) args.append(data['data']) ...
As a Python code composer, you craft elegant and concise scripts.
def name_from_class(cls, measurement_class): """For a given measurement class, return its generic name. The given class is expected to have a ``name`` attribute, otherwise this function will raise an execption. The point of using this method instead of just trying to grab that attribute...
Write a Python 3 function that can return the generic name for a given measurement class.
You are a Python code analyst, evaluating scripts for potential improvements.
def _store_timestamp(self, timestamp): """If not already saved, cache the first timestamp in the active trace file on the instance. """ if getattr(self, 'first_timestamp', None) is None: self.first_timestamp = timestamp LOG.debug("Storing %d as the first timestamp...
Write a Python 3 script for storing the first timestamp of the trace file.
You are a Python code analyst, evaluating scripts for potential improvements.
def read(self): """Read a line of data from the input source at a time.""" line = self.trace_file.readline() if line == '': if self.loop: self._reopen_file() else: self.trace_file.close() self.trace_file = None ...
Implement a function in Python 3 to read a line of data from the input source at a time.
You are a Python code analyst, evaluating scripts for potential improvements.
def _open_file(filename): """Attempt to open the the file at ``filename`` for reading. Raises: DataSourceError, if the file cannot be opened. """ if filename is None: raise DataSourceError("Trace filename is not defined") try: trace_file = op...
Write a Python 3 script to attempt to open the file at filename for reading.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _wait(starting_time, first_timestamp, timestamp): """Given that the first timestamp in the trace file is ``first_timestamp`` and we started playing back the file at ``starting_time``, block until the current ``timestamp`` should occur. """ target_time = starting_time + (times...
Implement a function in Python 3 to block until the current timestamp is reached.
As a Python code composer, you craft elegant and concise scripts.
def merge(a, b): """Merge two deep dicts non-destructively Uses a stack to avoid maximum recursion depth exceptions >>> a = {'a': 1, 'b': {1: 1, 2: 2}, 'd': 6} >>> b = {'c': 3, 'b': {2: 7}, 'd': {'z': [1, 2, 3]}} >>> c = merge(a, b) >>> from pprint import pprint; pprint(c) {'a': 1, 'b': {1...
Write a Python 3 script for merging two deep dicts non - destructively generates a new tree structure
You are a Python code generator, capable of creating scripts from specifications.