INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Provides a json dump of the struct Args: struct: The data to dump wrap (bool, optional): Specify whether to wrap the struct in an enclosing dict struct_key (str, optional): The string key which will contain the struct in the result dict meta (dict, optional):...
def jsoned(struct, wrap=True, meta=None, struct_key='result', pre_render_callback=None): """ Provides a json dump of the struct Args: struct: The data to dump wrap (bool, optional): Specify whether to wrap the struct in an enclosing dict struct_key (str, optional): The strin...
A decorator used to return a JSON response of a list of model objects. It expects the decorated function to return a list of model instances. It then converts the instances to dicts and serializes them into a json response Examples: >>> @app.route('/api') ... @a...
def as_list(func): """ A decorator used to return a JSON response of a list of model objects. It expects the decorated function to return a list of model instances. It then converts the instances to dicts and serializes them into a json response Examples: >>> @app.route...
filters = { "c": "AND", "f": [ { "k": "layout_id", "op": "=", "v": 1 }, { "k": "created_at", "op": ">=", "v": "2014-11-10T11:53:33" }, { ...
def filter_query_using_filters_list(result, filters_dict): """ filters = { "c": "AND", "f": [ { "k": "layout_id", "op": "=", "v": 1 }, { "k": "created_at", "op": ">=", ...
A decorator used to return a JSON response of a list of model objects. It differs from `as_list` in that it accepts a variety of querying parameters and can use them to filter and modify the results. It expects the decorated function to return either Model Class to query or a SQLAlchemy ...
def as_processed_list(func): """ A decorator used to return a JSON response of a list of model objects. It differs from `as_list` in that it accepts a variety of querying parameters and can use them to filter and modify the results. It expects the decorated function to return either Model Cl...
A decorator used to return a JSON response with a dict representation of the model instance. It expects the decorated function to return a Model instance. It then converts the instance to dicts and serializes it into a json response Examples: >>> @app.route('/api/shipments...
def as_obj(func): """ A decorator used to return a JSON response with a dict representation of the model instance. It expects the decorated function to return a Model instance. It then converts the instance to dicts and serializes it into a json response Examples: >>> ...
:return: None
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) #self.needs_data(data, 6) self.set_attributes(priority, address, rtr) self.module_type =...
:return: str
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['sub_1'] = self.sub_address_1 json_dict['sub_2'] = self.sub_address_2 json_dict['sub_3'] = self.sub_address_3 json_dict['sub_4'] = self.sub_address_4 return json.dum...
:return: str
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['ds'] = self._ds return json.dumps(json_dict)
Refresh the object in place.
def refresh(self): # type: () -> None """Refresh the object in place.""" src = self._client.reload(self) self.__dict__.update(src.__dict__)
:return: None
def populate(self, priority, address, rtr, data): """ :return: None """ self.needs_no_rtr(rtr) self.set_attributes(priority, address, rtr)
:return: str
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['sleep_time'] = self.sleep return json.dumps(json_dict)
Execute the service. For interactive (notebook) service execution, set interactive to True, defaults to False. .. versionadded:: 1.13 :param interactive: (optional) True if the notebook service should execute in interactive mode. :type interactive: bool or None :return: Servic...
def execute(self, interactive=False): """ Execute the service. For interactive (notebook) service execution, set interactive to True, defaults to False. .. versionadded:: 1.13 :param interactive: (optional) True if the notebook service should execute in interactive mode. ...
Edit Service details. .. versionadded:: 1.13 :param name: (optional) name of the service to change. :type name: basestring or None :param description: (optional) description of the service. :type description: basestring or None :param version: (optional) version number ...
def edit(self, name=None, description=None, version=None, **kwargs): """ Edit Service details. .. versionadded:: 1.13 :param name: (optional) name of the service to change. :type name: basestring or None :param description: (optional) description of the service. ...
Delete this service. :raises APIError: if delete was not succesfull.
def delete(self): # type: () -> None """Delete this service. :raises APIError: if delete was not succesfull. """ response = self._client._request('DELETE', self._client._build_url('service', service_id=self.id)) if response.status_code != requests.codes.no_content: # p...
Upload a python script (or kecpkg) to the service. .. versionadded:: 1.13 :param pkg_path: path to the python script or kecpkg to upload. :type pkg_path: basestring :raises APIError: if the python package could not be uploaded. :raises OSError: if the python package could not b...
def upload(self, pkg_path): """ Upload a python script (or kecpkg) to the service. .. versionadded:: 1.13 :param pkg_path: path to the python script or kecpkg to upload. :type pkg_path: basestring :raises APIError: if the python package could not be uploaded. :r...
Save the kecpkg service script to an (optional) target dir. Retains the filename of the service as known in KE-chain. .. versionadded:: 1.13 :param target_dir: (optional) target dir. If not provided will save to current working directory. :type target_dir: basestring or None :...
def save_as(self, target_dir=None): """ Save the kecpkg service script to an (optional) target dir. Retains the filename of the service as known in KE-chain. .. versionadded:: 1.13 :param target_dir: (optional) target dir. If not provided will save to current working directory...
Retrieve the executions related to the current service. .. versionadded:: 1.13 :param kwargs: (optional) additional search keyword arguments to limit the search even further. :type kwargs: dict :return: list of ServiceExecutions associated to the current service.
def get_executions(self, **kwargs): """ Retrieve the executions related to the current service. .. versionadded:: 1.13 :param kwargs: (optional) additional search keyword arguments to limit the search even further. :type kwargs: dict :return: list of ServiceExecutions a...
Retrieve the `Service` object to which this execution is associated.
def service(self): """Retrieve the `Service` object to which this execution is associated.""" if not self._service: self._service = self._client.service(id=self.service_id) return self._service
Terminate the Service execution. .. versionadded:: 1.13 :return: None if the termination request was successful :raises APIError: When the service execution could not be terminated.
def terminate(self): """ Terminate the Service execution. .. versionadded:: 1.13 :return: None if the termination request was successful :raises APIError: When the service execution could not be terminated. """ url = self._client._build_url('service_execution_te...
Retrieve the log of the service execution. .. versionadded:: 1.13 :param target_dir: (optional) directory path name where the store the log.txt to. :type target_dir: basestring or None :param log_filename: (optional) log filename to write the log to, defaults to `log.txt`. :typ...
def get_log(self, target_dir=None, log_filename='log.txt'): """ Retrieve the log of the service execution. .. versionadded:: 1.13 :param target_dir: (optional) directory path name where the store the log.txt to. :type target_dir: basestring or None :param log_filename: ...
Get the url of the notebook, if the notebook is executed in interactive mode. .. versionadded:: 1.13 :return: full url to the interactive running notebook as `basestring` :raises APIError: when the url cannot be retrieved.
def get_notebook_url(self): """ Get the url of the notebook, if the notebook is executed in interactive mode. .. versionadded:: 1.13 :return: full url to the interactive running notebook as `basestring` :raises APIError: when the url cannot be retrieved. """ url...
Plotting function intended for an easy representation of OpenSignals acquired data. ---------- Parameters ---------- time : list or list of lists List that contains the time axis samples or a list of lists, when it is intended to present data in a gridplot format. When the input is a li...
def _plot_future(time, data, legend=None, title=None, y_axis_label=None, hor_lines=None, hor_lines_leg=None, vert_lines=None, vert_lines_leg=None, apply_opensignals_style=True, show_plot=True, warn_print=False, **kwargs): """ Plotting function intended for an easy representation ...
----- Brief ----- Plotting function intended for an easy representation of OpenSignals acquired data. ----------- Description ----------- This function allows to plot data acquired with resource to OpenSignals, available at https://bitalino.com/en/software, in an easy way using the Boke...
def plot(*args, legend=None, title=None, x_axis_label="Time (s)", y_axis_label=None, grid_plot=False, grid_lines=None, grid_columns=None, hor_lines=None, hor_lines_leg=None, vert_lines=None, vert_lines_leg=None, apply_opensignals_style=True, show_plot=True, warn_print=False, get_fig_list=Fals...
----- Brief ----- Function used to automatically apply the OpenSignals graphical style to Bokeh plots. ----------- Description ----------- OpenSignals has its own graphical style and Bokeh plots function in an object oriented way. This function allows to apply the Opensignals graphical...
def opensignals_style(figure_list, grid_plot=None, toolbar="right"): """ ----- Brief ----- Function used to automatically apply the OpenSignals graphical style to Bokeh plots. ----------- Description ----------- OpenSignals has its own graphical style and Bokeh plots function in an ...
----- Brief ----- Function used to automatically apply the OpenSignals graphical style to the toolbar of Bokeh grid plots. ----------- Description ----------- Bokeh grid plots have numerous options in order to personalise the visual aspect and functionalities of plots. OpenSignals uses ...
def opensignals_kwargs(obj): """ ----- Brief ----- Function used to automatically apply the OpenSignals graphical style to the toolbar of Bokeh grid plots. ----------- Description ----------- Bokeh grid plots have numerous options in order to personalise the visual aspect and functi...
Function that verifies when an input ('input_arg') of function 'plot' has a valid structure. ---------- Parameters ---------- data : list or list of lists Structure with the data that will be plotted. input_arg : list or list of lists The input data to be verified. input_name ...
def _check_validity_of_inputs(data, input_arg, input_name, grid_plot, dimension): """ Function that verifies when an input ('input_arg') of function 'plot' has a valid structure. ---------- Parameters ---------- data : list or list of lists Structure with the data that will be plotted. ...
Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the frame is sent as Text. If the data is a bytearray objec...
def sendFragmentStart(self, data): """ Send the start of a data fragment stream to a websocket client. Subsequent data should be sent using sendFragment(). A fragment stream is completed when sendFragmentEnd() is called. If data is a unicode object then the frame is ...
Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary.
def sendMessage(self, data): """ Send websocket data frame to the client. If data is a unicode object then the frame is sent as Text. If the data is a bytearray object then the frame is sent as Binary. """ opcode = BINARY if isinstance(data, unicode): ...
----- Brief ----- This function synchronises the input signals using the full cross correlation function between the signals. ----------- Description ----------- Signals acquired with two devices may be dephased. It is possible to synchronise the two signals by multiple methods. Here, i...
def synchronise_signals(in_signal_1, in_signal_2): """ ----- Brief ----- This function synchronises the input signals using the full cross correlation function between the signals. ----------- Description ----------- Signals acquired with two devices may be dephased. It is possible ...
----- Brief ----- This function allows to generate a text file with synchronised signals from the input file(s). ----------- Description ----------- OpenSignals files follow a specific structure that allows to analyse all files in the same way. Furthermore, it allows those files to be o...
def generate_sync_txt_file(in_path, channels=("CH1", "CH1"), new_path='sync_file.txt'): """ ----- Brief ----- This function allows to generate a text file with synchronised signals from the input file(s). ----------- Description ----------- OpenSignals files follow a specific struct...
----- Brief ----- This function allows to generate a h5 file with synchronised signals from the input file(s). ----------- Description ----------- OpenSignals files follow a specific structure that allows to analyse all files in the same way. Furthermore, it allows those files to be ope...
def generate_sync_h5_file(in_paths, channels=('channel_1', 'channel_1'), new_path='sync_file.h5'): """ ----- Brief ----- This function allows to generate a h5 file with synchronised signals from the input file(s). ----------- Description ----------- OpenSignals files follow a specif...
----- Brief ----- This function creates .txt and .h5 files with synchronised signals. ----------- Description ----------- OpenSignals software generates 3 types of files structured in specific ways. The formats are .txt, .h5 and .edf. Those files follow specific structures in order to n...
def create_synchronised_files(in_path=(('file1.txt', 'file2.txt'), ('file1.h5', 'file2.h5')), channels=(1, 1), file_name='sync_file'): """ ----- Brief ----- This function creates .txt and .h5 files with synchronised signals. ----------- Description ----------- ...
Function that equalises the input arrays by zero-padding the shortest one. ---------- Parameters ---------- array1: list or numpy.array Array array2: list or numpy.array Array Return ------ arrays: numpy.array Array containing the equal-length arrays.
def _shape_array(array1, array2): """ Function that equalises the input arrays by zero-padding the shortest one. ---------- Parameters ---------- array1: list or numpy.array Array array2: list or numpy.array Array Return ------ arrays: numpy.array Array ...
Function to create a new .h5 file that contains the copy of the contents of the input file(s). in_paths : str or list If the input is a string, it is assumed that the two signals are in the same file, else, if the input is a list, it is assumed that the two signals are in different file (the list s...
def _create_h5_file_old(in_paths, new_path): """ Function to create a new .h5 file that contains the copy of the contents of the input file(s). in_paths : str or list If the input is a string, it is assumed that the two signals are in the same file, else, if the input is a list, it is assum...
Function to create a new .h5 file that contains the copy of the contents of the input file(s). in_paths : str or list If the input is a string, it is assumed that the two signals are in the same file, else, if the input is a list, it is assumed that the two signals are in different file (the list s...
def _create_h5_file(in_paths, new_path): """ Function to create a new .h5 file that contains the copy of the contents of the input file(s). in_paths : str or list If the input is a string, it is assumed that the two signals are in the same file, else, if the input is a list, it is assumed t...
This function allows to generate a text file with synchronised signals from the input file. ---------- Parameters ---------- in_path : str Path to the file containing the two signals that will be synchronised. channels : list List with the strings identifying the channels of each si...
def _create_txt_from_str(in_path, channels, new_path): """ This function allows to generate a text file with synchronised signals from the input file. ---------- Parameters ---------- in_path : str Path to the file containing the two signals that will be synchronised. channels : lis...
Renders a string from a path template using the provided bindings. Args: bindings (dict): A dictionary of var names to binding strings. Returns: str: The rendered instantiation of this path template. Raises: ValidationError: If a key isn't provided or if a ...
def render(self, bindings): """Renders a string from a path template using the provided bindings. Args: bindings (dict): A dictionary of var names to binding strings. Returns: str: The rendered instantiation of this path template. Raises: Validation...
Matches a fully qualified path template string. Args: path (str): A fully qualified path template string. Returns: dict: Var names to matched binding values. Raises: ValidationException: If path can't be matched to the template.
def match(self, path): """Matches a fully qualified path template string. Args: path (str): A fully qualified path template string. Returns: dict: Var names to matched binding values. Raises: ValidationException: If path can't be matched to the temp...
Returns a list of path template segments parsed from data. Args: data: A path template string. Returns: A list of _Segment.
def parse(self, data): """Returns a list of path template segments parsed from data. Args: data: A path template string. Returns: A list of _Segment. """ self.binding_var_count = 0 self.segment_count = 0 segments = self.parser.parse(data)...
bound_segments : bound_segment FORWARD_SLASH bound_segments | bound_segment
def p_bound_segments(self, p): """bound_segments : bound_segment FORWARD_SLASH bound_segments | bound_segment""" p[0] = p[1] if len(p) > 2: p[0].extend(p[3])
unbound_segments : unbound_terminal FORWARD_SLASH unbound_segments | unbound_terminal
def p_unbound_segments(self, p): """unbound_segments : unbound_terminal FORWARD_SLASH unbound_segments | unbound_terminal""" p[0] = p[1] if len(p) > 2: p[0].extend(p[3])
bound_terminal : unbound_terminal
def p_bound_terminal(self, p): """bound_terminal : unbound_terminal""" if p[1][0].literal in ['*', '**']: p[0] = [_Segment(_BINDING, '$%d' % self.binding_var_count), p[1][0], _Segment(_END_BINDING, '')] self.binding_var_count += 1 e...
variable : LEFT_BRACE LITERAL EQUALS unbound_segments RIGHT_BRACE | LEFT_BRACE LITERAL RIGHT_BRACE
def p_variable(self, p): """variable : LEFT_BRACE LITERAL EQUALS unbound_segments RIGHT_BRACE | LEFT_BRACE LITERAL RIGHT_BRACE""" p[0] = [_Segment(_BINDING, p[2])] if len(p) > 4: p[0].extend(p[4]) else: p[0].append(_Segment(_TERMINAL, '*')) ...
:return: None
def populate(self, priority, address, rtr, data): """ :return: None """ self.needs_low_priority(priority) self.needs_rtr(rtr) self.needs_no_data(data) self.set_attributes(priority, address, rtr)
Create a notification object. Args: window (:py:class:`BrowserWindow`): Window object this region appears in. root (:py:class:`~selenium.webdriver.remote.webelement.WebElement`): WebDriver element object that serves as the root for the ...
def create(window, root): """Create a notification object. Args: window (:py:class:`BrowserWindow`): Window object this region appears in. root (:py:class:`~selenium.webdriver.remote.webelement.WebElement`): WebDriver element objec...
Provide access to the notification label. Returns: str: The notification label
def label(self): """Provide access to the notification label. Returns: str: The notification label """ with self.selenium.context(self.selenium.CONTEXT_CHROME): return self.root.get_attribute("label")
Provide access to the notification origin. Returns: str: The notification origin.
def origin(self): """Provide access to the notification origin. Returns: str: The notification origin. """ with self.selenium.context(self.selenium.CONTEXT_CHROME): return self.root.get_attribute("origin")
Retrieve the primary button.
def find_primary_button(self): """Retrieve the primary button.""" if self.window.firefox_version >= 67: return self.root.find_element( By.CLASS_NAME, "popup-notification-primary-button") return self.root.find_anonymous_element_by_attribute( "anonid", "butt...
Close the notification.
def close(self): """Close the notification.""" with self.selenium.context(self.selenium.CONTEXT_CHROME): self.find_close_button().click() self.window.wait_for_notification(None)
Imports :func: from a python file at :path: and executes it with *args, **kwargs arguments. Everytime this function is called the module is reloaded so that you can alter your debug code while the application is running. The result of the function is returned, otherwise the exception is returned (if one is rai...
def inject_path(path): """ Imports :func: from a python file at :path: and executes it with *args, **kwargs arguments. Everytime this function is called the module is reloaded so that you can alter your debug code while the application is running. The result of the function is returned, otherwise the e...
Imports a function from a python module :module: and executes it with *args, **kwargs arguments. Dotted referencing can be used to specify the function from the module. For example, the following code will execute func1 and func2 from module mymodule with no arguments inject_module('mymodule.func1') ...
def inject_module(module, *args, **kwargs): """ Imports a function from a python module :module: and executes it with *args, **kwargs arguments. Dotted referencing can be used to specify the function from the module. For example, the following code will execute func1 and func2 from module mymodule with...
Setup default config. for dictConfig. :param log_level: str name or django debugging int :return: dict suitable for ``logging.config.dictConfig``
def log_config(log_level: Union[str, int]) -> dict: """ Setup default config. for dictConfig. :param log_level: str name or django debugging int :return: dict suitable for ``logging.config.dictConfig`` """ if isinstance(log_level, int): # to match django log_level = {3: 'DEBUG', ...
Check the user authentication.
def authenticate(self): """Check the user authentication.""" endpoint = os.path.join(self.config.get('napps', 'api'), 'auth', '') username = self.config.get('auth', 'user') password = getpass("Enter the password for {}: ".format(username)) response = requests.get(endpoint, auth=(...
:return: None
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_low_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 7) self.set_attributes(priority, address, rtr) self.channel = self...
:return: str
def to_json(self): """ :return: str """ json_dict = self.to_json_basic() json_dict['channel'] = self.channel json_dict['disable_inhibit_forced'] = self.disable_inhibit_forced json_dict['status'] = self.status json_dict['led_status'] = self.led_status ...
:return: bytes
def data_to_binary(self): """ :return: bytes """ return bytes([ COMMAND_CODE, self.channels_to_byte([self.channel]), self.disable_inhibit_forced, self.status, self.led_status ]) + struct.pack('>L', self.delay_time)[-3:]
Upload a report to the server. :param payload: Dictionary (JSON serializable) of crash data. :return: server response
def upload_report(server, payload, timeout=HQ_DEFAULT_TIMEOUT): """ Upload a report to the server. :param payload: Dictionary (JSON serializable) of crash data. :return: server response """ try: data = json.dumps(payload) r = requests.post(server + '/reports/upload', data=data, t...
Delete a specific crash report from the server. :param report_number: Report Number :return: server response
def delete_report(server, report_number, timeout=HQ_DEFAULT_TIMEOUT): """ Delete a specific crash report from the server. :param report_number: Report Number :return: server response """ try: r = requests.post(server + "/reports/delete/%d" % report_number, timeout=timeout) except Exc...
Return a list of all open windows. Returns: list: List of FoxPuppet BrowserWindow objects.
def windows(self): """Return a list of all open windows. Returns: list: List of FoxPuppet BrowserWindow objects. """ from foxpuppet.windows import BrowserWindow return [ BrowserWindow(self.selenium, handle) for handle in self.selenium.window...
Close the socket.
def stop(self): """Close the socket.""" self.logger.warning("Stop executed") try: self._socket.close() except Exception: self.logger.error("Error while closing socket") raise VelbusException("Error while closing socket") time.sleep(1)
Read thread.
def read_daemon(self): """Read thread.""" while True: data = self._socket.recv(9999) self.feed_parser(data)
Parse multiple effects from an effects(list) json.
def _parse_effects(self, effects_json=None): # type: (dict) -> Any """Parse multiple effects from an effects(list) json.""" if isinstance(effects_json, list): return [ValidatorEffect.parse(effect) for effect in effects_json] elif isinstance(effects_json, dict): re...
Parse a json dict and return the correct subclass of :class:`PropertyValidator`. It uses the 'effect' key to determine which :class:`PropertyValidator` to instantiate. Please refer to :class:`pykechain.enums.PropertyVTypes` for the supported effects. :param json: dictionary containing the spec...
def parse(cls, json): # type: (Dict) -> Any """Parse a json dict and return the correct subclass of :class:`PropertyValidator`. It uses the 'effect' key to determine which :class:`PropertyValidator` to instantiate. Please refer to :class:`pykechain.enums.PropertyVTypes` for the supporte...
JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict
def as_json(self): # type: () -> dict """JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict """ new_json = dict( vtype=self.vtype, config=self._config ) if self.on_val...
Parse a json dict and return the correct subclass of :class:`ValidatorEffect`. It uses the 'effect' key to determine which :class:`ValidatorEffect` to instantiate. Please refer to :class:`enums.ValidatorEffectTypes` for the supported effects. :param json: dictionary containing the specific key...
def parse(cls, json): # type: (dict) -> Any """Parse a json dict and return the correct subclass of :class:`ValidatorEffect`. It uses the 'effect' key to determine which :class:`ValidatorEffect` to instantiate. Please refer to :class:`enums.ValidatorEffectTypes` for the supported effect...
JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict
def as_json(self): # type: () -> dict """JSON representation of the effect. :returns: a python dictionary, serializable as json of the effect :rtype: dict """ self._json = dict( effect=self.effect, config=self._config ) return self...
:return: bytes
def data_to_binary(self): """ :return: bytes """ return bytes([ COMMAND_CODE, int(self.temp_type), int(self.temp) ])
:return: None
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_firmware_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 6) self.set_attributes(priority, address, rtr) self.module_ty...
:return: bytes
def data_to_binary(self): """ :return: bytes """ return chr(COMMAND_CODE) + chr(self.module_type) + \ struct.pack('>L', self.current_serial)[2:] + \ chr(self.module_address) + \ struct.pack('>L', self.new_serial)[2:]
Query the darwin webservice to obtain a board for a particular station and return a StationBoard instance Positional arguments: crs -- the three letter CRS code of a UK station Keyword arguments: rows -- the number of rows to retrieve (default 10) include_departures -- ...
def get_station_board( self, crs, rows=17, include_departures=True, include_arrivals=False, destination_crs=None, origin_crs=None ): """ Query the darwin webservice to obtain a board for a particular station and return a StationBoard in...
Get the details of an individual service and return a ServiceDetails instance. Positional arguments: service_id: A Darwin LDB service id
def get_service_details(self, service_id): """ Get the details of an individual service and return a ServiceDetails instance. Positional arguments: service_id: A Darwin LDB service id """ service_query = \ self._soap_client.service['LDBServiceSoap']['...
A list of CallingPoint objects. This is the list of all previous calling points for the service, including all associated services if multiple services join together to form this service.
def previous_calling_points(self): """ A list of CallingPoint objects. This is the list of all previous calling points for the service, including all associated services if multiple services join together to form this service. """ calling_points = list() ...
A list of CallingPoint objects. This is the list of all subsequent calling points for the service, including all associated services if the service splits into multiple services.
def subsequent_calling_points(self): """ A list of CallingPoint objects. This is the list of all subsequent calling points for the service, including all associated services if the service splits into multiple services. """ calling_points = list() for cpl...
Ignore channel
def get_state(self, channel): """ Ignore channel """ val = None if channel not in self._unit: return val if self._unit[channel] == 'l/h': val = ((1000 * 3600) / (self._delay[channel] * self._pulses[channel])) elif self._unit[channel] == 'm3...
Return URL rule, HTTP methods and docstring.
def _parse_decorated_functions(self, code): """Return URL rule, HTTP methods and docstring.""" matches = re.finditer(r""" # @rest decorators (?P<decorators> (?:@rest\(.+?\)\n)+ # one or more @rest decorators inside ) # ...
Render and save API doc in openapi.yml.
def render_template(self): """Render and save API doc in openapi.yml.""" self._parse_paths() context = dict(napp=self._napp.__dict__, paths=self._paths) self._save(context)
Parse the method docstring.
def _parse_docstring(self, docstring): """Parse the method docstring.""" match = re.match(r""" # Following PEP 257 \s* (?P<summary>[^\n]+?) \s* # First line ( # Description and YAML are optional (\n \s*){2} ...
Return HTTP method list. Use json for security reasons.
def _parse_methods(cls, list_string): """Return HTTP method list. Use json for security reasons.""" if list_string is None: return APIServer.DEFAULT_METHODS # json requires double quotes json_list = list_string.replace("'", '"') return json.loads(json_list)
Convert relative Flask rule to absolute OpenAPI path.
def _rule2path(cls, rule): """Convert relative Flask rule to absolute OpenAPI path.""" typeless = re.sub(r'<\w+?:', '<', rule) # remove Flask types return typeless.replace('<', '{').replace('>', '}')
:return: bool
def on_app_engine(): """ :return: bool """ if 'SERVER_SOFTWARE' in os.environ: server_software = os.environ['SERVER_SOFTWARE'] if server_software.startswith('Google App Engine') or \ server_software.startswith('Development'): return True return False ...
:return: None
def register_module(module_name, module_class): """ :return: None """ assert isinstance(module_name, str) assert isinstance(module_class, type) if module_name not in ModuleRegistry: ModuleRegistry[module_name] = module_class else: raise Exception("double registration in modul...
:return: int
def checksum(data): """ :return: int """ assert isinstance(data, bytes) assert len(data) >= MINIMUM_MESSAGE_SIZE - 2 assert len(data) <= MAXIMUM_MESSAGE_SIZE - 2 __checksum = 0 for data_byte in data: __checksum += data_byte __checksum = -(__checksum % 256) + 256 try: ...
Retrieve the property belonging to this part based on its name or uuid. :param name: property name or property UUID to search for :type name: basestring :return: a single :class:`Property` :raises NotFoundError: if the `Property` is not part of the `Part` Example ------...
def property(self, name): """Retrieve the property belonging to this part based on its name or uuid. :param name: property name or property UUID to search for :type name: basestring :return: a single :class:`Property` :raises NotFoundError: if the `Property` is not part of the `...
Retrieve the parent of this `Part`. :return: the parent :class:`Part` of this part :raises APIError: if an Error occurs Example ------- >>> part = project.part('Frame') >>> bike = part.parent()
def parent(self): # type: () -> Any """Retrieve the parent of this `Part`. :return: the parent :class:`Part` of this part :raises APIError: if an Error occurs Example ------- >>> part = project.part('Frame') >>> bike = part.parent() """ ...
Retrieve the children of this `Part` as `Partset`. When you call the :func:`Part.children()` method without any additional filtering options for the children, the children are cached to help speed up subsequent calls to retrieve the children. The cached children are returned as a list and not a...
def children(self, **kwargs): """Retrieve the children of this `Part` as `Partset`. When you call the :func:`Part.children()` method without any additional filtering options for the children, the children are cached to help speed up subsequent calls to retrieve the children. The cached children...
Retrieve the siblings of this `Part` as `Partset`. Siblings are other Parts sharing the same parent of this `Part`, including the part itself. :param kwargs: Additional search arguments to search for, check :class:`pykechain.Client.parts` for additional info :type kwargs...
def siblings(self, **kwargs): # type: (Any) -> Any """Retrieve the siblings of this `Part` as `Partset`. Siblings are other Parts sharing the same parent of this `Part`, including the part itself. :param kwargs: Additional search arguments to search for, check :class:`pykechain.Client....
Retrieve the model of this `Part` as `Part`. For instance, you can get the part model of a part instance. But trying to get the model of a part that has no model, like a part model, will raise a :exc:`NotFoundError`. .. versionadded:: 1.8 :return: the model of this part instance as :c...
def model(self): """ Retrieve the model of this `Part` as `Part`. For instance, you can get the part model of a part instance. But trying to get the model of a part that has no model, like a part model, will raise a :exc:`NotFoundError`. .. versionadded:: 1.8 :return: ...
Retrieve the instances of this `Part` as a `PartSet`. For instance, if you have a model part, you can get the list of instances that are created based on this moodel. If there are no instances (only possible if the multiplicity is :attr:`enums.Multiplicity.ZERO_MANY`) than a :exc:`NotFoundError...
def instances(self, **kwargs): """ Retrieve the instances of this `Part` as a `PartSet`. For instance, if you have a model part, you can get the list of instances that are created based on this moodel. If there are no instances (only possible if the multiplicity is :attr:`enums.Multipli...
Retrieve the single (expected) instance of this 'Part' (of `Category.MODEL`) as a 'Part'. See :func:`Part.instances()` method for documentation. :return: :class:`Part` with category `INSTANCE` :raises NotFoundError: if the instance does not exist :raises MultipleFoundError: if there ar...
def instance(self): """ Retrieve the single (expected) instance of this 'Part' (of `Category.MODEL`) as a 'Part'. See :func:`Part.instances()` method for documentation. :return: :class:`Part` with category `INSTANCE` :raises NotFoundError: if the instance does not exist ...
Retrieve the proxy model of this proxied `Part` as a `Part`. Allows you to retrieve the model of a proxy. But trying to get the catalog model of a part that has no proxy, will raise an :exc:`NotFoundError`. Only models can have a proxy. :return: :class:`Part` with category `MODEL` and from whi...
def proxy_model(self): """ Retrieve the proxy model of this proxied `Part` as a `Part`. Allows you to retrieve the model of a proxy. But trying to get the catalog model of a part that has no proxy, will raise an :exc:`NotFoundError`. Only models can have a proxy. :return: :clas...
Add a new child instance, based on a model, to this part. This can only act on instances. It needs a model from which to create the child instance. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method...
def add(self, model, **kwargs): # type: (Part, **Any) -> Part """Add a new child instance, based on a model, to this part. This can only act on instances. It needs a model from which to create the child instance. In order to prevent the backend from updating the frontend you may add `s...
Add a new instance of this model to a part. This works if the current part is a model and an instance of this model is to be added to a part instances in the tree. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value...
def add_to(self, parent, **kwargs): # type: (Part, **Any) -> Part """Add a new instance of this model to a part. This works if the current part is a model and an instance of this model is to be added to a part instances in the tree. In order to prevent the backend from updating...
Add a new child model to this model. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the frontend won't no...
def add_model(self, *args, **kwargs): # type: (*Any, **Any) -> Part """Add a new child model to this model. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance o...
Add this model as a proxy to another parent model. This will add the current model as a proxy model to another parent model. It ensure that it will copy the whole subassembly to the 'parent' model. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` a...
def add_proxy_to(self, parent, name, multiplicity=Multiplicity.ONE_MANY, **kwargs): # type: (Any, AnyStr, Any, **Any) -> Part """Add this model as a proxy to another parent model. This will add the current model as a proxy model to another parent model. It ensure that it will copy the w...
Add a new property to this model. See :class:`pykechain.Client.create_property` for available parameters. :return: :class:`Property` :raises APIError: in case an Error occurs
def add_property(self, *args, **kwargs): # type: (*Any, **Any) -> Property """Add a new property to this model. See :class:`pykechain.Client.create_property` for available parameters. :return: :class:`Property` :raises APIError: in case an Error occurs """ if se...
Edit the details of a part (model or instance). For an instance you can edit the Part instance name and the part instance description. To alter the values of properties use :func:`Part.update()`. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as ...
def edit(self, name=None, description=None, **kwargs): # type: (AnyStr, AnyStr, **Any) -> None """ Edit the details of a part (model or instance). For an instance you can edit the Part instance name and the part instance description. To alter the values of properties use :func:`...
Edit part name and property values in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the frontend...
def update(self, name=None, update_dict=None, bulk=True, **kwargs): """ Edit part name and property values in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve per...
Add a part and update its properties in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve performance of the backend against a trade-off that someone looking at the fronte...
def add_with_properties(self, model, name=None, update_dict=None, bulk=True, **kwargs): """ Add a part and update its properties in one go. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method....
Order the properties of a part model using a list of property objects or property names or property id's. :param property_list: ordered list of property names (basestring) or property id's (uuid) :type property_list: list(basestring) :returns: the :class:`Part` with the reordered list of proper...
def order_properties(self, property_list=None): """ Order the properties of a part model using a list of property objects or property names or property id's. :param property_list: ordered list of property names (basestring) or property id's (uuid) :type property_list: list(basestring) ...
Retrieve the descendants of a specific part in a list of dicts and populate the :func:`Part.children()` method. Each `Part` has a :func:`Part.children()` method to retrieve the children on the go. This function prepopulates the children and the children's children with its children in one call, making ...
def populate_descendants(self, batch=200): """ Retrieve the descendants of a specific part in a list of dicts and populate the :func:`Part.children()` method. Each `Part` has a :func:`Part.children()` method to retrieve the children on the go. This function prepopulates the children and...