code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
headers = {'User-agent': 'CLAMClientAPI-' + clam.common.data.VERSION}
if self.oauth:
if not self.oauth_access_token:
r = requests.get(self.url,headers=headers, verify=self.verify)
if r.status_code == 404:
raise clam.common.data.Not... | def initauth(self) | Initialise authentication, for internal use | 4.27424 | 4.241059 | 1.007824 |
requestparams = self.initrequest(data)
if method == 'POST':
request = requests.post
elif method == 'DELETE':
request = requests.delete
elif method == 'PUT':
request = requests.put
else:
request = requests.get
r ... | def request(self, url='', method = 'GET', data = None, parse=True, encoding=None) | Issue a HTTP request and parse CLAM XML response, this is a low-level function called by all of the higher-level communication methods in this class, use those instead | 2.446593 | 2.434362 | 1.005024 |
if content.find('<clam') != -1:
data = clam.common.data.CLAMData(content,self, loadmetadata=self.loadmetadata)
if data.errors:
error = data.parametererror()
if error:
raise clam.common.data.ParameterError(error)
ret... | def _parse(self, content) | Parses CLAM XML data and returns a ``CLAMData`` object. For internal use. Raises `ParameterError` exception on parameter errors. | 8.049386 | 5.240322 | 1.536048 |
try:
data = self.request(project + '/')
except:
raise
if not isinstance(data, clam.common.data.CLAMData):
raise Exception("Unable to retrieve CLAM Data")
else:
return data | def get(self, project) | Query the project status. Returns a ``CLAMData`` instance or raises an exception according to the returned HTTP Status code | 7.728671 | 6.158773 | 1.254904 |
if 'method' in kwargs:
method = kwargs['method']
del kwargs['method']
else:
method = 'GET'
if 'encoding' in kwargs:
encoding = kwargs['encoding']
del kwargs['encoding']
else:
encoding = 'utf-8'
ret... | def action(self, action_id, **kwargs) | Query an action, specify the parameters for the action as keyword parameters. An optional keyword parameter method='GET' (default) or method='POST' can be set. The character set encoding of the response can be configured using the encoding keyword parameter (defaults to utf-8 by default) | 2.618483 | 2.120163 | 1.235038 |
#auth = None
#if 'auth' in parameters:
# auth = parameters['auth']
# del parameters['auth']
for key in parameters:
if isinstance(parameters[key],list) or isinstance(parameters[key],tuple):
parameters[key] = ",".join(parameters[key])
... | def start(self, project, **parameters) | Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. Note that no exceptions are raised on parameter errors, you have to check for those manually! (Use startsafe instead if want Exceptions on pa... | 3.0999 | 3.192209 | 0.971083 |
try:
data = self.start(project, **parameters)
for parametergroup, paramlist in data.parameters: #pylint: disable=unused-variable
for parameter in paramlist:
if parameter.error:
raise clam.common.data.ParameterError(par... | def startsafe(self, project, **parameters) | Start a run. ``project`` is the ID of the project, and ``parameters`` are keyword arguments for
the global parameters. Returns a ``CLAMData`` object or raises exceptions. This version, unlike ``start()``, raises Exceptions (``ParameterError``) on parameter errors.
response = client.startsafe("mypro... | 6.718864 | 4.996149 | 1.344809 |
if isinstance(targetfile,str) or (sys.version < '3' and isinstance(targetfile,unicode)): #pylint: disable=undefined-variable
targetfile = open(targetfile,'wb')
r = requests.get(self.url + project + '/output/' + archiveformat,**self.initrequest())
CHUNK = 16 * 1024
fo... | def downloadarchive(self, project, targetfile, archiveformat = 'zip') | Download all output files as a single archive:
* *targetfile* - path for the new local file to be written
* *archiveformat* - the format of the archive, can be 'zip','gz','bz2'
Example::
client.downloadarchive("myproject","allresults.zip","zip") | 2.731459 | 3.01356 | 0.906389 |
if inputtemplate.filename:
filename = inputtemplate.filename
elif inputtemplate.extension:
if filename.lower()[-4:] == '.zip' or filename.lower()[-7:] == '.tar.gz' or filename.lower()[-8:] == '.tar.bz2':
#pass archives as-is
return filenam... | def getinputfilename(self, inputtemplate, filename) | Determine the final filename for an input file given an inputtemplate and a given filename.
Example::
filenameonserver = client.getinputfilename("someinputtemplate","/path/to/local/file") | 3.252345 | 3.896479 | 0.834688 |
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
try:
node = clam.common.data.parsexmlstring(node)
except:
raise Exception(node)
if node.tag != 'clamupload':
raise Exception("Not a valid CLAM uplo... | def _parseupload(self, node) | Parse CLAM Upload XML Responses. For internal use | 3.387108 | 3.142428 | 1.077863 |
if isinstance( inputtemplate, str) or (sys.version < '3' and isinstance( inputtemplate, unicode)): #pylint: disable=undefined-variable
data = self.get(project) #causes an extra query to server
inputtemplate = data.inputtemplate(inputtemplate)
elif not isinstance(inputtem... | def addinput(self, project, inputtemplate, contents, **kwargs) | Add an input file to the CLAM service. Explictly providing the contents as a string. This is not suitable for large files as the contents are kept in memory! Use ``addinputfile()`` instead for large files.
project - the ID of the project you want to add the file to.
inputtemplate - The input template y... | 2.854003 | 2.80961 | 1.0158 |
return self.addinputfile(project, inputtemplate,sourcefile, **kwargs) | def upload(self,project, inputtemplate, sourcefile, **kwargs) | Alias for ``addinputfile()`` | 6.563093 | 3.167003 | 2.072336 |
if loadmetadata is None: loadmetadata = self.loadmetadata
f = clam.common.data.CLAMOutputFile(self.url + project, filename, loadmetadata, self)
f.copy(targetfilename) | def download(self, project, filename, targetfilename, loadmetadata=None) | Download an output file | 10.054621 | 9.762186 | 1.029956 |
if self.validator is not None:
try:
valid = self.validator(value)
except Exception as e:
import pdb; pdb.set_trace()
if isinstance(valid, tuple) and len(valid) == 2:
valid, errormsg = valid
elif isinstance(v... | def validate(self,value) | Validate the parameter | 2.739767 | 2.841384 | 0.964237 |
if self.paramflag and self.paramflag[-1] == '=' or self.nospace:
sep = ''
elif self.paramflag:
sep = ' '
else:
return str(self.value)
return self.paramflag + sep + str(self.value) | def compilearg(self) | This method compiles the parameter into syntax that can be used on the shell, such as for example: --paramflag=value | 4.832417 | 3.560577 | 1.357201 |
xml = indent + "<" + self.__class__.__name__
xml += ' id="'+self.id + '"'
xml += ' name="'+xmlescape(self.name) + '"'
xml += ' description="'+xmlescape(self.description) + '"'
if self.paramflag:
xml += ' flag="'+self.paramflag + '"'
for key, v in self... | def xml(self, indent = "") | This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors | 2.327179 | 2.250708 | 1.033977 |
if self.validate(value):
#print "Parameter " + self.id + " successfully set to " + repr(value)
self.hasvalue = True
self.value = value
return True
else:
#print "Parameter " + self.id + " COULD NOT BE set to " + repr(value)
... | def set(self, value) | 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 | 3.480971 | 3.400919 | 1.023539 |
if self.denyusers:
if user in self.denyusers:
return False
if self.allowusers:
if not user in self.allowusers:
return False
return True | def access(self, user) | This method checks if the given user has access to see/set this parameter, based on the denyusers and/or allowusers option. | 2.863245 | 1.775149 | 1.61296 |
if not isinstance(node,ElementTree._Element): #pylint: disable=protected-access
node = ElementTree.parse(StringIO(node)).getroot()
if node.tag in globals():
id = ''
paramflag = ''
name = ''
description = ''
kwargs = {}
... | def fromxml(node) | Create a Parameter instance (of any class derived from AbstractParameter!) given its XML description. Node can be a string containing XML or an lxml _Element | 2.579424 | 2.516858 | 1.024859 |
value = value in (True,1) or ( (isinstance(value, str) or (sys.version < '3' and isinstance(value, unicode))) and (value.lower() in ("1","yes","true","enabled"))) #pylint: disable=undefined-variable
return super(BooleanParameter,self).set(value) | def set(self, value = True) | Set the boolean parameter | 4.660577 | 4.715487 | 0.988355 |
if self.id in postdata:
if ( (isinstance(postdata[self.id], bool) and postdata[self.id]) or postdata[self.id] == 1 or postdata[self.id].lower() in ('true','yes','enabled','1')):
return True #postdata[self.id]
else:
return False
else:
... | def valuefrompostdata(self, postdata) | 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(). It typically returns the default None when something is left unset (but that default can be overridden) | 3.101573 | 3.043565 | 1.019059 |
if isinstance(self.value,list):
value = self.delimiter.join(self.value)
else:
value = self.value
if value.find(" ") >= 0:
value = '"' + value + '"' #wrap all in quotes
#for some odd, reason this produced an error, as if we're not an instance ... | def compilearg(self) | This method compiles the parameter into syntax that can be used on the shell, such as -paramflag=value | 6.523484 | 5.639829 | 1.156681 |
xml = indent + "<" + self.__class__.__name__
xml += ' id="'+self.id + '"'
xml += ' name="'+xmlescape(self.name) + '"'
xml += ' description="'+xmlescape(self.description) + '"'
if self.paramflag:
xml += ' flag="'+self.paramflag + '"'
if self.multi:
... | def xml(self, indent = "") | This methods renders an XML representation of this parameter, along with
its selected value, and feedback on validation errors | 2.201792 | 2.103678 | 1.046639 |
if self.multi: #multi parameters can be passed as parameterid=choiceid1,choiceid2 or by setting parameterid[choiceid]=1 (or whatever other non-zero value)
found = False
if self.id in postdata:
found = True
passedvalues = postdata[self.id].split('... | def valuefrompostdata(self, postdata) | 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() | 3.151329 | 2.950451 | 1.068084 |
if self.id in postdata and postdata[self.id] != '':
return int(postdata[self.id])
else:
return None | def valuefrompostdata(self, postdata) | 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() | 3.058973 | 3.069265 | 0.996647 |
if self.validate(value):
#print "Parameter " + self.id + " successfully set to " + repr(value)
self.hasvalue = True
if isinstance(value, float):
self.value = round(value)
else:
self.value = int(value)
return Tru... | def set(self, value) | 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 | 3.229507 | 3.172936 | 1.017829 |
if self.id in postdata and postdata[self.id] != '':
return float(postdata[self.id])
else:
return None | def valuefrompostdata(self, postdata) | 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() | 3.151522 | 3.12212 | 1.009418 |
#handle shortcut
shortcutresponse = entryshortcut(credentials)
if shortcutresponse is not None:
return shortcutresponse
projects = []
user, oauth_access_token = parsecredentials(credentials)
totalsize = 0.0
if settings.LISTPROJECTS:
projects, totalsize = getprojects(us... | def index(credentials = None) | Get list of projects or shortcut to other functionality | 5.947555 | 5.832654 | 1.0197 |
postdata = flask.request.values
if 'user' in postdata:
user = postdata['user']
else:
user = 'anonymous'
if 'filename' in postdata:
filename = postdata['filename']
else:
printdebug('No filename passed')
return "{success: false, error: 'No filename passed'}... | def uploader(project, credentials=None) | 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... | 2.858329 | 2.810473 | 1.017028 |
global settingsmodule, DEBUG #pylint: disable=global-statement
printdebug("Initialising WSGI service")
globals()['settings'] = settings_module
settingsmodule = settings_module.__name__
try:
if settings.DEBUG:
DEBUG = True
setdebug(True)
except:
pass... | def run_wsgi(settings_module) | Run CLAM in WSGI mode | 5.296559 | 4.786605 | 1.106538 |
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)
usersprojects = {}
totalsize = {}
for f in glob.glob(setting... | def index(credentials=None) | Get list of projects | 3.701557 | 3.727941 | 0.992923 |
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
return settings.ROOT + "projects/" + user + '/' + project + "/" | def path(project, credentials) | Get the path to the project (static method) | 10.829957 | 8.888494 | 1.218424 |
return flask.make_response("Projects disabled, no command configured",404)
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
if not Project.validate(project):
return withheaders(flask.make_response('Invalid project ID. Note that only alpha... | def create(project, credentials): #pylint: disable=too-many-return-statements
if not settings.COMMAND | Create project skeleton if it does not already exist (static method) | 2.120827 | 2.098184 | 1.010792 |
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
printdebug("Checking if project " + project + " exists for " + user)
return os.path.isdir(Project.path(project, user)) | def exists(project, credentials) | Check if the project exists | 8.327161 | 8.294922 | 1.003887 |
index = [] #pylint: disable=redefined-outer-name
prefix = Project.path(project, user) + 'input/'
for linkf, f in globsymlinks(prefix + '.*.INPUTTEMPLATE.' + inputtemplate.id + '.*'):
seq = int(linkf.split('.')[-1])
index.append( (seq,f) )
#yield CLAMFile... | def inputindexbytemplate(project, user, inputtemplate) | Retrieve sorted index for the specified input template | 9.096061 | 8.45614 | 1.075675 |
index = [] #pylint: disable=redefined-outer-name
prefix = Project.path(project, user) + 'output/'
for linkf, f in globsymlinks(prefix + '.*.OUTPUTTEMPLATE.' + outputtemplate.id + '.*'):
seq = int(linkf.split('.')[-1])
index.append( (seq,f) )
#yield CLAMF... | def outputindexbytemplate(project, user, outputtemplate) | Retrieve sorted index for the specified input template | 9.411037 | 8.765367 | 1.073662 |
user, oauth_access_token = parsecredentials(credentials)
if not Project.exists(project, user):
return withheaders(flask.make_response("Project " + project + " was not found for user " + user,404) ,headers={'allow_origin': settings.ALLOW_ORIGIN})#404
else:
#if use... | def get(project, credentials=None) | Main Get method: Get project state, parameters, outputindex | 5.241205 | 5.200057 | 1.007913 |
user, oauth_access_token = parsecredentials(credentials)
response = Project.create(project, user)
if response is not None:
return response
msg = "Project " + project + " has been created for user " + user
if oauth_access_token:
extraloc = '?oauth_... | def new(project, credentials=None) | Create an empty project | 3.700782 | 3.690063 | 1.002905 |
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
if filename: filename = filename.replace("..","") #Simple security
if not filename or len(filename) == 0:
#Deleting all output files and resetting
Project.reset(project, u... | def deleteoutputfile(project, filename, credentials=None) | Delete an output file | 3.480506 | 3.535333 | 0.984492 |
d = Project.path(project, user) + "output"
if os.path.isdir(d):
shutil.rmtree(d)
os.makedirs(d)
else:
raise flask.abort(404)
if os.path.exists(Project.path(project, user) + ".done"):
os.unlink(Project.path(project, user) + ".done")... | def reset(project, user) | Reset system, delete all output files and prepare for a new run | 2.309744 | 2.159239 | 1.069703 |
if os.path.isfile(Project.path(project, user) + '.download'):
#make sure we don't start two compression processes at the same time
return withheaders(flask.make_response('Another compression is already running',403),headers={'allow_origin': settings.ALLOW_ORIGIN})
else:
... | def getarchive(project, user, format=None) | Generates and returns a download package (or 403 if one is already in the process of being prepared) | 2.265306 | 2.183155 | 1.03763 |
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
filename = filename.replace("..","") #Simple security
if len(filename) == 0:
#Deleting all input files
shutil.rmtree(Project.path(project, user) + 'input')
os.... | def deleteinputfile(project, filename, credentials=None) | Delete an input file | 4.642615 | 4.778199 | 0.971624 |
return response
postdata = flask.request.values
if filename == '': #pylint: disable=too-many-nested-blocks
#Handle inputsource
printdebug('Addinputfile: checking for input source' )
if 'inputsource' in postdata and postdata['inputsource']:
... | def addinputfile(project, filename, credentials=None): #pylint: disable=too-many-return-statements
printdebug('Addinputfile: Initialising' )
user, oauth_access_token = parsecredentials(credentials) #pylint: disable=unused-variable
response = Project.create(project, user)
if re... | Add a new input file, this invokes the actual uploader | 3.30555 | 3.236316 | 1.021393 |
corpora = []
for f in glob.glob(settings.ROOT + "corpora/*"):
if os.path.isdir(f):
corpora.append(os.path.basename(f))
return corpora | def corpusindex() | Get list of pre-installed corpora | 3.233406 | 2.703334 | 1.196081 |
if self.debug: print("Checking nonce " + str(nonce),file=sys.stderr)
try:
opaque, ip, expiretime = self.get(nonce) #pylint: disable=unused-variable
if expiretime < time.time():
if self.debug: print("Nonce expired",file=sys.stderr)
self.rem... | def validate(self, nonce) | Does the nonce exist and is it valid for the request? | 2.791467 | 2.649034 | 1.053768 |
t = time.time()
for noncefile in glob(self.path + '/*.nonce'):
if os.path.getmtime(noncefile) + self.expiration > t:
os.unlink(noncefile) | def cleanup(self) | Delete expired nonces | 4.862983 | 3.517981 | 1.382322 |
return {
"id": self.ID,
"steps": self.steps,
"graph_source": self.source,
"errored": self.errored
} | def json(self) | Retrun JSON representation for this run | 6.939097 | 5.390322 | 1.287325 |
self.current_run += 1
self.runs.append(RunData(self.current_run + 1)) | def new_run(self) | Creates a new RunData object and increments pointers | 5.161497 | 3.308353 | 1.560141 |
# Server needs to be up and running before starting sending POST requests
time.sleep(5)
try:
if self.remote:
logger.debug('Logfile in remote host!')
cl = client.SSHClient()
# Try to load system keys
cl.load_syst... | def follow_log(self) | Reads a logfile continuously and updates internal graph if new step is found | 3.027662 | 2.973126 | 1.018343 |
headers = {'Content-Type': 'text/event-stream'}
if info.get('when'):
info['when'] = info['when'].isoformat()
requests.post(self.base_url + '/publish', data=json.dumps(info), headers=headers) | 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. | 3.728656 | 3.860161 | 0.965933 |
if not self.analysis_finished:
return []
summary = {'times_summary': []}
for i in range(len(self.runs[self.current_run].steps) - 1):
step = self.runs[self.current_run].steps[i]
begin = parse(step['when'])
end = parse(self.runs[self.current... | def get_summary(self) | Returns some summary data for a finished analysis | 3.295964 | 3.026165 | 1.089155 |
# Defining an empty object for the response
info = {}
# This part has to be modified...
try:
# Configuring the socket
queryURL = "http://" + self.info["host"] + ":" + self.info["port"] + "/" + url
response ... | def _grabContentFromUrl(self, url) | 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. | 9.9195 | 9.667976 | 1.026016 |
command, args = parse_shell_command(cmd_line)
if len(args) >= 1:
get_workbench().get_editor_notebook().save_all_named_editors()
origcommand=command
if command == "Ev3RemoteRun":
command="Run"
if command == "Ev3RemoteDebug":
command="Debug"
... | 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.
(Debugger plugin may also use this method) | 3.968036 | 3.89906 | 1.01769 |
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()
if (not filename) or (not filename.endswith(".py")):
return
ast.parse(code)
if... | def upload_current_script() | upload current python script to EV3 | 5.979577 | 5.50267 | 1.086668 |
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 not saved and user closed file saving window, otherwise return file name.
py_file = get_workbench... | def start_current_script() | upload current python script to EV3 | 4.624648 | 4.356921 | 1.061449 |
if currentfile == None:
return
# add ".err.log" if file doesn't end with it!
if not currentfile.endswith(".err.log"):
currentfile=currentfile + ".err.log"
list = get_base_ev3dev_cmd() + ['download','--force']
list.append(currentfile)
env = os.environ.copy()
e... | def download_log(currentfile=None) | downloads log of given .py file from EV3. | 4.875645 | 4.675404 | 1.042829 |
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().get_filename(False)
if src_file is None:
return
download_log(src_file)
except Exception:
error_msg =... | def download_log_of_current_script() | download log of current python script from EV3 | 6.754589 | 6.852741 | 0.985677 |
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,
universal_newlines=True, env=env)
dlg = MySubprocessDialog(get_workbench(), p... | def cleanup_files_on_ev3() | cleanup files in homedir on EV3. | 6.040018 | 5.079956 | 1.18899 |
handler = RequestHandler(base_url, username, password, verify)
set_default_request_handler(handler)
return handler | def init(base_url, username=None, password=None, verify=True) | Initialize ubersmith API module with HTTP request handler. | 4.498727 | 3.643666 | 1.23467 |
if configFileName != None:
# Returning the path of the configuration file
if sys.platform == 'win32':
return os.path.expanduser(os.path.join('~\\', 'Deepify', configFileName))
else:
return os.path.expanduser(os.path.join('~/', '.config', 'Deepify', configFileName... | def getConfigPath(configFileName = None) | Auxiliar function to get the configuration path depending on the system. | 1.874338 | 1.795725 | 1.043778 |
if configPath == None:
# If a current.cfg has not been found, creating it by copying from default
configPath = getConfigPath("browser.cfg")
# Checking if the configuration file exists
if not os.path.exists(configPath):
try:
# Copy the data from the default folder
... | def getConfiguration(configPath = None) | Reading the configuration file to look for where the different gates are running.
:return: A json containing the information stored in the .cfg file. | 4.858446 | 4.923581 | 0.986771 |
file_handler = None
for handler in logger.handlers:
if isinstance(handler, logging.FileHandler):
file_handler = handler
new_logger = logging.getLogger(file_type + suffix)
if file_handler:
logger_file_name = path.splitext(file_handler.baseFilename)[0]
tcl_logger_... | def new_log_file(logger, suffix, file_type='tcl') | 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... | 2.371244 | 2.270342 | 1.044444 |
# make sure requested method is valid
self._validate_request_method(method)
# attempt the request multiple times
attempts = 3
for i in range(attempts):
response = self._send_request(method, data)
# handle case where ubersmith is 'updating token'... | def process_request(self, method, data=None) | Process request over HTTP to ubersmith instance.
method: Ubersmith API method string
data: dict of method arguments | 4.496202 | 4.366339 | 1.029742 |
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:
del data[fname]
return data, files or None, None | def _encode_data(data) | URL encode data. | 6.111472 | 5.753975 | 1.06213 |
str_keys_dict = OrderedDict({str(k): v for k, v in self.items()})
for k, v in str_keys_dict.items():
if isinstance(v, dict):
str_keys_dict[k] = OrderedDict({str(k1): v1 for k1, v1 in v.items()})
for k1, v1 in str_keys_dict[k].items():
... | def dumps(self, indent=1) | Returns nested string representation of the dictionary (like json.dumps).
:param indent: indentation level. | 1.697207 | 1.686409 | 1.006403 |
children = list(self.get_children(*types))
return children[0] if any(children) else None | 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). | 4.338271 | 4.249855 | 1.020805 |
if not types:
return self.objects.values()
types_l = [o.lower() for o in types]
return [o for o in self.objects.values() if o.obj_type().lower() in types_l] | def get_objects_by_type(self, *types) | 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. | 3.142547 | 3.295513 | 0.953583 |
children = self.get_objects_by_type(*types)
return children[0] if any(children) else None | def get_object_by_type(self, *types) | :param types: requested object types.
:return: the child of the specified types. | 4.884655 | 4.026373 | 1.213165 |
typed_objects = self.get_objects_by_type(*types)
for child in self.objects.values():
typed_objects += child.get_objects_by_type_in_subtree(*types)
return typed_objects | def get_objects_by_type_in_subtree(self, *types) | :param types: requested object types.
:return: all children of the specified types. | 3.221786 | 2.911388 | 1.106615 |
objects = self.get_objects_by_type(*types)
return objects if objects else self.get_children(*types) | def get_objects_or_children_by_type(self, *types) | 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. | 4.309455 | 4.713512 | 0.914277 |
objects = self.get_objects_or_children_by_type(*types)
return objects[0] if any(objects) else None | def get_object_or_child_by_type(self, *types) | 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. | 4.380672 | 4.716047 | 0.928887 |
return [o for o in self.get_objects_by_type(obj_type) if
o.get_objects_by_type(*child_types)] | def get_objects_with_object(self, obj_type, *child_types) | :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. | 3.505538 | 3.59307 | 0.975639 |
return [o for o in self.get_objects_by_type(obj_type) if
not o.get_objects_by_type(*child_types)] | def get_objects_without_object(self, obj_type, *child_types) | :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. | 2.950677 | 3.589733 | 0.821977 |
return [o for o in self.get_objects_by_type(obj_type) if o.get_attribute(attribute) == value] | def get_objects_with_attribute(self, obj_type, attribute, value) | :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. | 2.615081 | 3.234399 | 0.808522 |
if self.type.lower() == obj_type.lower():
return self
else:
if not self.parent:
return None
return self.parent.get_ancestor_object_by_type(obj_type) | 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 else None. | 2.36116 | 2.113175 | 1.117352 |
if self.parent:
self.parent.objects.pop(self.ref) | def del_object_from_parent(self) | Delete object from parent object. | 5.814055 | 4.760818 | 1.22123 |
return list(o for o in gc.get_objects() if isinstance(o, cls)) | def get_objects_of_class(cls) | :return: all instances of the requested class. | 4.811694 | 4.234142 | 1.136404 |
print("SIGHUP: stopping all clients",sys.stderr)
if myrpcserver._closed:
return
for c in set(myrpcserver.clients):
try:
c.shutdown(socket.SHUT_RDWR)
except Exception:
pass
c.close()
myrpcserver.clients.clear() | def _handle_sighup(myrpcserver, signum, unused) | Closes (terminates) all of its clients. Though keeps server running. | 4.261002 | 3.70188 | 1.151037 |
logger = logging.getLogger('extract_vcf.split_strings')
logger.debug("splitting string '{0}' with separators {1}".format(
string, separators
))
results = []
def recursion(recursive_string, separators, i=1):
if i == len(separators):
for value in recursiv... | def split_strings(string, separators) | 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'] | 2.698119 | 2.741717 | 0.984098 |
if x < 0:
sign = -1
elif x == 0:
return self._idChars[0]
else:
sign = 1
x *= sign
digits = []
while x:
digits.append(self._idChars[x % self._idCharsCnt])
x //= self._idCharsCnt
if sign < 0:
... | def _idToStr(self, x) | Convert VCD id in int to string | 2.277723 | 2.28974 | 0.994752 |
vInf = self._writer._idScope.registerVariable(sig, name, self, width,
sigType, valueFormatter)
self.children[vInf.name] = vInf
self._writer._oFile.write("$var %s %d %s %s $end\n" % (
sigType, vInf.width, vInf.vcdId, vInf.... | def addVar(self, sig: object, name: str, sigType: VCD_SIG_TYPE, width: int,
valueFormatter: Callable[["Value"], str]) | 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 | 6.872289 | 6.584656 | 1.043682 |
ch = VcdVarWritingScope(name, self._writer, parent=self)
assert name not in self.children, name
self.children[name] = ch
return ch | def varScope(self, name) | Create sub variable scope with defined name | 8.893951 | 9.399559 | 0.946209 |
'''
Wrapper for being able to launch all the threads.
:param params: We receive the parameters as a tuple.
'''
zeronet, index, total, output_folder, overwrite = params
print "[" + str(index) + "/" + str(total) + "] ", dt.datetime.now(), ":\tRecovering information from ", onion
try:
... | def multi_run_wrapper(params) | Wrapper for being able to launch all the threads.
:param params: We receive the parameters as a tuple. | 6.003582 | 5.245594 | 1.1445 |
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.output_folder)
# Using threads in a pool if we are not runnin... | def main(args) | Main function. | 5.568028 | 5.520526 | 1.008605 |
info =configuration.getConfiguration()
try:
# This returns only the parameters needed by each wrapper. E. g., for Tor:
# {
# "host" : "127.0.0.1"
# "port" : "9150"
# }
return info[self.name]
... | def _getConfiguration(self) | Method that abstracts the extraction of grabbing the configuration.
:return: the applicable configuration settings. | 8.710578 | 9.151022 | 0.951869 |
try:
domain = re.findall( self.domainRegexp, url )[0]
except Exception, e:
errMsg = "ERROR. Something happened when trying to find the domain from <" + url + ">. Are you sure that the following regular expression matches a domain in the url provided?\n\t" + self.domainRe... | def getDomainFromUrl(self, url) | Extracting the domain from the URL.
:return: domain as a string. | 5.065819 | 5.557845 | 0.911472 |
aux = {}
aux["headers"] = {}
aux["content"] = ""
for i, line in enumerate(content.splitlines()):
if i == 0:
aux["procotol"] = line.split()[0]
aux["code"] = line.split()[1]
elif line != "":
header = line.spl... | def _createDataStructure(self, content) | 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. | 4.630115 | 4.353547 | 1.063527 |
# Defining an empty object for the response
response = {}
# This part has to be modified...
try:
import urllib2
# Grabbing the data
data = urllib2.urlopen(url).read()
# Processing the data as expectesd
... | def _grabContentFromUrl(self, url) | 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. | 11.697073 | 11.548396 | 1.012874 |
# Defining an empty object for the response
response = {}
try:
# This receives only the parameters needed by this Tor Wrapper:
# {
# "host" : "127.0.0.1"
# "port" : "9150"
# }
self.info = self._getConfi... | def getResponse(self, url) | Public method that wraps the extraction of the content.
:param url: The resource to be processed.
:return: The response in a Json format. | 6.027878 | 5.956806 | 1.011931 |
parsed_url = urlsplit(url)
parsed_qs = parse_qsl(parsed_url.query, True)
if isstr(query_string):
parsed_qs += parse_qsl(query_string)
elif isdict(query_string):
for item in list(query_string.items()):
if islist(item[1]):
for val in item[1]:
... | def append_qs(url, query_string) | 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'... | 1.920721 | 1.829213 | 1.050026 |
data_iter = None
if isdict(data):
data_iter = list(data.items())
elif islist(data):
data_iter = data
if data_iter:
for i, (key, value) in enumerate(data_iter):
if isinstance(value, text_type):
# try to convert to str
try:
... | def urlencode_unicode(data, doseq=0) | urllib.urlencode can't handle unicode, this is a hack to fix it. | 2.874329 | 2.789516 | 1.030404 |
is_root = prefix_key is None
prefix_key = prefix_key if prefix_key else ''
if islist(data):
data_iter = data if is_root else enumerate(data)
new_data = [] if is_root else {}
elif isdict(data):
data_iter = list(data.items())
new_data = {}
else:
raise Type... | def to_nested_php_args(data, prefix_key=None) | 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. | 2.155166 | 2.212481 | 0.974095 |
if disposition:
params = [param.strip() for param in disposition.split(';')[1:]]
for param in params:
if '=' in param:
name, value = param.split('=', 1)
if name == 'filename':
return value.strip('"') | 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 | 2.158391 | 2.209215 | 0.976994 |
return ' '.join(' '.join(['-' + k, tcl_str(str(v))]) for k, v in arguments.items()) | def get_args_pairs(arguments) | :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. | 8.808999 | 8.950957 | 0.98414 |
if not within_tcl_str:
tcl_list = tcl_str(tcl_list)
return tcl_interp_g.eval('join ' + tcl_list + ' LiStSeP').split('LiStSeP') if tcl_list else [] | def tcl_list_2_py_list(tcl_list, within_tcl_str=False) | 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 | 7.546676 | 7.805982 | 0.966781 |
py_list_str = [str(s) for s in py_list]
return tcl_str(tcl_interp_g.eval('split' + tcl_str('\t'.join(py_list_str)) + '\\t')) | def py_list_to_tcl_list(py_list) | 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. | 7.05436 | 6.985801 | 1.009814 |
# Some operations (like take ownership) may take long time.
con_command_out = self._con.send_cmd(command, timeout=256)
if 'ERROR_SEND_CMD_EXIT_DUE_TO_TIMEOUT' in con_command_out:
raise Exception('{} - command timeout'.format(command))
command = command.replace('\\', ... | def eval(self, command) | @summary: Evaluate Tcl command.
@param command: command to evaluate.
@return: command output. | 4.353744 | 4.385342 | 0.992795 |
if self.logger.handlers:
self.logger.debug(command.decode('utf-8'))
if self.tcl_script:
self.tcl_script.info(command)
self.rc = self.tcl_interp.eval(command)
if self.logger.handlers:
self.logger.debug('\t' + self.rc.decode('utf-8'))
r... | def eval(self, command) | 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. | 3.781707 | 3.337211 | 1.133194 |
# Defining an empty object for the response
response = {}
# This part has to be modified...
try:
# Configuring the socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, self.info["host"], int(self.info["port"]), True)
... | def _grabContentFromUrl(self, url) | 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. | 5.711375 | 5.687764 | 1.004151 |
'''append change from VCD file signal data series'''
self.idcode2series[vcdId].append((self.now, value)) | def value_change(self, vcdId, value) | append change from VCD file signal data series | 34.550568 | 10.175383 | 3.395505 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.