text
stringlengths
81
112k
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set() def valuefrompostdata(self, postdata): """This parameter method searches the POST data and retrieves the values it needs....
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set() def valuefrompostdata(self, postdata): """This parameter method searches the POST data and retrieves the values it needs....
This parameter method attempts to set a specific value for this parameter. The value will be validated first, and if it can not be set. An error message will be set in the error property of this parameter def set(self, value): """This parameter method attempts to set a specific value for this parameter. The va...
This parameter method searches the POST data and retrieves the values it needs. It does not set the value yet though, but simply returns it. Needs to be explicitly passed to parameter.set() def valuefrompostdata(self, postdata): """This parameter method searches the POST data and retrieves the values it needs....
Get list of projects or shortcut to other functionality def index(credentials = None): """Get list of projects or shortcut to other functionality""" #handle shortcut shortcutresponse = entryshortcut(credentials) if shortcutresponse is not None: return shortcutresponse projects = [] us...
Add a new input file, this invokes the actual uploader def addfile(project, filename, user, postdata, inputsource=None,returntype='xml'): #pylint: disable=too-many-return-statements """Add a new input file, this invokes the actual uploader""" def errorresponse(msg, code=403): if returntype == 'json':...
The Uploader is intended for the Fine Uploader used in the web application (or similar frontend), it is not intended for proper RESTful communication. Will return JSON compatible with Fine Uploader rather than CLAM Upload XML. Unfortunately, normal digest authentication does not work well with the uploader, so we imple...
Run CLAM in WSGI mode def run_wsgi(settings_module): """Run CLAM in WSGI mode""" global settingsmodule, DEBUG #pylint: disable=global-statement printdebug("Initialising WSGI service") globals()['settings'] = settings_module settingsmodule = settings_module.__name__ try: if settings.DE...
Get list of projects def index(credentials=None): """Get list of projects""" user, oauth_access_token = parsecredentials(credentials) if not settings.ADMINS or user not in settings.ADMINS: return flask.make_response('You shall not pass!!! You are not an administrator!',403) ...
Get the path to the project (static method) def path(project, credentials): """Get the path to the project (static method)""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable return settings.ROOT + "projects/" + user + '/' + project + "/"
Create project skeleton if it does not already exist (static method) def create(project, credentials): #pylint: disable=too-many-return-statements """Create project skeleton if it does not already exist (static method)""" if not settings.COMMAND: return flask.make_response("Projects disabl...
Check if the project exists def exists(project, credentials): """Check if the project exists""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable printdebug("Checking if project " + project + " exists for " + user) return os.path.isdir(Project.pat...
Retrieve sorted index for the specified input template def inputindexbytemplate(project, user, inputtemplate): """Retrieve sorted index for the specified input template""" index = [] #pylint: disable=redefined-outer-name prefix = Project.path(project, user) + 'input/' for linkf, f in gl...
Retrieve sorted index for the specified input template def outputindexbytemplate(project, user, outputtemplate): """Retrieve sorted index for the specified input template""" index = [] #pylint: disable=redefined-outer-name prefix = Project.path(project, user) + 'output/' for linkf, f in...
Main Get method: Get project state, parameters, outputindex def get(project, credentials=None): """Main Get method: Get project state, parameters, outputindex""" user, oauth_access_token = parsecredentials(credentials) if not Project.exists(project, user): return withheaders(flask.m...
Create an empty project def new(project, credentials=None): """Create an empty project""" user, oauth_access_token = parsecredentials(credentials) response = Project.create(project, user) if response is not None: return response msg = "Project " + project + " has bee...
Start execution def start(project, credentials=None): #pylint: disable=too-many-return-statements """Start execution""" #handle shortcut shortcutresponse = entryshortcut(credentials, True) #protected against endless recursion, will return None when no shortcut is found, True when one is found ...
Delete an output file def deleteoutputfile(project, filename, credentials=None): """Delete an output file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable if filename: filename = filename.replace("..","") #Simple security if not filename or ...
Reset system, delete all output files and prepare for a new run def reset(project, user): """Reset system, delete all output files and prepare for a new run""" d = Project.path(project, user) + "output" if os.path.isdir(d): shutil.rmtree(d) os.makedirs(d) else: ...
Generates and returns a download package (or 403 if one is already in the process of being prepared) def getarchive(project, user, format=None): """Generates and returns a download package (or 403 if one is already in the process of being prepared)""" if os.path.isfile(Project.path(project, user) + '.d...
Delete an input file def deleteinputfile(project, filename, credentials=None): """Delete an input file""" user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable filename = filename.replace("..","") #Simple security if len(filename) == 0: ...
Add a new input file, this invokes the actual uploader def addinputfile(project, filename, credentials=None): #pylint: disable=too-many-return-statements """Add a new input file, this invokes the actual uploader""" printdebug('Addinputfile: Initialising' ) user, oauth_access_token = parsecred...
Get list of pre-installed corpora def corpusindex(): """Get list of pre-installed corpora""" corpora = [] for f in glob.glob(settings.ROOT + "corpora/*"): if os.path.isdir(f): corpora.append(os.path.basename(f)) return corpora
Does the nonce exist and is it valid for the request? def validate(self, nonce): """Does the nonce exist and is it valid for the request?""" if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr) try: opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-var...
Delete expired nonces def cleanup(self): """Delete expired nonces""" t = time.time() for noncefile in glob(self.path + '/*.nonce'): if os.path.getmtime(noncefile) + self.expiration > t: os.unlink(noncefile)
Retrun JSON representation for this run def json(self): """Retrun JSON representation for this run""" return { "id": self.ID, "steps": self.steps, "graph_source": self.source, "errored": self.errored }
Creates a new RunData object and increments pointers def new_run(self): """Creates a new RunData object and increments pointers""" self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
Reads a logfile continuously and updates internal graph if new step is found def follow_log(self): """Reads a logfile continuously and updates internal graph if new step is found""" # Server needs to be up and running before starting sending POST requests time.sleep(5) try: ...
Updates frontend with info from the log :param info: dict - Information from a line in the log. i.e regular line, new step. def update_frontend(self, info): """Updates frontend with info from the log :param info: dict - Information from a line in the log. i.e regular line, new step. "...
Returns some summary data for a finished analysis def get_summary(self): """Returns some summary data for a finished analysis""" if not self.analysis_finished: return [] summary = {'times_summary': []} for i in range(len(self.runs[self.current_run].steps) - 1): s...
Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format. def _grabContentFromUrl(self, url): """ Function that abstracts capturing a URL. This method rewr...
Handles all commands that take a filename and 0 or more extra arguments. Passes the command to backend. (Debugger plugin may also use this method) def _handle_rundebug_from_shell(cmd_line): """ Handles all commands that take a filename and 0 or more extra arguments. Passes the command to backend. ...
upload current python script to EV3 def upload_current_script(): """upload current python script to EV3""" current_editor = get_workbench().get_editor_notebook().get_current_editor() code = current_editor.get_text_widget().get("1.0", "end") try: filename= current_editor.get_filename() i...
upload current python script to EV3 def start_current_script(): """upload current python script to EV3""" current_editor = get_workbench().get_editor_notebook().get_current_editor() code = current_editor.get_text_widget().get("1.0", "end") try: ast.parse(code) #Return None, if script is...
downloads log of given .py file from EV3. def download_log(currentfile=None): """downloads log of given .py file from EV3.""" if currentfile == None: return # add ".err.log" if file doesn't end with it! if not currentfile.endswith(".err.log"): currentfile=currentfile + ".err.log" ...
download log of current python script from EV3 def download_log_of_current_script(): """download log of current python script from EV3""" try: #Return None, if script is not saved and user closed file saving window, otherwise return file name. src_file = get_workbench().get_current_editor().ge...
cleanup files in homedir on EV3. def cleanup_files_on_ev3(): """cleanup files in homedir on EV3.""" list = get_base_ev3dev_cmd() + ['cleanup'] env = os.environ.copy() env["PYTHONUSERBASE"] = THONNY_USER_BASE proc = subprocess.Popen(list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ...
Adds EV3 buttons on toolbar and commands under Run and Tools menu. Add EV3 configuration window. def load_plugin(): """Adds EV3 buttons on toolbar and commands under Run and Tools menu. Add EV3 configuration window.""" # Add EV3 configuration window workbench=get_workbench() workbench.set_default("ev3...
Initialize ubersmith API module with HTTP request handler. def init(base_url, username=None, password=None, verify=True): """Initialize ubersmith API module with HTTP request handler.""" handler = RequestHandler(base_url, username, password, verify) set_default_request_handler(handler) return handler
Auxiliar function to get the configuration path depending on the system. def getConfigPath(configFileName = None): """ Auxiliar function to get the configuration path depending on the system. """ if configFileName != None: # Returning the path of the configuration file if sys.platfo...
Reading the configuration file to look for where the different gates are running. :return: A json containing the information stored in the .cfg file. def getConfiguration(configPath = None): """ Reading the configuration file to look for where the different gates are running. ...
Create new logger and log file from existing logger. The new logger will be create in the same directory as the existing logger file and will be named as the existing log file with the requested suffix. :param logger: existing logger :param suffix: string to add to the existing log file name to create...
Process request over HTTP to ubersmith instance. method: Ubersmith API method string data: dict of method arguments def process_request(self, method, data=None): """Process request over HTTP to ubersmith instance. method: Ubersmith API method string data: dict ...
URL encode data. def _encode_data(data): """URL encode data.""" data = data if data is not None else {} data = to_nested_php_args(data) files = dict([ (key, value) for key, value in data.items() if isinstance(value, file_type)]) for fname in files: ...
Returns nested string representation of the dictionary (like json.dumps). :param indent: indentation level. def dumps(self, indent=1): """ Returns nested string representation of the dictionary (like json.dumps). :param indent: indentation level. """ str_keys_dict = OrderedDi...
:param types: list of requested types. :return: the first (and in most useful cases only) child of specific type(s). def get_child(self, *types): """ :param types: list of requested types. :return: the first (and in most useful cases only) child of specific type(s). """ ...
Returned objects stored in memory (without re-reading them from the TGN). Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. def get_objects_by_type(self, *types): """ Returne...
:param types: requested object types. :return: the child of the specified types. def get_object_by_type(self, *types): """ :param types: requested object types. :return: the child of the specified types. """ children = self.get_objects_by_type(*types) return chil...
:param types: requested object types. :return: all children of the specified types. def get_objects_by_type_in_subtree(self, *types): """ :param types: requested object types. :return: all children of the specified types. """ typed_objects = self.get_objects_by_type(*ty...
Get objects if children already been read or get children. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. def get_objects_or_children_by_type(self, *types): """ Get object...
Get object if child already been read or get child. Use this method for fast access to objects in case of static configurations. :param types: requested object types. :return: all children of the specified types. def get_object_or_child_by_type(self, *types): """ Get object if child a...
:param obj_type: requested object type. :param child_type: requested child types. :return: all children of the requested type that have the requested child types. def get_objects_with_object(self, obj_type, *child_types): """ :param obj_type: requested object type. :param child_...
:param obj_type: requested object type. :param child_type: unrequested child types. :return: all children of the requested type that do not have the unrequested child types. def get_objects_without_object(self, obj_type, *child_types): """ :param obj_type: requested object type. ...
:param obj_type: requested object type. :param attribute: requested attribute. :param value: requested attribute value. :return: all children of the requested type that have the requested attribute == requested value. def get_objects_with_attribute(self, obj_type, attribute, value): """...
:param obj_type: requested ancestor type. :return: the ancestor of the object who's type is obj_type if exists else None. def get_ancestor_object_by_type(self, obj_type): """ :param obj_type: requested ancestor type. :return: the ancestor of the object who's type is obj_type if exists e...
Delete object from parent object. def del_object_from_parent(self): """ Delete object from parent object. """ if self.parent: self.parent.objects.pop(self.ref)
:return: all instances of the requested class. def get_objects_of_class(cls): """ :return: all instances of the requested class. """ return list(o for o in gc.get_objects() if isinstance(o, cls))
Closes (terminates) all of its clients. Though keeps server running. def _handle_sighup(myrpcserver, signum, unused): """Closes (terminates) all of its clients. Though keeps server running.""" print("SIGHUP: stopping all clients",sys.stderr) if myrpcserver._closed: return for c in set(myrpcserv...
Split a string with arbitrary number of separators. Return a list with the splitted values Arguments: string (str): ex. "a:1|2,b:2" separators (list): ex. [',',':','|'] Returns: results (list) : ex. ['a','1','2','b','2'] def split_strings(string, separators): """ ...
Convert VCD id in int to string def _idToStr(self, x): """ Convert VCD id in int to string """ if x < 0: sign = -1 elif x == 0: return self._idChars[0] else: sign = 1 x *= sign digits = [] while x: d...
Add variable to scope :ivar sig: user specified object to keep track of VcdVarInfo in change() :ivar sigType: vcd type name :ivar valueFormatter: value which converts new value in change() to vcd string def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int, ...
Create sub variable scope with defined name def varScope(self, name): """ Create sub variable scope with defined name """ ch = VcdVarWritingScope(name, self._writer, parent=self) assert name not in self.children, name self.children[name] = ch return ch
Wrapper for being able to launch all the threads. :param params: We receive the parameters as a tuple. def multi_run_wrapper(params): ''' Wrapper for being able to launch all the threads. :param params: We receive the parameters as a tuple. ''' zeronet, index, total, output_folder, ...
Main function. def main(args): """ Main function. """ urls = [] # Grabbing all possible URL with open(args.file) as iF: urls = iF.read().splitlines() # Creating the output folder if it does not exist. if not os.path.exists(args.output_folder): os.makedirs(args....
Method that abstracts the extraction of grabbing the configuration. :return: the applicable configuration settings. def _getConfiguration(self): """ Method that abstracts the extraction of grabbing the configuration. :return: the applicable configur...
Extracting the domain from the URL. :return: domain as a string. def getDomainFromUrl(self, url): """ Extracting the domain from the URL. :return: domain as a string. """ try: domain = re.findall( self.domainRegexp, url )...
This method receives a response, including headers, and creates the appropriate structure. :param url: The URL to be recovered. :param content: The content of the response. :return: A json. def _createDataStructure(self, content): """ ...
Function that abstracts capturing a URL. This method will be rewritten in child classes. :param url: The URL to be processed. :return: The response in a Json format. def _grabContentFromUrl(self, url): """ Function that abstracts capturing a URL. This method...
Public method that wraps the extraction of the content. :param url: The resource to be processed. :return: The response in a Json format. def getResponse(self, url): """ Public method that wraps the extraction of the content. :param ...
Append query_string values to an existing URL and return it as a string. query_string can be: * an encoded string: 'test3=val1&test3=val2' * a dict of strings: {'test3': 'val'} * a dict of lists of strings: {'test3': ['val1', 'val2']} * a list of tuples: [('test3', 'val1'), ('test3'...
urllib.urlencode can't handle unicode, this is a hack to fix it. def urlencode_unicode(data, doseq=0): """urllib.urlencode can't handle unicode, this is a hack to fix it.""" data_iter = None if isdict(data): data_iter = list(data.items()) elif islist(data): data_iter = data if data...
This function will take either a dict or list and will recursively loop through the values converting it into a format similar to a PHP array which Ubersmith requires for the info portion of the API's order.create method. def to_nested_php_args(data, prefix_key=None): """ This function will take either...
Parse Content-Disposition header to pull out the filename bit. See: http://tools.ietf.org/html/rfc2616#section-19.5.1 def get_filename(disposition): """Parse Content-Disposition header to pull out the filename bit. See: http://tools.ietf.org/html/rfc2616#section-19.5.1 """ if disposition: ...
:param arguments: Python dictionary of TGN API command arguments <key, value>. :returns: Tcl list of argument pairs <-key, value> to be used in TGN API commands. def get_args_pairs(arguments): """ :param arguments: Python dictionary of TGN API command arguments <key, value>. :returns: Tcl list of argum...
Convert Tcl list to Python list using Tcl interpreter. :param tcl_list: string representing the Tcl string. :param within_tcl_str: True - Tcl list is embedded within Tcl str. False - native Tcl string. :return: Python list equivalent to the Tcl ist. :rtye: list def tcl_list_2_py_list(tcl_list, within_...
Convert Python list to Tcl list using Tcl interpreter. :param py_list: Python list. :type py_list: list :return: string representing the Tcl string equivalent to the Python list. def py_list_to_tcl_list(py_list): """ Convert Python list to Tcl list using Tcl interpreter. :param py_list: Python li...
@summary: Evaluate Tcl command. @param command: command to evaluate. @return: command output. def eval(self, command): """ @summary: Evaluate Tcl command. @param command: command to evaluate. @return: command output. """ # Some operations (like take own...
Execute Tcl command. Write the command to tcl script (.tcl) log file. Execute the command. Write the command and the output to general (.txt) log file. :param command: Command to execute. :returns: command raw output. def eval(self, command): """ Execute Tcl command. ...
Function that abstracts capturing a URL. This method rewrites the one from Wrapper. :param url: The URL to be processed. :return: The response in a Json format. def _grabContentFromUrl(self, url): """ Function that abstracts capturing a URL. This method rewr...
append change from VCD file signal data series def value_change(self, vcdId, value): '''append change from VCD file signal data series''' self.idcode2series[vcdId].append((self.now, value))
Tokenize and parse the VCD file :ivar file_handle: opened file with vcd string def parse(self, file_handle): ''' Tokenize and parse the VCD file :ivar file_handle: opened file with vcd string ''' # open the VCD file and create a token generator lineIterator = i...
Update a record in Archivist's Toolkit using the provided new_record. The format of new_record is identical to the format returned by get_resource_component_and_children and related methods. This means it's possible, for example, to request a record, modify the returned dict, and pass that dict to this...
Returns an array of all levels of description defined in this Archivist's Toolkit instance. def get_levels_of_description(self): """ Returns an array of all levels of description defined in this Archivist's Toolkit instance. """ if not hasattr(self, "levels_of_description"): ...
Fetches a list of all resource and component IDs within the specified resource. :param long resource_id: The ID of the resource to fetch children from. :param string resource_type: Specifies whether the resource to fetch is a collection or a child element. Defaults to 'collection'. ...
Fetch detailed metadata for the specified resource_id and all of its children. :param long resource_id: The resource for which to fetch metadata. :param string resource_type: The level of description of the record. :param int recurse_max_level: The maximum depth level to fetch when fetching chi...
Given the ID of a component, returns the parent resource ID. If the immediate parent of the component is itself a component, this method will progress up the tree until a resource is found. :param long component_id: The ID of the ResourceComponent. :return: The ID of the component's parent res...
Given the ID of a component, returns the parent component's ID. :param string component_id: The ID of the component. :return: A tuple containing: * The type of the parent record; valid values are ArchivesSpaceClient.RESOURCE and ArchivesSpaceClient.RESOURCE_COMPONENT. * The ID o...
Fetches a list of all resource IDs for every resource in the database. :param string search_pattern: A search pattern to use in looking up resources by title or resourceid. The search will match any title or resourceid containing this string; for example, "text" will match "this title h...
Evaluate the Gaussian model Parameters ---------- flux : tf.Variable xo, yo : tf.Variable, tf.Variable Center coordiantes of the Gaussian. a, b, c : tf.Variable, tf.Variable Parameters that control the rotation angle and the stretch along the ...
Parses a log line and returns it with more information :param line: str - A line from a bcbio-nextgen log :returns dict: A dictionary containing the line, if its a new step if its a Traceback or if the analysis is finished def parse_log_line(line): """Parses a log line and returns it wi...
Dictionary representation of the Event appropriate for JSON-encoding. def message(self): """Dictionary representation of the Event appropriate for JSON-encoding.""" return { 'timestamp': time.mktime(self.timestamp.timetuple())*1e3 + self.timestamp.microsecond/1e3, 'group': self....
Saving an Event automatically sets the timestamp if not already set. def save(self, *args, **kwargs): """Saving an Event automatically sets the timestamp if not already set.""" if self.timestamp is None: self.timestamp = timezone.now() super().save(*args, **kwargs)
Called from the WebSocket consumer. Checks if all players in the group have connected; runs :meth:`when_all_players_ready` once all connections are established. def _on_connect(self, participant): """Called from the WebSocket consumer. Checks if all players in the group have connected; ...
Trigger the :meth:`when_player_disconnects` callback. def _on_disconnect(self, participant): """Trigger the :meth:`when_player_disconnects` callback.""" player = None for p in self.get_players(): if p.participant == participant: player = p break ...
Send a message with the given payload on the given channel. Messages are broadcast to all players in the group. def send(self, channel, payload): """Send a message with the given payload on the given channel. Messages are broadcast to all players in the group. """ with track('se...
BUG: Django save-the-change, which all oTree models inherit from, doesn't recognize changes to JSONField properties. So saving the model won't trigger a database save. This is a hack, but fixes it so any JSONFields get updated every save. oTree uses a forked version of save-the-change so...
Initializes decisions based on ``player.initial_decision()``. If :attr:`num_subperiods` is set, starts a timed task to run the sub-periods. def when_all_players_ready(self): """Initializes decisions based on ``player.initial_decision()``. If :attr:`num_subperiods` is set, starts a timed...
Tick each sub-period, copying group_decisions to subperiod_group_decisions. def _subperiod_tick(self, current_interval, intervals): """Tick each sub-period, copying group_decisions to subperiod_group_decisions.""" self.refresh_from_db() for key, value in self.group_decisions.items(): ...
Called when an Event is received on the decisions channel. Saves the value in group_decisions. If num_subperiods is None, immediately broadcasts the event back out on the group_decisions channel. def _on_decisions_event(self, event=None, **kwargs): """Called when an Event is received on the dec...
Return a copy of given matrix where keys associated to space values are discarded def clean(matrix): """Return a copy of given matrix where keys associated to space values are discarded""" return defaultdict(lambda: ' ', { k: v for k, v in matrix.items() if v != ' ' })